summaryrefslogtreecommitdiff
path: root/odk/examples/DevelopersGuide/OfficeDev/Linguistic/LinguisticExamples.java
blob: 887d8f35ffa3104cae0472fa8298c0fec77ba55d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*************************************************************************
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright 2000, 2010 Oracle and/or its affiliates.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *************************************************************************/

// used interfaces
import com.sun.star.uno.XComponentContext;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.linguistic2.XLinguServiceManager;
import com.sun.star.linguistic2.XSpellChecker;
import com.sun.star.linguistic2.XHyphenator;
import com.sun.star.linguistic2.XThesaurus;
import com.sun.star.linguistic2.XSpellAlternatives;
import com.sun.star.linguistic2.XHyphenatedWord;
import com.sun.star.linguistic2.XPossibleHyphens;
import com.sun.star.linguistic2.XMeaning;
import com.sun.star.linguistic2.XSearchableDictionaryList;
import com.sun.star.linguistic2.XLinguServiceEventListener;
import com.sun.star.linguistic2.LinguServiceEvent;
import com.sun.star.beans.XPropertySet;
import com.sun.star.beans.PropertyValue;
import com.sun.star.lang.EventObject;
import com.sun.star.lang.Locale;
import com.sun.star.uno.UnoRuntime;

public class LinguisticExamples
{
    // The remote office ocntext
    protected XComponentContext mxRemoteContext = null;
    // The MultiServiceFactory interface of the Office
    protected XMultiComponentFactory mxRemoteServiceManager = null;

    // The LinguServiceManager interface
    protected XLinguServiceManager mxLinguSvcMgr = null;

    // The SpellChecker interface
    protected XSpellChecker mxSpell = null;

    // The Hyphenator interface
    protected XHyphenator mxHyph = null;

    // The Thesaurus interface
    protected XThesaurus  mxThes = null;

    // The DictionaryList interface
    protected XSearchableDictionaryList  mxDicList = null;

    // The LinguProperties interface
    protected XPropertySet  mxLinguProps = null;


    public static void main(String args[])
    {
        // Create an instance of the class and call its begin method
        try {
            LinguisticExamples aExample = new LinguisticExamples();
            aExample.Connect();
            aExample.Run();
        } catch (Exception e) {
            System.err.println("failed to run examples");
            e.printStackTrace();
        }
    }


    public void Connect()
        throws java.lang.Exception
    {
        // get the remote office context. If necessary a new office
        // process is started
        mxRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
        System.out.println("Connected to a running office ...");
        mxRemoteServiceManager = mxRemoteContext.getServiceManager();
    }


    /** Get the LinguServiceManager to be used. For example to access spell
        checker, thesaurus and hyphenator, also the component may choose to
        register itself as listener to it in order to get notified of relevant
        events. */
    public boolean GetLinguSvcMgr()
        throws com.sun.star.uno.Exception
    {
        if (mxRemoteContext != null && mxRemoteServiceManager != null) {
            Object aObj = mxRemoteServiceManager.createInstanceWithContext(
                "com.sun.star.linguistic2.LinguServiceManager", mxRemoteContext );
            mxLinguSvcMgr = UnoRuntime.queryInterface(XLinguServiceManager.class, aObj);
        }
        return mxLinguSvcMgr != null;
    }


    /** Get the SpellChecker to be used.
    */
    public boolean GetSpell()
        throws com.sun.star.uno.RuntimeException
    {
        if (mxLinguSvcMgr != null)
            mxSpell = mxLinguSvcMgr.getSpellChecker();
        return mxSpell != null;
    }

    /** Get the Hyphenator to be used.
    */
    public boolean GetHyph()
        throws com.sun.star.uno.RuntimeException
    {
        if (mxLinguSvcMgr != null)
            mxHyph = mxLinguSvcMgr.getHyphenator();
        return mxHyph != null;
    }

    /** Get the Thesaurus to be used.
    */
    public boolean GetThes()
        throws com.sun.star.uno.RuntimeException
    {
        if (mxLinguSvcMgr != null)
            mxThes = mxLinguSvcMgr.getThesaurus();
        return mxThes != null;
    }


    public void Run()
        throws Exception
    {
        GetLinguSvcMgr();


        // list of property values to used in function calls below.
        // Only properties with values different from the (default) values
        // in the LinguProperties property set need to be supllied.
        // Thus we may stay with an empty list in order to use the ones
        // form the property set.
        PropertyValue[] aEmptyProps = new PropertyValue[0];

        // use american english as language
        Locale aLocale = new Locale("en","US","");



        // another list of property values to used in function calls below.
        // Only properties with values different from the (default) values
        // in the LinguProperties property set need to be supllied.
        PropertyValue[] aProps = new PropertyValue[1];
        aProps[0] = new PropertyValue();
        aProps[0].Name  = "IsGermanPreReform";
        aProps[0].Value = Boolean.TRUE;


        GetSpell();
        if (mxSpell !=  null)
        {
            // test with correct word
            String aWord = "horseback";
            boolean bIsCorrect = mxSpell.isValid( aWord, aLocale, aEmptyProps );
            System.out.println( aWord + ": " +  bIsCorrect );

            // test with incorrect word
            aWord = "course";
            bIsCorrect = mxSpell.isValid( aWord, aLocale , aEmptyProps );
            System.out.println( aWord + ": " +  bIsCorrect );


            aWord = "house";
            XSpellAlternatives xAlt = mxSpell.spell( aWord, aLocale, aEmptyProps );
            if (xAlt == null)
                System.out.println( aWord + " is correct." );
            else
            {
                System.out.println( aWord + " is not correct. A list of proposals follows." );
                String[] aAlternatives = xAlt.getAlternatives();
                if (aAlternatives.length == 0)
                    System.out.println( "no proposal found." );
                else
                {
                    for (int i = 0; i < aAlternatives.length; ++i)
                        System.out.println( aAlternatives[i] );
                }
            }
        }


        GetHyph();
        if (mxHyph != null)
        {
            // maximum number of characters to remain before the hyphen
            // character in the resulting word of the hyphenation
            short nMaxLeading = 6;

            XHyphenatedWord xHyphWord = mxHyph.hyphenate( "waterfall",
                                                          aLocale, nMaxLeading ,
                                                          aEmptyProps );
            if (xHyphWord == null)
                System.out.println( "no valid hyphenation position found" );
            else
            {
                System.out.println( "valid hyphenation pos found at "
                                    + xHyphWord.getHyphenationPos()
                        + " in " + xHyphWord.getWord() );
                System.out.println( "hyphenation char will be after char "
                                    + xHyphWord.getHyphenPos()
                        + " in " + xHyphWord.getHyphenatedWord() );
            }


            //! Note: 'aProps' needs to have set 'IsGermanPreReform' to true!
            xHyphWord = mxHyph.queryAlternativeSpelling( "Schiffahrt",
                                new Locale("de","DE",""), (short)4, aProps );
            if (xHyphWord == null)
                System.out.println( "no alternative spelling found at specified position." );
            else
            {
                if (xHyphWord.isAlternativeSpelling())
                    System.out.println( "alternative spelling detectetd!" );
                System.out.println( "valid hyphenation pos found at "
                                    + xHyphWord.getHyphenationPos()
                        + " in " + xHyphWord.getWord() );
                System.out.println( "hyphenation char will be after char "
                                    + xHyphWord.getHyphenPos()
                        + " in " + xHyphWord.getHyphenatedWord() );
            }


            XPossibleHyphens xPossHyph = mxHyph.createPossibleHyphens("waterfall",
                                                                      aLocale,
                                                                      aEmptyProps );
            if (xPossHyph == null)
                System.out.println( "no hyphenation positions found." );
            else
                System.out.println( xPossHyph.getPossibleHyphens() );
        }


        GetThes();
        if (mxThes != null)
        {
            XMeaning[] xMeanings = mxThes.queryMeanings("house", aLocale,
                                                        aEmptyProps );
            if (xMeanings == null)
                System.out.println( "nothing found." );
            else
            {
                for (int i = 0; i < xMeanings.length; ++i)
                {
                    System.out.println( "Meaning: " + xMeanings[i].getMeaning() );
                    String[] aSynonyms = xMeanings[i].querySynonyms();
                    for (int k = 0; k < aSynonyms.length; ++k)
                        System.out.println( "    Synonym: " + aSynonyms[k] );
                }
            }
        }



        XLinguServiceEventListener aClient = new Client();

        // get access to LinguProperties property set
        Object aObj = mxRemoteServiceManager.createInstanceWithContext(
            "com.sun.star.linguistic2.LinguProperties", mxRemoteContext);
        XPropertySet aLinguProps = UnoRuntime.queryInterface(
            XPropertySet.class,aObj);

        // set a spellchecker and hyphenator property value to a defined state
        try {
            aLinguProps.setPropertyValue("IsGermanPreReform", Boolean.TRUE);
        } catch (Exception e) {
        }

        // now add the client as listener to the service manager to
        // get informed when spellchecking or hyphenation may produce
        // different results then before.
        mxLinguSvcMgr.addLinguServiceManagerListener(aClient);

        // change that property value in order to trigger a property change
        // event that eventually results in the listeners
        // 'processLinguServiceEvent' function being called
        try {
            aLinguProps.setPropertyValue("IsGermanPreReform", Boolean.FALSE);
        } catch (Exception e) {
        }

        //! keep the listener and the program alive until the event will
        //! be launched.
        //! There is a voluntary delay before launching the event!
        // Of course this code would usually not be in a *real* client
        // its
        synchronized(this) {
            try {
                this.wait(4000);
            } catch(Exception e) {

            }
        }

        //! remove listener before programm termination.
        //! should not be omitted.
        mxLinguSvcMgr.removeLinguServiceManagerListener(aClient);


        System.exit(0);
    }

    /** simple sample implementation of a clients XLinguServiceEventListener
     *  interface implementation
     */
    private class Client
            implements XLinguServiceEventListener
    {
        public void disposing ( EventObject aEventObj )
        {
            //! any references to the EventObjects source have to be
            //! released here now!

            System.out.println("object listened to will be disposed");
        }

        public void processLinguServiceEvent( LinguServiceEvent aServiceEvent )
        {
            //! do here whatever you think needs to be done depending
            //! on the event received (e.g. trigger background spellchecking
            //! or hyphenation again.)

            System.out.println("Listener called");
        }
    }

}