1 /*************************************************************************
2  *
3  *  The Contents of this file are made available subject to the terms of
4  *  the BSD license.
5  *
6  *  Copyright 2000, 2010 Oracle and/or its affiliates.
7  *  All rights reserved.
8  *
9  *  Redistribution and use in source and binary forms, with or without
10  *  modification, are permitted provided that the following conditions
11  *  are met:
12  *  1. Redistributions of source code must retain the above copyright
13  *     notice, this list of conditions and the following disclaimer.
14  *  2. Redistributions in binary form must reproduce the above copyright
15  *     notice, this list of conditions and the following disclaimer in the
16  *     documentation and/or other materials provided with the distribution.
17  *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
18  *     contributors may be used to endorse or promote products derived
19  *     from this software without specific prior written permission.
20  *
21  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
28  *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
29  *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
30  *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
31  *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  *************************************************************************/
34 
35 import com.sun.star.ucb.OpenCommandArgument2;
36 import com.sun.star.ucb.OpenMode;
37 import com.sun.star.ucb.XContent;
38 import com.sun.star.ucb.XContentAccess;
39 import com.sun.star.ucb.XDynamicResultSet;
40 import com.sun.star.beans.Property;
41 import com.sun.star.uno.UnoRuntime;
42 import com.sun.star.sdbc.XRow;
43 import com.sun.star.sdbc.XResultSet;
44 
45 import java.util.Vector;
46 import java.util.Enumeration;
47 import java.util.StringTokenizer;
48 
49 /**
50  * Retrieve the Children of a UCB Folder Content
51  */
52 public class ChildrenRetriever {
53 
54     /**
55      * Member properties
56      */
57     private  Helper   m_helper;
58     private  XContent m_content;
59     private  String   m_contenturl    = "";
60     private  Vector   m_propnames      = new Vector();
61 
62     /**
63      * Constructor. Create a new connection with the specific args to a running office
64      *
65      *@param      String[]   This construtor requires the arguments:
66      *                          -url=...       (optional)
67      *                          -propNames=... (optional)
68      *                       See Help (method printCmdLineUsage()).
69      *                       Without the arguments a new connection to a
70      *                       running office cannot created.
71      *@exception  java.lang.Exception
72      */
73     public ChildrenRetriever( String args[] ) throws java.lang.Exception {
74 
75         // Parse arguments
76         parseArguments( args );
77 
78         // Init
79         m_helper       = new Helper( getContentURL() );
80 
81         // Create UCB content
82         m_content      = m_helper.createUCBContent();
83     }
84 
85     /**
86      * Open a folder content, get properties values.
87      * This method requires the main and the optional arguments to be set in order to work.
88      * See Constructor.
89      *
90      *@return     Vector   Returns children properties values if values successfully retrieved,
91      *                     null otherwise
92      *@exception  com.sun.star.ucb.CommandAbortedException
93      *@exception  com.sun.star.uno.Exception
94      */
95     public Vector getChildren()
96         throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception {
97         Vector properties = getProperties();
98         return getChildren ( properties );
99     }
100 
101     /**
102      * Open a folder content, get properties values for the properties.
103      *
104      *@param  Vector   Properties
105      *@return Vector   Returns children properties values if values successfully retrieved,
106      *                 null otherwise
107      *@exception  com.sun.star.ucb.CommandAbortedException
108      *@exception  com.sun.star.uno.Exception
109      */
110     public Vector getChildren( Vector properties )
111         throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception {
112 
113         Vector result = null;
114         if ( m_content != null ) {
115             int size = 0;
116             if ( properties != null && !properties.isEmpty()) {
117                 size = properties.size();
118             }
119             // Fill info for the properties wanted.
120             Property[] props = new Property[ size ];
121             for ( int index = 0 ; index < size; index++ ) {
122 
123                 // Define property sequence.
124                 Property prop = new Property();
125                 prop.Name = ( String )properties.get( index );
126                 prop.Handle = -1; // n/a
127                 props[ index ] = prop;
128             }
129 
130             // Fill argument structure...
131             OpenCommandArgument2 arg = new OpenCommandArgument2();
132             arg.Mode = OpenMode.ALL; // FOLDER, DOCUMENTS -> simple filter
133             arg.Priority = 32768;    // Final static for 32768
134             arg.Properties = props;
135 
136             XDynamicResultSet set;
137 
138             // Execute command "open".
139             set = ( XDynamicResultSet )UnoRuntime.queryInterface(
140                 XDynamicResultSet.class, m_helper.executeCommand( m_content, "open", arg ));
141             XResultSet resultSet = ( XResultSet )set.getStaticResultSet();
142 
143             result = new Vector();
144 
145             /////////////////////////////////////////////////////////////////////
146             // Iterate over children, access children and property values...
147             /////////////////////////////////////////////////////////////////////
148 
149                 // Move to begin.
150             if ( resultSet.first() ) {
151                 XContentAccess contentAccess = ( XContentAccess )UnoRuntime.queryInterface(
152                     XContentAccess.class, resultSet );
153                 XRow row = ( XRow )UnoRuntime.queryInterface( XRow.class, resultSet );
154 
155                 do {
156                     Vector propsValues = new Vector();
157 
158                     // Obtain URL of child.
159                     String id = contentAccess.queryContentIdentifierString();
160                     propsValues.add( id );
161                     for ( int i = 1; i <= size ; i++)  {
162                         Object propValue = row.getObject( i, null );
163                         if ( !row.wasNull() && !(propValue instanceof com.sun.star.uno.Any )) {
164                             propsValues.add( propValue );
165                         } else {
166                             propsValues.add( "[ Property not found ]" );
167                         }
168                     }
169                     result.add( propsValues );
170                 } while ( resultSet.next() ); // next child
171             }
172         }
173         return result;
174     }
175 
176     /**
177      *  Get connect URL.
178      *
179      *@return   String  That contains the connect URL
180      */
181     public String getContentURL() {
182         return m_contenturl;
183     }
184 
185     /**
186      * Get the properties.
187      *
188      *@return String    That contains the properties
189      */
190     public Vector getProperties() {
191         return m_propnames;
192     }
193 
194     /**
195      * Parse arguments
196      *
197      *@param      String[]   Arguments
198      *@exception  java.lang.Exception
199      */
200     public void parseArguments( String[] args ) throws java.lang.Exception {
201 
202         for ( int i = 0; i < args.length; i++ ) {
203             if ( args[i].startsWith( "-url=" )) {
204                 m_contenturl    = args[i].substring( 5 );
205             } else if ( args[i].startsWith( "-propNames=" )) {
206                 StringTokenizer tok
207 					= new StringTokenizer( args[i].substring( 11 ), ";" );
208 
209 				while ( tok.hasMoreTokens() )
210 					m_propnames.add( tok.nextToken() );
211 
212             } else if ( args[i].startsWith( "-help" ) ||
213                         args[i].startsWith( "-?" )) {
214                 printCmdLineUsage();
215                 System.exit( 0 );
216             }
217         }
218 
219 		if ( m_contenturl == null || m_contenturl.equals( "" )) {
220             m_contenturl    = "file:///";
221         }
222 
223 		if ( m_propnames.size() == 0 ) {
224 			m_propnames.add( "Title" );
225 			m_propnames.add( "IsDocument" );
226 		}
227     }
228 
229     /**
230      * Print the commands options
231      */
232     public void printCmdLineUsage() {
233         System.out.println(
234             "Usage   : ChildrenRetriever -url=... -propNames=..." );
235         System.out.println(
236             "Defaults: -url=file:/// -propNames=Title,IsDocument" );
237         System.out.println(
238             "\nExample : -url=file:///temp/ -propNames=Title;IsFolder;IsDocument" );
239     }
240 
241     /**
242      *  Print all properties out contained in vector .
243      *
244      *@param   Vector
245      */
246     public void printLine( Vector props ) {
247         int limit;
248         while ( !props.isEmpty() )   {
249             String print = "";
250             int size  = props.size();
251             for ( int i = 0; i < size; i++ ) {
252                 limit = 15;
253                 Object obj = props.get( i );
254                 if ( obj != null)  {
255                     String prop = obj.toString();
256                     int leng = prop.length();
257                     if ( leng < limit ) {
258                         for ( int l = leng; l < limit; l++) {
259                             prop += " ";
260                         }
261                         print+= prop + "  ";
262                         props.set( i, null );
263                     } else {
264                         String temp1 = prop.substring( 0, limit );
265                         String temp2 = prop.substring( limit );
266                         print+= temp1 + "  ";
267                         props.set( i, temp2 );
268                     }
269                 } else  {
270                     for ( int l = 0; l < limit; l++) {
271                         print += " ";
272                     }
273                     print+= "  ";
274                 }
275             }
276             System.out.println( print );
277             boolean isEmpty = true;
278             for ( int i = 0; i < size; i++ ) {
279             Object obj = props.get( i );
280             if( obj != null )
281                 isEmpty = false;
282             }
283             if( isEmpty )
284                 props.clear();
285         }
286     }
287 
288     /**
289      *  Create a new connection with the specific args to a running office and
290      *  access the children from a folder.
291      *
292      *@param  String[]   Arguments
293      */
294     public static void main ( String args[] ) {
295 
296         System.out.println( "\n" );
297 		System.out.println(
298             "-----------------------------------------------------------------" );
299 		System.out.println(
300             "ChildrenRetriever - obtains the children of a folder resource." );
301 		System.out.println(
302             "-----------------------------------------------------------------" );
303 
304         try {
305             ChildrenRetriever access = new ChildrenRetriever( args );
306 
307             // Get the properties Title and IsFolder for the children.
308             Vector result = access.getChildren();
309 
310             String tempPrint = "\nChildren of resource " + access.getContentURL();
311             int size = tempPrint.length();
312             System.out.println( tempPrint );
313             tempPrint = "";
314             for( int i = 0; i < size; i++ ) {
315                 tempPrint += "-";
316             }
317             System.out.println( tempPrint );
318 
319             if ( result != null && !result.isEmpty() ) {
320 
321                 Vector cont = new Vector();
322                 cont.add("URL:");
323                 Vector props = access.getProperties();
324                 size = props.size();
325                 for ( int i = 0; i < size; i++ ) {
326                     Object obj = props.get( i );
327                     String prop = obj.toString();
328                     cont.add( prop + ":" );
329                 }
330                 access.printLine(cont);
331                 System.out.println( "\n" );
332                 for ( Enumeration e = result.elements(); e.hasMoreElements(); ) {
333                     Vector propsV   = ( Vector )e.nextElement();
334                     access.printLine( propsV );
335                 }
336             }
337         } catch ( com.sun.star.ucb.ResultSetException e ) {
338             System.out.println( "Error: " + e );
339         } catch ( com.sun.star.ucb.CommandAbortedException e ) {
340             System.out.println( "Error: " + e );
341         } catch ( com.sun.star.uno.Exception e ) {
342             System.out.println( "Error: " + e );
343         } catch ( java.lang.Exception e ) {
344             System.out.println( "Error: " + e );
345         }
346         System.exit( 0 );
347     }
348 }
349