Source Code Cross Referenced for DataHandler.java in  » 6.0-JDK-Core » activation » javax » activation » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Home
Java Source Code / Java Documentation
1.6.0 JDK Core
2.6.0 JDK Modules
3.6.0 JDK Modules com.sun
4.6.0 JDK Modules com.sun.java
5.6.0 JDK Modules sun
6.6.0 JDK Platform
7.Ajax
8.Apache Harmony Java SE
9.Aspect oriented
10.Authentication Authorization
11.Blogger System
12.Build
13.Byte Code
14.Cache
15.Chart
16.Chat
17.Code Analyzer
18.Collaboration
19.Content Management System
20.Database Client
21.Database DBMS
22.Database JDBC Connection Pool
23.Database ORM
24.Development
25.EJB Server
26.ERP CRM Financial
27.ESB
28.Forum
29.Game
30.GIS
31.Graphic 3D
32.Graphic Library
33.Groupware
34.HTML Parser
35.IDE
36.IDE Eclipse
37.IDE Netbeans
38.Installer
39.Internationalization Localization
40.Inversion of Control
41.Issue Tracking
42.J2EE
43.J2ME
44.JBoss
45.JMS
46.JMX
47.Library
48.Mail Clients
49.Music
50.Net
51.Parser
52.PDF
53.Portal
54.Profiler
55.Project Management
56.Report
57.RSS RDF
58.Rule Engine
59.Science
60.Scripting
61.Search Engine
62.Security
63.Sevlet Container
64.Source Control
65.Swing Library
66.Template Engine
67.Test Coverage
68.Testing
69.UML
70.Web Crawler
71.Web Framework
72.Web Mail
73.Web Server
74.Web Services
75.Web Services apache cxf 2.2.6
76.Web Services AXIS2
77.Wiki Engine
78.Workflow Engines
79.XML
80.XML UI
Java Source Code / Java Documentation » 6.0 JDK Core » activation » javax.activation 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001        /*
002         * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
003         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004         *
005         * This code is free software; you can redistribute it and/or modify it
006         * under the terms of the GNU General Public License version 2 only, as
007         * published by the Free Software Foundation.  Sun designates this
008         * particular file as subject to the "Classpath" exception as provided
009         * by Sun in the LICENSE file that accompanied this code.
010         *
011         * This code is distributed in the hope that it will be useful, but WITHOUT
012         * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013         * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
014         * version 2 for more details (a copy is included in the LICENSE file that
015         * accompanied this code).
016         *
017         * You should have received a copy of the GNU General Public License version
018         * 2 along with this work; if not, write to the Free Software Foundation,
019         * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020         *
021         * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022         * CA 95054 USA or visit www.sun.com if you need additional information or
023         * have any questions.
024         */
025
026        package javax.activation;
027
028        import java.io.InputStream;
029        import java.io.IOException;
030        import java.io.OutputStream;
031        import java.io.PipedInputStream;
032        import java.io.PipedOutputStream;
033        import java.io.OutputStreamWriter;
034        import java.net.URL;
035        import java.awt.datatransfer.Transferable;
036        import java.awt.datatransfer.DataFlavor;
037        import java.awt.datatransfer.UnsupportedFlavorException;
038
039        /**
040         * The DataHandler class provides a consistent interface to data
041         * available in many different sources and formats.
042         * It manages simple stream to string conversions and related operations
043         * using DataContentHandlers.
044         * It provides access to commands that can operate on the data.
045         * The commands are found using a CommandMap. <p>
046         *
047         * <b>DataHandler and the Transferable Interface</b><p>
048         * DataHandler implements the Transferable interface so that data can
049         * be used in AWT data transfer operations, such as cut and paste and
050         * drag and drop. The implementation of the Transferable interface
051         * relies on the availability of an installed DataContentHandler
052         * object corresponding to the MIME type of the data represented in
053         * the specific instance of the DataHandler.<p>
054         *
055         * <b>DataHandler and CommandMaps</b><p>
056         * The DataHandler keeps track of the current CommandMap that it uses to
057         * service requests for commands (<code>getCommand</code>,
058         * <code>getAllCommands</code>, <code>getPreferredCommands</code>).
059         * Each instance of a DataHandler may have a CommandMap associated with
060         * it using the <code>setCommandMap</code> method.  If a CommandMap was
061         * not set, DataHandler calls the <code>getDefaultCommandMap</code>
062         * method in CommandMap and uses the value it returns. See
063         * <i>CommandMap</i> for more information. <p>
064         *
065         * <b>DataHandler and URLs</b><p>
066         * The current DataHandler implementation creates a private
067         * instance of URLDataSource when it is constructed with a URL.
068         *
069         * @see javax.activation.CommandMap
070         * @see javax.activation.DataContentHandler
071         * @see javax.activation.DataSource
072         * @see javax.activation.URLDataSource
073         *
074         * @since 1.6
075         */
076
077        public class DataHandler implements  Transferable {
078
079            // Use the datasource to indicate whether we were started via the
080            // DataSource constructor or the object constructor.
081            private DataSource dataSource = null;
082            private DataSource objDataSource = null;
083
084            // The Object and mimetype from the constructor (if passed in).
085            // object remains null if it was instantiated with a
086            // DataSource.
087            private Object object = null;
088            private String objectMimeType = null;
089
090            // Keep track of the CommandMap
091            private CommandMap currentCommandMap = null;
092
093            // our transfer flavors
094            private static final DataFlavor emptyFlavors[] = new DataFlavor[0];
095            private DataFlavor transferFlavors[] = emptyFlavors;
096
097            // our DataContentHandler
098            private DataContentHandler dataContentHandler = null;
099            private DataContentHandler factoryDCH = null;
100
101            // our DataContentHandlerFactory
102            private static DataContentHandlerFactory factory = null;
103            private DataContentHandlerFactory oldFactory = null;
104            // the short representation of the ContentType (sans params)
105            private String shortType = null;
106
107            /**
108             * Create a <code>DataHandler</code> instance referencing the
109             * specified DataSource.  The data exists in a byte stream form.
110             * The DataSource will provide an InputStream to access the data.
111             *
112             * @param ds	the DataSource
113             */
114            public DataHandler(DataSource ds) {
115                // save a reference to the incoming DS
116                dataSource = ds;
117                oldFactory = factory; // keep track of the factory
118            }
119
120            /**
121             * Create a <code>DataHandler</code> instance representing an object
122             * of this MIME type.  This constructor is
123             * used when the application already has an in-memory representation
124             * of the data in the form of a Java Object.
125             *
126             * @param obj	the Java Object
127             * @param mimeType	the MIME type of the object
128             */
129            public DataHandler(Object obj, String mimeType) {
130                object = obj;
131                objectMimeType = mimeType;
132                oldFactory = factory; // keep track of the factory
133            }
134
135            /**
136             * Create a <code>DataHandler</code> instance referencing a URL.
137             * The DataHandler internally creates a <code>URLDataSource</code>
138             * instance to represent the URL.
139             *
140             * @param url	a URL object
141             */
142            public DataHandler(URL url) {
143                dataSource = new URLDataSource(url);
144                oldFactory = factory; // keep track of the factory
145            }
146
147            /**
148             * Return the CommandMap for this instance of DataHandler.
149             */
150            private synchronized CommandMap getCommandMap() {
151                if (currentCommandMap != null)
152                    return currentCommandMap;
153                else
154                    return CommandMap.getDefaultCommandMap();
155            }
156
157            /**
158             * Return the DataSource associated with this instance
159             * of DataHandler.
160             * <p>
161             * For DataHandlers that have been instantiated with a DataSource,
162             * this method returns the DataSource that was used to create the
163             * DataHandler object. In other cases the DataHandler
164             * constructs a DataSource from the data used to construct
165             * the DataHandler. DataSources created for DataHandlers <b>not</b>
166             * instantiated with a DataSource are cached for performance
167             * reasons.
168             *
169             * @return	a valid DataSource object for this DataHandler
170             */
171            public DataSource getDataSource() {
172                if (dataSource == null) {
173                    // create one on the fly
174                    if (objDataSource == null)
175                        objDataSource = new DataHandlerDataSource(this );
176                    return objDataSource;
177                }
178                return dataSource;
179            }
180
181            /**
182             * Return the name of the data object. If this DataHandler
183             * was created with a DataSource, this method calls through
184             * to the <code>DataSource.getName</code> method, otherwise it
185             * returns <i>null</i>.
186             *
187             * @return	the name of the object
188             */
189            public String getName() {
190                if (dataSource != null)
191                    return dataSource.getName();
192                else
193                    return null;
194            }
195
196            /**
197             * Return the MIME type of this object as retrieved from
198             * the source object. Note that this is the <i>full</i>
199             * type with parameters.
200             *
201             * @return	the MIME type
202             */
203            public String getContentType() {
204                if (dataSource != null) // data source case
205                    return dataSource.getContentType();
206                else
207                    return objectMimeType; // obj/type case
208            }
209
210            /**
211             * Get the InputStream for this object. <p>
212             *
213             * For DataHandlers instantiated with a DataSource, the DataHandler
214             * calls the <code>DataSource.getInputStream</code> method and
215             * returns the result to the caller.
216             * <p>
217             * For DataHandlers instantiated with an Object, the DataHandler
218             * first attempts to find a DataContentHandler for the Object. If
219             * the DataHandler can not find a DataContentHandler for this MIME
220             * type, it throws an UnsupportedDataTypeException.  If it is
221             * successful, it creates a pipe and a thread.  The thread uses the
222             * DataContentHandler's <code>writeTo</code> method to write the
223             * stream data into one end of the pipe.  The other end of the pipe
224             * is returned to the caller.  Because a thread is created to copy
225             * the data, IOExceptions that may occur during the copy can not be
226             * propagated back to the caller. The result is an empty stream.<p>
227             *
228             * @return	the InputStream representing this data
229             * @exception IOException	if an I/O error occurs
230             *
231             * @see javax.activation.DataContentHandler#writeTo
232             * @see javax.activation.UnsupportedDataTypeException
233             */
234            public InputStream getInputStream() throws IOException {
235                InputStream ins = null;
236
237                if (dataSource != null) {
238                    ins = dataSource.getInputStream();
239                } else {
240                    DataContentHandler dch = getDataContentHandler();
241                    // we won't even try if we can't get a dch
242                    if (dch == null)
243                        throw new UnsupportedDataTypeException(
244                                "no DCH for MIME type " + getBaseType());
245
246                    if (dch instanceof  ObjectDataContentHandler) {
247                        if (((ObjectDataContentHandler) dch).getDCH() == null)
248                            throw new UnsupportedDataTypeException(
249                                    "no object DCH for MIME type "
250                                            + getBaseType());
251                    }
252                    // there is none but the default^^^^^^^^^^^^^^^^
253                    final DataContentHandler fdch = dch;
254
255                    // from bill s.
256                    // ce n'est pas une pipe!
257                    //
258                    // NOTE: This block of code needs to throw exceptions, but
259                    // can't because it is in another thread!!! ARG!
260                    //
261                    final PipedOutputStream pos = new PipedOutputStream();
262                    PipedInputStream pin = new PipedInputStream(pos);
263                    new Thread(new Runnable() {
264                        public void run() {
265                            try {
266                                fdch.writeTo(object, objectMimeType, pos);
267                            } catch (IOException e) {
268
269                            } finally {
270                                try {
271                                    pos.close();
272                                } catch (IOException ie) {
273                                }
274                            }
275                        }
276                    }, "DataHandler.getInputStream").start();
277                    ins = pin;
278                }
279
280                return ins;
281            }
282
283            /**
284             * Write the data to an <code>OutputStream</code>.<p>
285             *
286             * If the DataHandler was created with a DataSource, writeTo
287             * retrieves the InputStream and copies the bytes from the
288             * InputStream to the OutputStream passed in.
289             * <p>
290             * If the DataHandler was created with an object, writeTo
291             * retrieves the DataContentHandler for the object's type.
292             * If the DataContentHandler was found, it calls the
293             * <code>writeTo</code> method on the <code>DataContentHandler</code>.
294             *
295             * @param os	the OutputStream to write to
296             * @exception IOException	if an I/O error occurs
297             */
298            public void writeTo(OutputStream os) throws IOException {
299                // for the DataSource case
300                if (dataSource != null) {
301                    InputStream is = null;
302                    byte data[] = new byte[8 * 1024];
303                    int bytes_read;
304
305                    is = dataSource.getInputStream();
306
307                    try {
308                        while ((bytes_read = is.read(data)) > 0) {
309                            os.write(data, 0, bytes_read);
310                        }
311                    } finally {
312                        is.close();
313                        is = null;
314                    }
315                } else { // for the Object case
316                    DataContentHandler dch = getDataContentHandler();
317                    dch.writeTo(object, objectMimeType, os);
318                }
319            }
320
321            /**
322             * Get an OutputStream for this DataHandler to allow overwriting
323             * the underlying data.
324             * If the DataHandler was created with a DataSource, the
325             * DataSource's <code>getOutputStream</code> method is called.
326             * Otherwise, <code>null</code> is returned.
327             *
328             * @return the OutputStream
329             *
330             * @see javax.activation.DataSource#getOutputStream
331             * @see javax.activation.URLDataSource
332             */
333            public OutputStream getOutputStream() throws IOException {
334                if (dataSource != null)
335                    return dataSource.getOutputStream();
336                else
337                    return null;
338            }
339
340            /**
341             * Return the DataFlavors in which this data is available. <p>
342             *
343             * Returns an array of DataFlavor objects indicating the flavors
344             * the data can be provided in. The array is usually ordered
345             * according to preference for providing the data, from most
346             * richly descriptive to least richly descriptive.<p>
347             *
348             * The DataHandler attempts to find a DataContentHandler that
349             * corresponds to the MIME type of the data. If one is located,
350             * the DataHandler calls the DataContentHandler's
351             * <code>getTransferDataFlavors</code> method. <p>
352             *
353             * If a DataContentHandler can <i>not</i> be located, and if the
354             * DataHandler was created with a DataSource (or URL), one
355             * DataFlavor is returned that represents this object's MIME type
356             * and the <code>java.io.InputStream</code> class.  If the
357             * DataHandler was created with an object and a MIME type,
358             * getTransferDataFlavors returns one DataFlavor that represents
359             * this object's MIME type and the object's class.
360             *
361             * @return	an array of data flavors in which this data can be transferred
362             * @see javax.activation.DataContentHandler#getTransferDataFlavors
363             */
364            public synchronized DataFlavor[] getTransferDataFlavors() {
365                if (factory != oldFactory) // if the factory has changed, clear cache
366                    transferFlavors = emptyFlavors;
367
368                // if it's not set, set it...
369                if (transferFlavors == emptyFlavors)
370                    transferFlavors = getDataContentHandler()
371                            .getTransferDataFlavors();
372                return transferFlavors;
373            }
374
375            /**
376             * Returns whether the specified data flavor is supported
377             * for this object.<p>
378             *
379             * This method iterates through the DataFlavors returned from
380             * <code>getTransferDataFlavors</code>, comparing each with
381             * the specified flavor.
382             *
383             * @param flavor	the requested flavor for the data
384             * @return		true if the data flavor is supported
385             * @see javax.activation.DataHandler#getTransferDataFlavors
386             */
387            public boolean isDataFlavorSupported(DataFlavor flavor) {
388                DataFlavor[] lFlavors = getTransferDataFlavors();
389
390                for (int i = 0; i < lFlavors.length; i++) {
391                    if (lFlavors[i].equals(flavor))
392                        return true;
393                }
394                return false;
395            }
396
397            /**
398             * Returns an object that represents the data to be
399             * transferred. The class of the object returned is defined by the
400             * representation class of the data flavor.<p>
401             *
402             * <b>For DataHandler's created with DataSources or URLs:</b><p>
403             *
404             * The DataHandler attempts to locate a DataContentHandler
405             * for this MIME type. If one is found, the passed in DataFlavor
406             * and the type of the data are passed to its <code>getTransferData</code>
407             * method. If the DataHandler fails to locate a DataContentHandler
408             * and the flavor specifies this object's MIME type and the
409             * <code>java.io.InputStream</code> class, this object's InputStream
410             * is returned.
411             * Otherwise it throws an UnsupportedFlavorException. <p>
412             *
413             * <b>For DataHandler's created with Objects:</b><p>
414             *
415             * The DataHandler attempts to locate a DataContentHandler
416             * for this MIME type. If one is found, the passed in DataFlavor
417             * and the type of the data are passed to its getTransferData
418             * method. If the DataHandler fails to locate a DataContentHandler
419             * and the flavor specifies this object's MIME type and its class,
420             * this DataHandler's referenced object is returned.  
421             * Otherwise it throws an UnsupportedFlavorException.
422             *
423             * @param flavor	the requested flavor for the data
424             * @return		the object
425             * @exception UnsupportedFlavorException	if the data could not be
426             *			converted to the requested flavor
427             * @exception IOException	if an I/O error occurs
428             * @see javax.activation.ActivationDataFlavor
429             */
430            public Object getTransferData(DataFlavor flavor)
431                    throws UnsupportedFlavorException, IOException {
432                return getDataContentHandler().getTransferData(flavor,
433                        dataSource);
434            }
435
436            /**
437             * Set the CommandMap for use by this DataHandler.
438             * Setting it to <code>null</code> causes the CommandMap to revert
439             * to the CommandMap returned by the
440             * <code>CommandMap.getDefaultCommandMap</code> method.
441             * Changing the CommandMap, or setting it to <code>null</code>,
442             * clears out any data cached from the previous CommandMap.
443             *
444             * @param commandMap	the CommandMap to use in this DataHandler
445             *
446             * @see javax.activation.CommandMap#setDefaultCommandMap
447             */
448            public synchronized void setCommandMap(CommandMap commandMap) {
449                if (commandMap != currentCommandMap || commandMap == null) {
450                    // clear cached values...
451                    transferFlavors = emptyFlavors;
452                    dataContentHandler = null;
453
454                    currentCommandMap = commandMap;
455                }
456            }
457
458            /**
459             * Return the <i>preferred</i> commands for this type of data.
460             * This method calls the <code>getPreferredCommands</code> method
461             * in the CommandMap associated with this instance of DataHandler.
462             * This method returns an array that represents a subset of
463             * available commands. In cases where multiple commands for the
464             * MIME type represented by this DataHandler are present, the
465             * installed CommandMap chooses the appropriate commands.
466             *
467             * @return	the CommandInfo objects representing the preferred commands
468             *
469             * @see javax.activation.CommandMap#getPreferredCommands
470             */
471            public CommandInfo[] getPreferredCommands() {
472                if (dataSource != null)
473                    return getCommandMap().getPreferredCommands(getBaseType(),
474                            dataSource);
475                else
476                    return getCommandMap().getPreferredCommands(getBaseType());
477            }
478
479            /**
480             * Return all the commands for this type of data.
481             * This method returns an array containing all commands
482             * for the type of data represented by this DataHandler. The
483             * MIME type for the underlying data represented by this DataHandler
484             * is used to call through to the <code>getAllCommands</code> method
485             * of the CommandMap associated with this DataHandler.
486             *
487             * @return	the CommandInfo objects representing all the commands
488             *
489             * @see javax.activation.CommandMap#getAllCommands
490             */
491            public CommandInfo[] getAllCommands() {
492                if (dataSource != null)
493                    return getCommandMap().getAllCommands(getBaseType(),
494                            dataSource);
495                else
496                    return getCommandMap().getAllCommands(getBaseType());
497            }
498
499            /**
500             * Get the command <i>cmdName</i>. Use the search semantics as
501             * defined by the CommandMap installed in this DataHandler. The
502             * MIME type for the underlying data represented by this DataHandler
503             * is used to call through to the <code>getCommand</code> method
504             * of the CommandMap associated with this DataHandler.
505             *
506             * @param cmdName	the command name
507             * @return	the CommandInfo corresponding to the command
508             *
509             * @see javax.activation.CommandMap#getCommand
510             */
511            public CommandInfo getCommand(String cmdName) {
512                if (dataSource != null)
513                    return getCommandMap().getCommand(getBaseType(), cmdName,
514                            dataSource);
515                else
516                    return getCommandMap().getCommand(getBaseType(), cmdName);
517            }
518
519            /**
520             * Return the data in its preferred Object form. <p>
521             *
522             * If the DataHandler was instantiated with an object, return
523             * the object. <p>
524             *
525             * If the DataHandler was instantiated with a DataSource,
526             * this method uses a DataContentHandler to return the content
527             * object for the data represented by this DataHandler. If no
528             * <code>DataContentHandler</code> can be found for the
529             * the type of this data, the DataHandler returns an
530             * InputStream for the data.
531             *
532             * @return the content.
533             * @exception IOException if an IOException occurs during
534             *                              this operation.
535             */
536            public Object getContent() throws IOException {
537                if (object != null)
538                    return object;
539                else
540                    return getDataContentHandler().getContent(getDataSource());
541            }
542
543            /**
544             * A convenience method that takes a CommandInfo object
545             * and instantiates the corresponding command, usually
546             * a JavaBean component.
547             * <p>
548             * This method calls the CommandInfo's <code>getCommandObject</code>
549             * method with the <code>ClassLoader</code> used to load
550             * the <code>javax.activation.DataHandler</code> class itself.
551             *
552             * @param cmdinfo	the CommandInfo corresponding to a command
553             * @return	the instantiated command object
554             */
555            public Object getBean(CommandInfo cmdinfo) {
556                Object bean = null;
557
558                try {
559                    // make the bean
560                    ClassLoader cld = null;
561                    // First try the "application's" class loader.
562                    cld = SecuritySupport.getContextClassLoader();
563                    if (cld == null)
564                        cld = this .getClass().getClassLoader();
565                    bean = cmdinfo.getCommandObject(this , cld);
566                } catch (IOException e) {
567                } catch (ClassNotFoundException e) {
568                }
569
570                return bean;
571            }
572
573            /**
574             * Get the DataContentHandler for this DataHandler: <p>
575             *
576             * If a DataContentHandlerFactory is set, use it.
577             * Otherwise look for an object to serve DCH in the
578             * following order: <p>
579             *
580             * 1) if a factory is set, use it <p>
581             * 2) if a CommandMap is set, use it <p>
582             * 3) use the default CommandMap <p>
583             *
584             * In any case, wrap the real DataContentHandler with one of our own
585             * to handle any missing cases, fill in defaults, and to ensure that
586             * we always have a non-null DataContentHandler.
587             *
588             * @return	the requested DataContentHandler
589             */
590            private synchronized DataContentHandler getDataContentHandler() {
591
592                // make sure the factory didn't change
593                if (factory != oldFactory) {
594                    oldFactory = factory;
595                    factoryDCH = null;
596                    dataContentHandler = null;
597                    transferFlavors = emptyFlavors;
598                }
599
600                if (dataContentHandler != null)
601                    return dataContentHandler;
602
603                String simpleMT = getBaseType();
604
605                if (factoryDCH == null && factory != null)
606                    factoryDCH = factory.createDataContentHandler(simpleMT);
607
608                if (factoryDCH != null)
609                    dataContentHandler = factoryDCH;
610
611                if (dataContentHandler == null) {
612                    if (dataSource != null)
613                        dataContentHandler = getCommandMap()
614                                .createDataContentHandler(simpleMT, dataSource);
615                    else
616                        dataContentHandler = getCommandMap()
617                                .createDataContentHandler(simpleMT);
618                }
619
620                // getDataContentHandler always uses these 'wrapper' handlers
621                // to make sure it returns SOMETHING meaningful...
622                if (dataSource != null)
623                    dataContentHandler = new DataSourceDataContentHandler(
624                            dataContentHandler, dataSource);
625                else
626                    dataContentHandler = new ObjectDataContentHandler(
627                            dataContentHandler, object, objectMimeType);
628                return dataContentHandler;
629            }
630
631            /**
632             * Use the MimeType class to extract the MIME type/subtype,
633             * ignoring the parameters.  The type is cached.
634             */
635            private synchronized String getBaseType() {
636                if (shortType == null) {
637                    String ct = getContentType();
638                    try {
639                        MimeType mt = new MimeType(ct);
640                        shortType = mt.getBaseType();
641                    } catch (MimeTypeParseException e) {
642                        shortType = ct;
643                    }
644                }
645                return shortType;
646            }
647
648            /**
649             * Sets the DataContentHandlerFactory.  The DataContentHandlerFactory
650             * is called first to find DataContentHandlers.
651             * The DataContentHandlerFactory can only be set once.
652             * <p>
653             * If the DataContentHandlerFactory has already been set,
654             * this method throws an Error.
655             *
656             * @param newFactory	the DataContentHandlerFactory
657             * @exception Error	if the factory has already been defined.
658             *
659             * @see javax.activation.DataContentHandlerFactory
660             */
661            public static synchronized void setDataContentHandlerFactory(
662                    DataContentHandlerFactory newFactory) {
663                if (factory != null)
664                    throw new Error("DataContentHandlerFactory already defined");
665
666                SecurityManager security = System.getSecurityManager();
667                if (security != null) {
668                    try {
669                        // if it's ok with the SecurityManager, it's ok with me...
670                        security.checkSetFactory();
671                    } catch (SecurityException ex) {
672                        // otherwise, we also allow it if this code and the
673                        // factory come from the same class loader (e.g.,
674                        // the JAF classes were loaded with the applet classes).
675                        if (DataHandler.class.getClassLoader() != newFactory
676                                .getClass().getClassLoader())
677                            throw ex;
678                    }
679                }
680                factory = newFactory;
681            }
682        }
683
684        /**
685         * The DataHanderDataSource class implements the
686         * DataSource interface when the DataHandler is constructed
687         * with an Object and a mimeType string.
688         */
689        class DataHandlerDataSource implements  DataSource {
690            DataHandler dataHandler = null;
691
692            /**
693             * The constructor.
694             */
695            public DataHandlerDataSource(DataHandler dh) {
696                this .dataHandler = dh;
697            }
698
699            /**
700             * Returns an <code>InputStream</code> representing this object.
701             * @return	the <code>InputStream</code>
702             */
703            public InputStream getInputStream() throws IOException {
704                return dataHandler.getInputStream();
705            }
706
707            /**
708             * Returns the <code>OutputStream</code> for this object.
709             * @return	the <code>OutputStream</code>
710             */
711            public OutputStream getOutputStream() throws IOException {
712                return dataHandler.getOutputStream();
713            }
714
715            /**
716             * Returns the MIME type of the data represented by this object.
717             * @return	the MIME type
718             */
719            public String getContentType() {
720                return dataHandler.getContentType();
721            }
722
723            /**
724             * Returns the name of this object.
725             * @return	the name of this object
726             */
727            public String getName() {
728                return dataHandler.getName(); // what else would it be?
729            }
730        }
731
732        /*
733         * DataSourceDataContentHandler
734         *
735         * This is a <i>private</i> DataContentHandler that wraps the real
736         * DataContentHandler in the case where the DataHandler was instantiated
737         * with a DataSource.
738         */
739        class DataSourceDataContentHandler implements  DataContentHandler {
740            private DataSource ds = null;
741            private DataFlavor transferFlavors[] = null;
742            private DataContentHandler dch = null;
743
744            /**
745             * The constructor.
746             */
747            public DataSourceDataContentHandler(DataContentHandler dch,
748                    DataSource ds) {
749                this .ds = ds;
750                this .dch = dch;
751            }
752
753            /**
754             * Return the DataFlavors for this <code>DataContentHandler</code>.
755             * @return	the DataFlavors
756             */
757            public DataFlavor[] getTransferDataFlavors() {
758
759                if (transferFlavors == null) {
760                    if (dch != null) { // is there a dch?
761                        transferFlavors = dch.getTransferDataFlavors();
762                    } else {
763                        transferFlavors = new DataFlavor[1];
764                        transferFlavors[0] = new ActivationDataFlavor(ds
765                                .getContentType(), ds.getContentType());
766                    }
767                }
768                return transferFlavors;
769            }
770
771            /**
772             * Return the Transfer Data of type DataFlavor from InputStream.
773             * @param df	the DataFlavor
774             * @param ds	the DataSource
775             * @return		the constructed Object
776             */
777            public Object getTransferData(DataFlavor df, DataSource ds)
778                    throws UnsupportedFlavorException, IOException {
779
780                if (dch != null)
781                    return dch.getTransferData(df, ds);
782                else if (df.equals(getTransferDataFlavors()[0])) // only have one now
783                    return ds.getInputStream();
784                else
785                    throw new UnsupportedFlavorException(df);
786            }
787
788            public Object getContent(DataSource ds) throws IOException {
789
790                if (dch != null)
791                    return dch.getContent(ds);
792                else
793                    return ds.getInputStream();
794            }
795
796            /**
797             * Write the object to the output stream.
798             */
799            public void writeTo(Object obj, String mimeType, OutputStream os)
800                    throws IOException {
801                if (dch != null)
802                    dch.writeTo(obj, mimeType, os);
803                else
804                    throw new UnsupportedDataTypeException(
805                            "no DCH for content type " + ds.getContentType());
806            }
807        }
808
809        /*
810         * ObjectDataContentHandler
811         *
812         * This is a <i>private</i> DataContentHandler that wraps the real
813         * DataContentHandler in the case where the DataHandler was instantiated
814         * with an object.
815         */
816        class ObjectDataContentHandler implements  DataContentHandler {
817            private DataFlavor transferFlavors[] = null;
818            private Object obj;
819            private String mimeType;
820            private DataContentHandler dch = null;
821
822            /**
823             * The constructor.
824             */
825            public ObjectDataContentHandler(DataContentHandler dch, Object obj,
826                    String mimeType) {
827                this .obj = obj;
828                this .mimeType = mimeType;
829                this .dch = dch;
830            }
831
832            /**
833             * Return the DataContentHandler for this object.
834             * Used only by the DataHandler class.
835             */
836            public DataContentHandler getDCH() {
837                return dch;
838            }
839
840            /**
841             * Return the DataFlavors for this <code>DataContentHandler</code>.
842             * @return	the DataFlavors
843             */
844            public synchronized DataFlavor[] getTransferDataFlavors() {
845                if (transferFlavors == null) {
846                    if (dch != null) {
847                        transferFlavors = dch.getTransferDataFlavors();
848                    } else {
849                        transferFlavors = new DataFlavor[1];
850                        transferFlavors[0] = new ActivationDataFlavor(obj
851                                .getClass(), mimeType, mimeType);
852                    }
853                }
854                return transferFlavors;
855            }
856
857            /**
858             * Return the Transfer Data of type DataFlavor from InputStream.
859             * @param df	the DataFlavor
860             * @param ds	the DataSource
861             * @return		the constructed Object
862             */
863            public Object getTransferData(DataFlavor df, DataSource ds)
864                    throws UnsupportedFlavorException, IOException {
865
866                if (dch != null)
867                    return dch.getTransferData(df, ds);
868                else if (df.equals(getTransferDataFlavors()[0])) // only have one now
869                    return obj;
870                else
871                    throw new UnsupportedFlavorException(df);
872
873            }
874
875            public Object getContent(DataSource ds) {
876                return obj;
877            }
878
879            /**
880             * Write the object to the output stream.
881             */
882            public void writeTo(Object obj, String mimeType, OutputStream os)
883                    throws IOException {
884                if (dch != null)
885                    dch.writeTo(obj, mimeType, os);
886                else if (obj instanceof  byte[])
887                    os.write((byte[]) obj);
888                else if (obj instanceof  String) {
889                    OutputStreamWriter osw = new OutputStreamWriter(os);
890                    osw.write((String) obj);
891                    osw.flush();
892                } else
893                    throw new UnsupportedDataTypeException(
894                            "no object DCH for MIME type " + this.mimeType);
895            }
896        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.