1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 import com.sun.star.beans.PropertyValue;
25 import com.sun.star.uno.UnoRuntime;
26 import com.sun.star.ucb.ContentInfo;
27 import com.sun.star.ucb.InsertCommandArgument;
28 import com.sun.star.ucb.XContent;
29 import com.sun.star.io.XInputStream;
30 
31 
32 /**
33  * Creating a New Resource
34  */
35 public class ResourceCreator {
36 
37     /**
38      * Member properties
39      */
40     private  Helper    m_helper;
41     private  XContent  m_content;
42     private  String    m_contenturl    = "";
43     private  String    m_name          = "";
44     private  String    m_srcURL        = "";
45 
46     /**
47      * Constructor.
48      *
49      *@param      String[]   This construtor requires the arguments:
50      *                          -url=...     (optional)
51      *                          -name=...    (optional)
52      *                          -srcURL=...  (optional)
53      *                          -workdir=... (optional)
54      *                       See Help (method printCmdLineUsage()).
55      *                       Without the arguments a new connection to a
56      *                       running office cannot created.
57      *@exception  java.lang.Exception
58      */
ResourceCreator( String args[] )59     public ResourceCreator( String args[] ) throws java.lang.Exception {
60 
61         // Parse arguments
62         parseArguments( args );
63         String url     = getContentURL();
64 
65         // Init
66         m_helper = new Helper( url );
67         if ( url.startsWith( "file:///" )) {
68 
69             // Create UCB content
70             m_content  = m_helper.createUCBContent();
71         } else  {
72             throw new Exception(
73                 "Create new resource : parameter 'url' must contain a File URL " +
74                 "pointing to the file system folder in which the new resource " +
75                 "shall be created. (Example: file:///tmp/)" );
76         }
77     }
78 
79     /**
80      *  Create a new resource.
81      *  This method requires the main and the optional arguments to be set in order to work.
82      *  See Constructor.
83      *
84      *@return boolean  Returns true if resource successfully created, false otherwise
85      *@exception  com.sun.star.ucb.CommandAbortedException
86      *@exception  com.sun.star.uno.Exception
87      */
createNewResource()88     public boolean createNewResource()
89         throws com.sun.star.ucb.CommandAbortedException,
90                com.sun.star.uno.Exception,
91                java.lang.Exception {
92 
93         String sourceURL         = getSourceURL();
94         String name              = getName();
95         return createNewResource( sourceURL, name );
96     }
97 
98     /**
99      *  Create a new resource.
100      *
101      *@param  String   Source resource URL
102      *@param  String   New resource name
103      *@return boolean  Returns true if resource successfully created, false otherwise
104      *@exception  com.sun.star.ucb.CommandAbortedException
105      *@exception  com.sun.star.uno.Exception
106      */
createNewResource( String sourceURL, String name )107     public boolean createNewResource( String sourceURL, String name )
108         throws com.sun.star.ucb.CommandAbortedException,
109                com.sun.star.uno.Exception,
110                java.lang.Exception {
111 
112         XInputStream stream = null;
113         if ( sourceURL == null || sourceURL.equals( "" )) {
114             stream = new MyInputStream();
115         } else  {
116             String[] args =  new String[ 1 ];
117             args[ 0 ] = "-url=" + sourceURL;
118             DataStreamRetriever access = new DataStreamRetriever( args );
119             stream = access.getDataStream();
120         }
121         return createNewResource( stream, name );
122     }
123 
124     /**
125      *  Create a new resource.
126      *
127      *@param  XInputStream   Source resource stream
128      *@param  String         New resource name
129      *@return boolean        Returns true if resource successfully created, false otherwise
130      *@exception  com.sun.star.ucb.CommandAbortedException
131      *@exception  com.sun.star.uno.Exception
132      */
createNewResource( XInputStream stream, String name )133     public boolean createNewResource( XInputStream stream, String name )
134         throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception {
135 
136         boolean result = false;
137         if ( stream != null && name != null && !name.equals( "" )) {
138 
139             // Note: The data for info may have been obtained from
140             //       property CreatableContentsInfo.
141             ContentInfo info = new ContentInfo();
142             info.Type = "application/vnd.sun.staroffice.fsys-file";
143             info.Attributes = 0;
144 
145             // Create new, empty content (execute command "createNewContent").
146             XContent newContent = ( XContent )UnoRuntime.queryInterface(
147                 XContent.class,
148                 m_helper.executeCommand( m_content, "createNewContent", info ) );
149 
150             if ( newContent != null ) {
151 
152                 /////////////////////////////////////////////////////////////////////
153                 // Set mandatory properties...
154                 /////////////////////////////////////////////////////////////////////
155 
156                 // Define property value sequence.
157                 PropertyValue[] props = new PropertyValue[ 1 ];
158                 PropertyValue prop = new PropertyValue();
159                 prop.Name   = "Title";
160                 prop.Handle = -1; // n/a
161                 prop.Value  = name;
162                 props[ 0 ] = prop;
163 
164                 // Execute command "setPropertyValues".
165                 m_helper.executeCommand( newContent, "setPropertyValues", props );
166 
167                 /////////////////////////////////////////////////////////////////////
168                 // Write the new file to disk...
169                 /////////////////////////////////////////////////////////////////////
170 
171                 // Obtain document data for the new file.
172                 XInputStream data = stream;
173 
174                 // Fill argument structure...
175                 InsertCommandArgument arg = new InsertCommandArgument();
176                 arg.Data = data;
177                 arg.ReplaceExisting = false;
178 
179                 // Execute command "insert".
180                 m_helper.executeCommand( newContent, "insert", arg );
181                 result = true;
182             }
183         }
184         return result;
185     }
186 
187     /**
188      * Get new resource name.
189      *
190      *@return String    That contains the name
191      */
getName()192     public String getName() {
193         return m_name;
194     }
195 
196     /**
197      * Get source URL.
198      *
199      *@return String    That contains the source URL
200      */
getSourceURL()201     public String getSourceURL() {
202         return m_srcURL;
203     }
204 
205     /**
206      *  Get connect URL.
207      *
208      *@return   String    That contains the connect URL
209      */
getContentURL()210     public String getContentURL() {
211         return m_contenturl;
212     }
213 
214     /**
215      * Parse arguments
216      *
217      *@param      String[]   Arguments
218      *@exception  java.lang.Exception
219      */
parseArguments( String[] args )220     public void parseArguments( String[] args ) throws java.lang.Exception {
221 
222         String workdir = "";
223 
224         for ( int i = 0; i < args.length; i++ ) {
225             if ( args[i].startsWith( "-url=" )) {
226                 m_contenturl = args[i].substring( 5 );
227             } else if ( args[i].startsWith( "-name=" )) {
228                 m_name = args[i].substring( 6 );
229             } else if ( args[i].startsWith( "-srcURL=" )) {
230                 m_srcURL = args[i].substring( 8 );
231             } else if ( args[i].startsWith( "-workdir=" )) {
232                 workdir = args[i].substring( 9 );
233             } else if ( args[i].startsWith( "-help" ) ||
234                         args[i].startsWith( "-?" )) {
235                 printCmdLineUsage();
236                 System.exit( 0 );
237             }
238         }
239 
240         if ( m_contenturl == null || m_contenturl.equals( "" )) {
241             m_contenturl = Helper.getAbsoluteFileURLFromSystemPath( workdir );
242         }
243 
244         if ( m_name == null || m_name.equals( "" )) {
245             m_name = "created-resource-" + System.currentTimeMillis();
246         }
247 
248         if ( m_srcURL == null || m_srcURL.equals( "" )) {
249             m_srcURL = Helper.prependCurrentDirAsAbsoluteFileURL( "data/data.txt" );
250         }
251     }
252 
253     /**
254      * Print the commands options
255      */
printCmdLineUsage()256     public void printCmdLineUsage() {
257         System.out.println(
258             "Usage   : ResourceCreator -url=... -name=... -srcURL=... -workdir=..." );
259         System.out.println(
260             "Defaults: -url=<workdir> -name=created-resource-<uniquepostfix> -srcURL=<currentdir>/data/data.txt> -workdir=<currentdir>" );
261         System.out.println(
262             "\nExample : -url=file:///home/kai/ -name=newfile.txt -srcURL=file:///home/kai/sourcefile.txt" );
263     }
264 
265     /**
266      *  Create a new connection with the specific args to a running office and
267      *  create a new resource.
268      *
269      *@param  String[]   Arguments
270      */
main( String args[] )271     public static void main ( String args[] ) {
272         System.out.println( "\n" );
273         System.out.println(
274             "-----------------------------------------------------------------------" );
275         System.out.println(
276             "ResourceCreator - creates a new file in an existing file system folder." );
277         System.out.println(
278             " (Content for the new file can be retrieved from another file)." );
279         System.out.println(
280             "-----------------------------------------------------------------------" );
281         try {
282             ResourceCreator create = new ResourceCreator( args );
283             boolean result = create.createNewResource();
284             if ( result )  {
285                 System.out.println(
286                     "Creation of new resource " + create.getName() + " in folder: " +
287                     create.getContentURL() + " succeeded." );
288             } else  {
289                 System.out.println(
290                     "Creation of new resource " + create.getName() + " in folder: " +
291                     create.getContentURL() + " failed." );
292             }
293         } catch ( com.sun.star.ucb.CommandAbortedException e ) {
294             System.out.println( "Error: " + e );
295         } catch ( com.sun.star.uno.Exception e ) {
296             System.out.println( "Error: " + e );
297         } catch ( java.lang.Exception e ) {
298             System.out.println( "Error: " + e );
299         }
300         System.exit( 0 );
301     }
302 }
303