Debian Codegraph @

samples/attachments/EchoAttachment.java

raw
1 /*
2 * Copyright 2001-2004 The Apache Software Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package samples.attachments;
18
19
20 import org.apache.axis.AxisFault;
21 import org.apache.axis.client.Call;
22 import org.apache.axis.client.Service;
23 import org.apache.axis.encoding.XMLType;
24 import org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory;
25 import org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory;
26 import org.apache.axis.transport.http.HTTPConstants;
27 import org.apache.axis.utils.Options;
28
29 import javax.activation.DataHandler;
30 import javax.activation.FileDataSource;
31 import javax.xml.namespace.QName;
32 import javax.xml.rpc.ParameterMode;
33 import javax.xml.soap.AttachmentPart;
34 import javax.xml.soap.MessageFactory;
35 import javax.xml.soap.SOAPBody;
36 import javax.xml.soap.SOAPBodyElement;
37 import javax.xml.soap.SOAPConnection;
38 import javax.xml.soap.SOAPConnectionFactory;
39 import javax.xml.soap.SOAPEnvelope;
40 import javax.xml.soap.SOAPMessage;
41 import javax.xml.soap.SOAPPart;
42 import java.io.File;
43 import java.net.URL;
44 import java.util.Hashtable;
45 import java.util.Iterator;
46 import java.util.ListIterator;
47 import java.util.Vector;
48
49
50 /**
51 *
52 * @author Rick Rineholt
53 */
54
55 /**
56 * An example of sending an attachment via RPC.
57 * This class has a main method that beside the standard arguments
58 * allows you to specify an attachment that will be sent to a
59 * service which will then send it back.
60 *
61 */
62 public class EchoAttachment {
63
64 Options opts = null;
65
66
67 public EchoAttachment(Options opts) {
68 this.opts = opts;
69 }
70
71 /**
72 * This method sends a file as an attachment then
73 * receives it as a return. The returned file is
74 * compared to the source.
75 * @param The filename that is the source to send.
76 * @return True if sent and compared.
77 */
78 public boolean echo(final boolean doTheDIME, String filename) throws Exception {
79
80 //javax.activation.MimetypesFileTypeMap map= (javax.activation.MimetypesFileTypeMap)javax.activation.MimetypesFileTypeMap.getDefaultFileTypeMap();
81 //map.addMimeTypes("application/x-org-apache-axis-wsdd wsdd");
82
83
84 //Create the data for the attached file.
85 DataHandler dhSource = new DataHandler(new FileDataSource(filename));
86
87 Service service = new Service();
88
89 Call call = (Call) service.createCall();
90
91
92 call.setTargetEndpointAddress(new URL(opts.getURL())); //Set the target service host and service location,
93
94 call.setOperationName(new QName("urn:EchoAttachmentsService", "echo")); //This is the target services method to invoke.
95
96 QName qnameAttachment = new QName("urn:EchoAttachmentsService", "DataHandler");
97
98 call.registerTypeMapping(dhSource.getClass(), //Add serializer for attachment.
99 qnameAttachment,
100 JAFDataHandlerSerializerFactory.class,
101 JAFDataHandlerDeserializerFactory.class);
102
103
104 call.addParameter("source", qnameAttachment,
105 ParameterMode.IN); //Add the file.
106
107 call.setReturnType(qnameAttachment);
108
109 call.setUsername(opts.getUser());
110
111 call.setPassword(opts.getPassword());
112
113 if (doTheDIME)
114 call.setProperty(call.ATTACHMENT_ENCAPSULATION_FORMAT,
115 call.ATTACHMENT_ENCAPSULATION_FORMAT_DIME);
116
117
118 Object ret = call.invoke(new Object[]{
119 dhSource
120 }
121 ); //Add the attachment.
122
123 if (null == ret) {
124 System.out.println("Received null ");
125 throw new AxisFault("", "Received null", null, null);
126 }
127
128 if (ret instanceof String) {
129 System.out.println("Received problem response from server: " + ret);
130 throw new AxisFault("", (String) ret, null, null);
131 }
132
133 if (!(ret instanceof DataHandler)) {
134 //The wrong type of object that what was expected.
135 System.out.println("Received problem response from server:" +
136 ret.getClass().getName());
137 throw new AxisFault("", "Received problem response from server:" +
138 ret.getClass().getName(), null, null);
139
140 }
141 //Still here, so far so good.
142 //Now lets brute force compare the source attachment
143 // to the one we received.
144 DataHandler rdh = (DataHandler) ret;
145
146 //From here we'll just treat the data resource as file.
147 String receivedfileName = rdh.getName();//Get the filename.
148
149 if (receivedfileName == null) {
150 System.err.println("Could not get the file name.");
151 throw new AxisFault("", "Could not get the file name.", null, null);
152 }
153
154
155 System.out.println("Going to compare the files..");
156 boolean retv = compareFiles(filename, receivedfileName);
157
158 java.io.File receivedFile = new java.io.File(receivedfileName);
159
160 receivedFile.delete();
161
162 return retv;
163 }
164
165 /**
166 * This method sends all the files in a directory.
167 * @param The directory that is the source to send.
168 * @return True if sent and compared.
169 */
170 public boolean echoDir(final boolean doTheDIME, String filename) throws Exception {
171 boolean rc = true;
172
173
174 DataHandler[] attachments = getAttachmentsFromDir(filename); //Get the attachments from the directory.
175
176 if (attachments.length == 0) {
177 throw new java.lang.IllegalArgumentException(
178 "The directory \"" + filename + "\" has no files to send.");
179 }
180
181 Service service = new Service(); //A new axis Service.
182
183 Call call = (Call) service.createCall(); //Create a call to the service.
184
185 /*Un comment the below statement to do HTTP/1.1 protocol*/
186 //call.setScopedProperty(MessageContext.HTTP_TRANSPORT_VERSION,HTTPConstants.HEADER_PROTOCOL_V11);
187 Hashtable myhttp = new Hashtable();
188 myhttp.put("dddd", "yyy"); //Send extra soap headers
189 myhttp.put("SOAPAction", "dyyy");
190 myhttp.put("SOAPActions", "prova");
191
192 /*Un comment the below to do http chunking to avoid the need to calculate content-length. (Needs HTTP/1.1)*/
193 //myhttp.put(HTTPConstants.HEADER_TRANSFER_ENCODING, HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED);
194
195 /*Un comment the below to force a 100-Continue... This will cause httpsender to wait for
196 * this response on a post. If HTTP 1.1 and this is not set, *SOME* servers *MAY* reply with this anyway.
197 * Currently httpsender won't handle this situation, this will require the resp. which it will handle.
198 */
199 //myhttp.put(HTTPConstants.HEADER_EXPECT, HTTPConstants.HEADER_EXPECT_100_Continue);
200 call.setProperty(HTTPConstants.REQUEST_HEADERS, myhttp);
201
202 call.setTargetEndpointAddress(new URL(opts.getURL())); //Set the target service host and service location,
203
204 call.setOperationName(new QName("urn:EchoAttachmentsService", "echoDir")); //This is the target services method to invoke.
205
206 QName qnameAttachment = new QName("urn:EchoAttachmentsService", "DataHandler");
207
208 call.registerTypeMapping(attachments[0].getClass(), //Add serializer for attachment.
209 qnameAttachment,
210 JAFDataHandlerSerializerFactory.class,
211 JAFDataHandlerDeserializerFactory.class);
212
213 call.addParameter("source", XMLType.SOAP_ARRAY, // new XMLType(qnameAttachment),
214 ParameterMode.IN); //Add the file.
215
216 call.setReturnType(XMLType.SOAP_ARRAY); // new XMLType(qnameAttachment));
217
218 call.setUsername(opts.getUser());
219
220 call.setPassword(opts.getPassword());
221
222 if (doTheDIME)
223 call.setProperty(call.ATTACHMENT_ENCAPSULATION_FORMAT,
224 call.ATTACHMENT_ENCAPSULATION_FORMAT_DIME);
225
226 Object ret = call.invoke(new Object[]{
227 attachments
228 }
229 ); //Add the attachment.
230
231 if (null == ret) {
232 System.out.println("Received null ");
233 throw new AxisFault("", "Received null", null, null);
234 }
235
236 if (ret instanceof String) {
237 System.out.println("Received problem response from server: " + ret);
238 throw new AxisFault("", (String) ret, null, null);
239 }
240
241 if (!(ret instanceof javax.activation.DataHandler[])) {
242 //The wrong type of object that what was expected.
243 System.out.println("Received unexpected type :" +
244 ret.getClass().getName());
245 throw new AxisFault("", "Received unexpected type:" +
246 ret.getClass().getName(), null, null);
247
248 }
249 //Still here, so far so good.
250 //Now lets brute force compare the source attachment
251 // to the one we received.
252 javax.activation.DataHandler[] received = (javax.activation.DataHandler[]) ret;
253
254 int i = 0;
255 for (i = 0; i < received.length && i < attachments.length; ++i) {
256 DataHandler recDH = received[i];
257 DataHandler orginalDH = attachments[i];
258
259 if (!compareFiles(filename + java.io.File.separator + orginalDH.getName(), recDH.getName())) {
260 System.err.println("The attachment with the file name: \"" + orginalDH.getName() +
261 "\" was not received the same!.");
262 rc = false;
263 }
264 java.io.File receivedFile = new java.io.File(recDH.getName());
265
266 receivedFile.delete();
267 }
268
269 if (i < received.length) {
270 System.err.println("There are more file received than sent!!!!");
271
272 rc = false;
273 }
274 if (i < attachments.length) {
275 System.err.println("Not all the files were received!");
276 rc = false;
277 }
278
279
280 return rc;
281 }
282
283 /**
284 * Give a single file to send or name a directory
285 * to send an array of attachments of the files in
286 * that directory.
287 */
288 public static void main(String args[]) {
289 try {
290
291 Options opts = new Options(args);
292 EchoAttachment echoattachment = new EchoAttachment(opts);
293
294 args = opts.getRemainingArgs();
295 int argpos = 0;
296
297 if (args == null || args.length == 0) {
298 System.err.println("Need a file or directory argument.");
299 System.exit(8);
300 }
301
302 boolean doTheDIME = false;
303 if (args[0].trim().equalsIgnoreCase("+FDR")) {
304 doTheDIME = true;
305 ++argpos;
306 }
307
308 if (argpos >= args.length) {
309 System.err.println("Need a file or directory argument.");
310 System.exit(8);
311 }
312
313 String argFile = args[argpos];
314
315 java.io.File source = new java.io.File(argFile);
316
317 if (!source.exists()) {
318 System.err.println("Error \"" + argFile + "\" does not exist!");
319 System.exit(8);
320 }
321
322 if (source.isFile()) {
323 if (echoattachment.echoUsingSAAJ(argFile) && echoattachment.echo(doTheDIME, argFile)) {
324 System.out.println("Attachment sent and received ok!");
325 System.exit(0);
326 } else {
327 System.err.println("Problem in matching attachments");
328 System.exit(8);
329 }
330 } else { //a directory?
331 if (echoattachment.echoDir(doTheDIME, argFile)) {
332 System.out.println("Attachments sent and received ok!");
333 System.exit(0);
334 } else {
335 System.err.println("Problem in matching attachments");
336 System.exit(8);
337 }
338 }
339 } catch (Exception e) {
340 System.err.println(e);
341 e.printStackTrace();
342 }
343 System.exit(18);
344 }
345
346 /**
347 * Quick and unsophisticated method to compare two file's
348 * byte stream.
349 * @param The first file to compare.
350 * @param The second file to compare.
351 * @return True if the bytestreams do compare, false for
352 * any other reason.
353 */
354 protected boolean compareFiles(String one, String other)
355 throws java.io.FileNotFoundException, java.io.IOException {
356
357 java.io.BufferedInputStream oneStream = null;
358 java.io.BufferedInputStream otherStream = null;
359
360 // First compare file length.
361 File f1 = new File(one);
362 File f2 = new File(other);
363 if (f1.length() != f2.length())
364 return false;
365
366 try {
367 oneStream = new java.io.BufferedInputStream(
368 new java.io.FileInputStream(one), 1024 * 64);
369 otherStream = new java.io.BufferedInputStream(
370 new java.io.FileInputStream(other), 1024 * 64);
371
372 byte[] bufOne = new byte[1024 * 64];
373 byte[] bufOther = new byte[1024 * 64];
374 int breadOne = -1;
375 int breadOther = -1;
376 int available = 0;
377
378 do {
379 available = oneStream.available();
380 available = Math.min(available, otherStream.available());
381 available = Math.min(available, bufOther.length);
382
383 if (0 != available) {
384 java.util.Arrays.fill(bufOne, (byte) 0);
385 java.util.Arrays.fill(bufOther, (byte) 0);
386
387 breadOne = oneStream.read(bufOne, 0, available);
388 breadOther = otherStream.read(bufOther, 0, available);
389 if (breadOne != breadOther)
390 throw new RuntimeException(
391 "Sorry couldn't really read whats available!");
392 if (!java.util.Arrays.equals(bufOne, bufOther)) {
393 return false;
394 }
395 }
396
397 } while (available != 0 && breadOne != -1 && breadOther != -1);
398 if (available != 0 && (breadOne != -1 || breadOther != -1)) {
399 return false;
400 }
401 return true;
402 } finally {
403 if (null != oneStream) oneStream.close();
404 if (null != otherStream) otherStream.close();
405 }
406 }
407
408 /**
409 * Return an array of datahandlers for each file in the dir.
410 * @param the name of the directory
411 * @return return an array of datahandlers.
412 */
413
414 protected DataHandler[] getAttachmentsFromDir(String dirName) {
415 java.util.LinkedList retList = new java.util.LinkedList();
416 DataHandler[] ret = new DataHandler[0];// empty
417
418 java.io.File sourceDir = new java.io.File(dirName);
419
420 java.io.File[] files = sourceDir.listFiles();
421
422 for (int i = files.length - 1; i >= 0; --i) {
423 java.io.File cf = files[i];
424
425 if (cf.isFile() && cf.canRead()) {
426 String fname = null;
427
428 try {
429 fname = cf.getAbsoluteFile().getCanonicalPath();
430 } catch (java.io.IOException e) {
431 System.err.println("Couldn't get file \"" + fname + "\" skipping...");
432 continue;
433 }
434 retList.add(new DataHandler(new FileDataSource(fname)));
435 }
436 }
437 if (!retList.isEmpty()) {
438 ret = new DataHandler[retList.size()];
439 ret = (DataHandler[]) retList.toArray(ret);
440 }
441
442 return ret;
443 }
444
445 /**
446 * This method sends a file as an attachment then
447 * receives it as a return. The returned file is
448 * compared to the source. Uses SAAJ API.
449 * @param The filename that is the source to send.
450 * @return True if sent and compared.
451 */
452 public boolean echoUsingSAAJ(String filename) throws Exception {
453 String endPointURLString = "http://localhost:" +opts.getPort() + "/axis/services/urn:EchoAttachmentsService";
454
455 SOAPConnectionFactory soapConnectionFactory =
456 javax.xml.soap.SOAPConnectionFactory.newInstance();
457 SOAPConnection soapConnection =
458 soapConnectionFactory.createConnection();
459
460 MessageFactory messageFactory =
461 MessageFactory.newInstance();
462 SOAPMessage soapMessage =
463 messageFactory.createMessage();
464 SOAPPart soapPart = soapMessage.getSOAPPart();
465 SOAPEnvelope requestEnvelope =
466 soapPart.getEnvelope();
467 SOAPBody body = requestEnvelope.getBody();
468 SOAPBodyElement operation = body.addBodyElement
469 (requestEnvelope.createName("echo"));
470
471 Vector dataHandlersToAdd = new Vector();
472 dataHandlersToAdd.add(new DataHandler(new FileDataSource(new
473 File(filename))));
474
475 if (dataHandlersToAdd != null) {
476 ListIterator dataHandlerIterator =
477 dataHandlersToAdd.listIterator();
478
479 while (dataHandlerIterator.hasNext()) {
480 DataHandler dataHandler = (DataHandler)
481 dataHandlerIterator.next();
482 javax.xml.soap.SOAPElement element =
483 operation.addChildElement(requestEnvelope.createName("source"));
484 javax.xml.soap.AttachmentPart attachment =
485 soapMessage.createAttachmentPart(dataHandler);
486 soapMessage.addAttachmentPart(attachment);
487 element.addAttribute(requestEnvelope.createName
488 ("href"), "cid:" + attachment.getContentId());
489 }
490 }
491 javax.xml.soap.SOAPMessage returnedSOAPMessage =
492 soapConnection.call(soapMessage, endPointURLString);
493 Iterator iterator = returnedSOAPMessage.getAttachments();
494 if (!iterator.hasNext()) {
495 //The wrong type of object that what was expected.
496 System.out.println("Received problem response from server");
497 throw new AxisFault("", "Received problem response from server", null, null);
498
499 }
500 //Still here, so far so good.
501 //Now lets brute force compare the source attachment
502 // to the one we received.
503 DataHandler rdh = (DataHandler) ((AttachmentPart)iterator.next()).getDataHandler();
504
505 //From here we'll just treat the data resource as file.
506 String receivedfileName = rdh.getName();//Get the filename.
507
508 if (receivedfileName == null) {
509 System.err.println("Could not get the file name.");
510 throw new AxisFault("", "Could not get the file name.", null, null);
511 }
512
513
514 System.out.println("Going to compare the files..");
515 boolean retv = compareFiles(filename, receivedfileName);
516
517 java.io.File receivedFile = new java.io.File(receivedfileName);
518
519 receivedFile.delete();
520
521 return retv;
522 }
523 }