(转)Axis2 附件传输

本文来自百度文库 代码和配置文件都能调通,采用比较好的方式,自己不写了。

 

听说axis传输文件过5M就嗝屁。要用attachment形式传输,故研究之。

官方参考:http://axis.apache.org/axis2/java/core/docs/mtom-guide.html

 

1.工作环境
IDE: Eclipse 3.1.2
jdk: jdk1.5.0_04
Tomcat: apache-tomcat-5.0.28
AXIS2:1.0(war版本和bin版本)
 
2.实现
   在Eclipse新建一个动态web工程,在WEB-INF\lib下加入axis2所需的jar包。
本例的是一个系统的用户上传下载图片格式文件的例子,每次上传出携带附件外,还包括文件名, 文件类型。此webservice实现的2个功能就是upload, download.
   AXIS2的webservice发布的时候是打包成xxx.aar发布的,xxx.aar展开后的目录结构为
 --
    --META-INF
       services.xml
    --包含server端实现的class( 目录跟package是一样的结构)
 
3.服务器端FileTransferServer.java
package sample;
 
import org.apache.axiom.attachments.utils.IOUtils;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;
import org.apache.axis2.AxisFault;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
 
import java.util.Iterator;
 
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
 
public class FileTransferServer {
       public static final String TMP_PATH = "D:/temp";
 
       public OMElement upload(OMElement element) throws Exception {
              OMElement _fileContent = null;//文件内容
              OMElement _fileName = null;//文件名
              OMElement _fileType = null;//文件类型
              System.out.println("The element for upload: " + element);
              for (Iterator _iterator = element.getChildElements(); _iterator.hasNext();) {
                     OMElement _ele = (OMElement) _iterator.next();
                     if (_ele.getLocalName().equalsIgnoreCase("fileContent")) {
                            _fileContent = _ele;
                     }
                     if (_ele.getLocalName().equalsIgnoreCase("fileName")) {
                            _fileName = _ele;
                     }
                     if (_ele.getLocalName().equalsIgnoreCase("fileType")) {
                            _fileType = _ele;
                     }
              }
 
              if (_fileContent == null || _fileType == null) {
                     throw new AxisFault("Either Image or FileName is null");
              }
 
              OMText binaryNode = (OMText) _fileContent.getFirstOMChild();
              String fileName = _fileName.getText();
              String fileType = _fileType.getText();
              String storeDir = TMP_PATH + "/" + "tempTest";
              File dir = new File(storeDir);
              if (!dir.exists()) {
                     dir.mkdir();
              }
              String filePath = storeDir + "/" + fileName + "." + fileType;
              File uploadFile = new File(filePath);
              if (uploadFile.exists()) {
                     filePath = storeDir + "/" + fileName + "(1)" + "." + fileType;
                     uploadFile = new File(filePath);
              }
 
              // Extracting the data and saving
              DataHandler actualDH;
              actualDH = (DataHandler) binaryNode.getDataHandler();
 
              FileOutputStream imageOutStream = new FileOutputStream(uploadFile);
              InputStream is = actualDH.getInputStream();
              imageOutStream.write(IOUtils.getStreamAsByteArray(is));
              // setting response
              OMFactory fac = OMAbstractFactory.getOMFactory();
              OMNamespace ns = fac.createOMNamespace("http://example.org/filedata",
                            "fd");
              OMElement ele = fac.createOMElement("response", ns);
              ele.setText("true");
              return ele;
       }
 
       public OMElement download(OMElement element) throws Exception {
              System.out.println("The element for download: " + element);
              OMElement _userName = null;
              OMElement _fileName = null;
              OMElement _fileType = null;
              for (Iterator _iterator = element.getChildElements(); _iterator
                            .hasNext();) {
                     OMElement _ele = (OMElement) _iterator.next();
                     if (_ele.getLocalName().equalsIgnoreCase("userName")) {
                            _userName = _ele;
                     }
                     if (_ele.getLocalName().equalsIgnoreCase("fileName")) {
                            _fileName = _ele;
                     }
                     if (_ele.getLocalName().equalsIgnoreCase("fileType")) {
                            _fileType = _ele;
                     }
              }
              String userName = _userName.getText();
              String fileName = _fileName.getText();
              String fileType = _fileType.getText();
              String filePath = TMP_PATH + "/" + userName + "/" + fileName + "."
                            + fileType;
              System.out.println("The filePath for download: " + filePath);
              FileDataSource dataSource = new FileDataSource(filePath);
              DataHandler expectedDH = new DataHandler(dataSource);
              OMFactory fac = OMAbstractFactory.getOMFactory();
              OMNamespace ns = fac.createOMNamespace("http://example.org/filedata",
                            "fd");
              OMText textData = fac.createOMText(expectedDH, true);
              OMElement ele = fac.createOMElement("response", ns);
              ele.addChild(textData);
              return ele;
       }
}
 
4.services.xml
<?xml version="1.0" encoding="UTF-8"?>
<service name="FileOperation">
    <description>
        This is a sample Web Service with two operations,echo and ping.
    </description>
    <parameter name="ServiceClass" locked="false">sample.FileTransferServer</parameter>
    <operation name="upload">
        <actionMapping>urn:upload</actionMapping>
        <messageReceiver class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
    </operation>
      <operation name="download">
        <actionMapping>urn:download</actionMapping>
        <messageReceiver class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
    </operation>
</service>
 
将这两个文件打包并部署到Tomcat上(略)。
 
5.测试
FileTransferClient.java
package sample;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
 
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
 
import org.apache.axiom.attachments.utils.IOUtils;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;
import org.apache.axiom.soap.SOAP11Constants;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
 
public class FileTransferClient {
   private static EndpointReference targetEPR =
 new EndpointReference("http://127.0.0.1:8080/axis2/services/FileOperation");
  
   public static boolean upload(String fileName, File file, String fileType) {
     try {
      OMElement data = buildUploadEnvelope(fileName, file, fileType);
      Options options = buildOptions();
      ServiceClient sender = new ServiceClient();
      sender.setOptions(options);
      System.out.println("The data in method upload: "+data);
      OMElement ome = sender.sendReceive(data);
      System.out.println("Convert the data to element in method upload: "+ome);
      String b = ome.getText();
      return Boolean.parseBoolean(b);
     }
     catch(Exception e) {
       e.printStackTrace();
     }
     return false;
   }
  
   public static boolean download(String userName, String fileName, String fileType) {
     try {
       OMElement data = buildDownloadEnvelope(userName, fileName, fileType);
       Options options = buildOptions();
       ServiceClient sender = new ServiceClient();
       sender.setOptions(options);
       System.out.println("The data in method download: "+data);
       OMElement ome = sender.sendReceive(data);
       System.out.println("Convert the data to element in method download: "+ome);
       OMText binaryNode = (OMText) ome.getFirstOMChild();
       binaryNode.setOptimize(true); //必须加此句,否则会出现ContentID is null的异常!
       DataHandler actualDH = (DataHandler) binaryNode.getDataHandler();
       FileOutputStream imageOutStream = new FileOutputStream("D:/userTemp/xx.gif");
       InputStream is = actualDH.getInputStream();
       imageOutStream.write(IOUtils.getStreamAsByteArray(is));
       return true;
      }
      catch(Exception e) {
        e.printStackTrace();
      }
     return false;
   }
  
   private static OMElement buildUploadEnvelope(String fileName, File file, String fileType) {
     DataHandler expectedDH;
     OMFactory fac = OMAbstractFactory.getOMFactory();
     OMNamespace omNs = fac.createOMNamespace("http://example.org/filedata", "fd");
     OMElement data = fac.createOMElement("upload", omNs);
     OMElement fileContent = fac.createOMElement("fileContent", omNs);
     FileDataSource dataSource = new FileDataSource(file);
     expectedDH = new DataHandler(dataSource);
     OMText textData = fac.createOMText(expectedDH, true);
     fileContent.addChild(textData);
     OMElement _fileName = fac.createOMElement("fileName", omNs);
     _fileName.setText(fileName);
     OMElement _fileType = fac.createOMElement("fileType", omNs);
     _fileType.setText(fileType);
     data.addChild(_fileName);
     data.addChild(_fileType);
     data.addChild(fileContent);
     return data;
   }
  
   private static OMElement buildDownloadEnvelope(String userName, String fileName, String fileType) {
     OMFactory fac = OMAbstractFactory.getOMFactory();
     OMNamespace omNs = fac.createOMNamespace("http://example.org/filedata", "fd");
     OMElement data = fac.createOMElement("download", omNs);
     OMElement _userName = fac.createOMElement("userName", omNs);
     _userName.setText(userName);
     OMElement _fileName = fac.createOMElement("fileName", omNs);
     _fileName.setText(fileName);
     OMElement _fileType=fac.createOMElement("fileType", omNs);
     _fileType.setText(fileType);
     data.addChild(_userName);
     data.addChild(_fileName);
     data.addChild(_fileType);
     return data;
   }
   private static Options buildOptions() throws AxisFault {
     Options options = new Options();
     options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
     options.setTo(targetEPR);
     // enabling MTOM in the client side
     options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
     options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
     return options;
   }
   public static void main(String agrs[]) {
     String file = "D:/userTemp/ya.gif";
     String fn = "testUser";
     String ft="gif";
     boolean rtv = upload(fn,new File(file),ft);
     System.out.println("is upload success: "+rtv);
     String un="zj";
     String downfn="1";
     if(download(un,downfn,ft)){
            System.out.println("download success.");
     }
     else System.out.println("download fail.");
     System.out.println("Client main end.");
   }
}
 
6.结果
察看soap消息,我们可以发现
<fd:upload xmlns:fd="http://example.org/filedata">
<fd:fileName>testUser</fd:fileName>
<fd:fileType>gif</fd:fileType>
<fd:fileContent>RHQMLJJ4/AMZkEBAEAOw(省略部分2进制代码)</fd:fileContent>
</fd:upload>
 
Convert the data to element in method upload:
<fd:response xmlns:fd=http://example.org/filedata xmlns:tns="http://ws.apache.org/axis2">true</fd:response>
 
The data in method download:
<fd:download xmlns:fd="http://example.org/filedata">
<fd:userName>zj</fd:userName>
<fd:fileName>1</fd:fileName>
<fd:fileType>gif</fd:fileType>
</fd:download>
 
Convert the data to element in method download:
<fd:response xmlns:fd="http://example.org/filedata" xmlns:tns="http://ws.apache.org/axis2">
eIqGRwjkQAAAOw==(省略部分2进制代码)
</fd:response>
 
7.代码分析
   利用Axis2的Mtom发送附件应用了builder模式。要向一个webserive 发送请求,首先就要构建一个请求的Envelope,Axis2构建Envelope的时候是利用的Axis2的AXIOM api(就是axis2的java object和xml的映射处理机制),其编程模式和DOM差不多的.看这一段:
private static OMElement buildUploadEnvelope(String mailboxnum, short greetingType, File file, String FileType) {
DataHandler expectedDH;
     OMFactory fac = OMAbstractFactory.getOMFactory();
...
return data;
}
这一段其实是构建的data对像是这样一段xml的java object代表:
<fd:upload xmlns:fd="http://example.org/filedata">
<fd:fileName>testUser</fd:fileName>
<fd:fileType>gif</fd:fileType>
<fd:fileContent>RHQMLJJ4/AMZkEBAEAOw(省略部分2进制代码)</fd:fileContent>
</fd:upload>
其中的Dwvc2VydmljZT4NCjwvZGVwbG95bWVudD4NCg0K是要传送的文件的内容代表,至于什么编码,我没有深究。注意这一句:
OMElement data = fac.createOMElement("upload", omNs);
这里的“upload”参数对应的是webservice的一个操作的名称,这个操作的名称是跟webservice的server端实现类的方法名和services.xml的所定义的
<operationname="upload">
   <actionMapping>urn:upload</actionMapping>
   <messageReceiverclass="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
</operation>
要一致的。
再看看这一段,
 private static Options buildOptions() {
     Options options = new Options();
     ...
     return options;
   }
这里构建的Options对象,顾名思义就是调用webservice的相应的选项:比如这里就指定了Soap协议为1.1 版,指定了所请求的service 的EPR(就是地址),声明在client应用MTOM指定传输协议为HTTP。
构建好要传送的data和options后,所执行的代码为:
ServiceClient sender = new ServiceClient();
//设定选项
sender.setOptions(options);
//打印要传送的数据,为一段xml
System.out.println(data);
//传送数据,得到返回值
OMElement ome = sender.sendReceive(data);
//打印返回值,为一段xml
System.out.println(ome);
//析取返回值中的数据
String b = ome.getText();
//返回
return Boolean.parseBoolean(b);
可以发现,server端和client的中间传递数据都是通过      org.apache.axiom.om.OMElement对象的,这个对象是一段xml的java 对象映射。

axis2 发送附件 axis2 发送附件axis2 发送附件axis2 发送附件axis2 发送附件 立即下载

相关推荐

axis2_demo实战 复杂对象传输 文件传输

axis2_demo实战 复杂对象传输 文件传输 webservice实例 传List ,传Object 传对象,传文件 各种实战。 有备注说明whdd

Axis2中的webservice服务器端与客户端之间的大数据量的对象传递方法

[code="java"] public Raster2D dataView(String path) throws Exception{ Raster2D raster2D=RasterReadWrite.read(path); System.out.println(path); // Raster2D raster2D=new...

隔壁老瓦的专栏 974

AD(AltiumDesigner)封装导入allegro生成allegro封装

AD(AltiumDesigner)封装导入allegro生成allegro封装 貌似PCB的封装问题是一个无尽话题,为了简单我总是想找捷径(主要还是太懒了),因为也是近期才开始学习使用allegro进行PCB设计,在最近的一个设计中,很多器件封装allegro中都没有,一个一个画感觉很费时间,但是在AD(AltiumDesigner)的封装库中是有的,于是便想着AD的封装库能不能倒入到alleg...

yangh2560的博客 2万+

axis2、CXF webservice传对象及附件

axis2、CXF 传对象及附件

浩的专栏 1152

平均电流控制模式BUCK变换器的环路设计

引言 电压模式的BUCK变换器存在的常见缺点: 1、在没有前馈补偿的时候,对输入源的跳动响应较慢; 2、在不加入电感电流控制的时候,由于不直接对电感电流进行采样,因此不能实时的控制电感电流,有可能在某些负载极端变化时,系统直接奔溃; 3、LC组成的二阶系统存在谐振点,谐振峰随负载变化而变化,不容易做到完全消除; 峰值电流模式的BUCK变换器存在的常见缺点: 1、占空比大于50%时,存在次谐波震荡的问题,需要添加斜坡补偿已解决该问题; 2、抗干扰能力较差; 3、峰值电流和平均电流间存在误差,不适合做PFC线路

c007106333的博客 1万+

手把手教你学Simulink——基于Simulink的变换器老化预测与数字孪生(Digital Twin)

这不仅是技术的演进,更是从“事后救火”到“事前预言”的降维打击。:通过本文的实战演练,你不仅掌握了功率变换器“电气-热-老化”多物理场耦合的建模哲学,更深刻领悟了如何将高深的随机过程(粒子滤波)降维成可落地、可量产的工程工具;:起初,由于数据量少,粒子滤波器预测的剩余寿命(RUL)置信区间(95%)非常宽泛(如 1000~2000小时)。在工业4.0与智能制造的浪潮下,功率变换器(如光伏逆变器、车载OBC、服务器电源)不再是孤立的硬件,而是具备“自我感知”与“寿命预知”的智能节点。

MHD0815的博客 299

使用Axis2传输附件(AXIS2 MTOM)

本文介绍如何使用Axis2传递附件。 author: ZJ 07-5-7 Blog: [url]http://zhangjunhd.blog.51cto.com/[/url] 1.工作环境 IDE: Eclipse 3.1.2 jdk: jdk1.5.0_04 Tomcat: apache-tomcat-5.0.28 AXIS2:1.0(war版本和bin...

weixin_33985679的博客 234

Maven的下载安装配置教程(详细图文)

目录 一、简单了解一下什么是Maven 二、maven的下载 三、maven的安装 四、maven的环境变量配置 五、setting文件配置 六、开发工具配置Maven 一、简单了解一下什么是Maven Maven就是一款帮助程序员构建项目的工具,我们只需要告诉Maven需要哪些Jar 包,它会帮助我们下载所有的Jar,极大提升开发效率。 1.Maven翻译为“专家“, ”内行”的意思,是著名Apache公司下基于Java开发的开源项目。 2.Maven项目对象模型(POM)是一..

bakelFF的博客 12万+

Axis2用法:soap消息携带附件

1、附件类File2Attachmentssoap消息携带附件时,soap消息需要携带符合axis2规范的文件。那么我们需要将普通的文件转化成符合axis2的附件对象的类Attachments。这里主要提供一个File类型的对象转化成Attachments类型的对象的方法。(1)分装过程一、判断输入文件是否是标准文件,如果非标准文件直接返回null。二、根据文件后缀,获取文件...

weixin_34259232的博客 238

分布式协作方案:OpenClaw多节点部署与设备互联

主从架构或对等架构服务发现与注册机制负载均衡策略选择分布式任务队列优先级调度失败重试机制WebSocket实时通信数据同步引擎冲突解决策略健康检查机制故障自动转移数据复制与恢复通过分布式部署,OpenClaw可以支撑更大规模的业务场景,提供更稳定可靠的AI助手服务。在下一篇文章中,我们将深入探讨安全与权限管理的精细化策略。

gaoxiang_120的专栏 371

【TCAD】Sentaurus 中的“陷阱trap”仿真设置

允许使用有限的数据集名称 SFactor 规范,例如 DeepLevels , xMoleFraction , 和 yMoleFraction (从兴奋剂档案中读取) eTrappedCharge 和 hTrappedCharge (从指定的文件中读取 DevFields 在 File 部分)或 PMI 用户字段 PMIUserField0...10 (从指定的文件中读取 PMIUserFields 在 File 部分)。给定的陷阱截面 eNeutral 陷阱是多种多样的 Xsec 项目参数。

荷塘阅色 1308

如何使用Axis传送附件

使用Axis传送附件有两种方式:1. 将你要传送的文件封装在DataHandler中,然后将DataHandler对象或DataHandler数组(多个文件传送的时候)作为客户端调用函数的参数(从客户端上传文件到服务器)Axis服务的返回类型(从服务器端下载文件到客户端)进行传输。2. 还有一种方式是直接修改soap信封的内容,将附件信息加到soap信封中发送。这里我们只讨论第一种方法,因为它实现

波波熊的专栏 1636

【STK】手把手教你利用STK进行覆盖分析02-生成详细分析报告和图表

这篇文章主要针对上一篇文章中最后的案例1进行进一步的说明,详细介绍我们可以生成哪些结论性的成果。STK的Coverage模块的生成结果包括分析报告和图表两种样式,每种样式还分为动态和静态两种,也就是说,我们做完一个STK覆盖场景的仿真后,一般可以生成静态分析报告、动态分析报告、静态分析图表和动态分析图表这4种形式的分析成果,下面进行详细介绍。我们在选择了想要分析的区域或者点后,就可以利用CovDef生成分析报告了,覆盖定义的分析报告分为静态报告和动态报告两种,下面分析进行介绍: 首先我们先在左侧目标浏览器C

weixin_44184852的博客 3443

Axis2 附件传输 样例 解读

axis2 的客户端发送带附件的过程如下 [code="java"] //设置options Options options = new Options(); options.setTo(targetEPR); options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE...

dingchd0212的博客 331

遗传算法(Genetic Algorithm)详解与实现

遗传算法(Genetic Algorithm, GA)是受自然进化原理启发的一系列搜索算法。通过模仿自然选择和繁殖的过程,遗传算法可以为涉及搜索、优化和学习的各种问题提供高质量的解决方案。同时,它们类似于自然进化,因此遗传算法可以克服传统搜索和优化算法遇到的一些障碍,尤其是对于具有大量参数和复杂数学表示形式的问题。

盼小辉丶的博客 24万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

java soap附件_Axis2用法:soap消息携带附件

1、附件类File2Attachmentssoap消息携带附件时,soap消息需要携带符合axis2规范的文件。那么我们需要将普通的文件转化成符合axis2的附件对象的类Attachments。这里主要提供一个File类型的对象转化成Attachments类型的对象的方法。(1)分装过程一、判断输入文件是否是标准文件,如果非标准文件直接返回null。二、根据文件后缀,获取文件内容的类型。默认为tx...

weixin_39618275的博客 459

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

WebService(Axis)服务器端返回附件

在webservice的开发中难免会遇到传输附件的问题,如电信C网的彩信业务开发。通常的作法是client调用server端方法时携带附件,server端得到附件。但是server端返回消息时携带附件似乎用的比较少,而且网上关于这方面的资料也不多,经过几天的尝试,可以在server端返回附件,贴出来给大家分享一下。我是用axis开发的程序,所以针对axis做一些详解,希望用别的框架的大家多多交

小筑听风的专栏 2928

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Axis2介绍

Web Service是现在最适合实现SOA的技术,而Axis2是实现Web Service的一种技术框架(架构)。 目录 Axis2 主要特点 方式比较 Building the service using AXIOM Generating the service using ADB Generating the service using XMLBean Gen

screensky的专栏 753

如何使用Axis传送附件[原]

使用Axis传送附件有两种方式: 1. 将你要传送的文件封装在DataHandler中,然后将DataHandler对象或DataHandler数组(多个文件传送的时候)作为客户端调用函数的参数(从客户端上传文件到服务器)Axis服务的返回类型(从服务器端下载文件到客户端)进行传输。 2. 还有一种方式是直接修改soap信封的内容,将附件信息加到soap信封中发送。 这里我们只讨论第一种方法,因为

猴子腿儿的Blog 4265

通向架构师的道路(第十二天)之Axis2 Web Service(三)

一、SOAPIn Axis2 在前两天的教程中,我们学习到了用Axis2如何进行复杂数据、简单数据进行传输。 正如我在前一天教程中所说,在web service的世界里,一切都是基于SOAP的,因此在今天我们将学习Axis2中的SOAP特性。 今天的课程将用3个例子来完成即: 1)  客户端与服务端使用SOAP进行通讯 2)  服务端将Exception以SOAPFault的形式抛给客户

虎子专栏 6032

axis2介绍1

一、全局配置axis2.xml文件配置全局信息需要编写axis2.xml文件,在axis2.xml文件中,顶级元素有六个,它们分别为:ParameterTransport ReceiverTransport SenderPhase OrderModule ReferencesLi

HeiBoyYang---->It Life 2274

Axis2调用使用DataHandler传递字节数组

在Web Service开发中,对于数据量不大的二进行类型经常需要传递字节数组(大文件使用Soap附件方式,见参考),对于Axis2,客户端调用的方式可参见如下示例(注意匿名类DataHandler的使用):public static void main(String[] args) throws Exception { try { NonCopyServerStub nonCo

李燕军的专栏 7730

使用axis2传输附件

服务端Service文件: [code="java"] import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import javax.activation.DataHandler; public class FileService { // 使...

雕刻时间的专栏 339
上一篇: 常用T-sql
下一篇: Andriod开发
O2AtomLife
博客等级 码龄19年 2粉丝 82原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值