cid#1607171 Data race condition
[LibreOffice.git] / swext / mediawiki / src / com / sun / star / wiki / Helper.java
blobe43091d2e269faac356ecf1c268845f2a30f7230
1 /*
2 * This file is part of the LibreOffice project.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 * This file incorporates work covered by the following license notice:
10 * Licensed to the Apache Software Foundation (ASF) under one or more
11 * contributor license agreements. See the NOTICE file distributed
12 * with this work for additional information regarding copyright
13 * ownership. The ASF licenses this file to you under the Apache
14 * License, Version 2.0 (the "License"); you may not use this file
15 * except in compliance with the License. You may obtain a copy of
16 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
19 package com.sun.star.wiki;
21 import com.sun.star.awt.MessageBoxButtons;
22 import com.sun.star.awt.MessageBoxType;
23 import com.sun.star.awt.XControl;
24 import com.sun.star.awt.XDialog;
25 import com.sun.star.awt.XMessageBox;
26 import com.sun.star.awt.XMessageBoxFactory;
27 import com.sun.star.awt.XWindowPeer;
28 import com.sun.star.beans.NamedValue;
29 import com.sun.star.beans.PropertyValue;
30 import com.sun.star.beans.XPropertySet;
31 import com.sun.star.container.XContainerQuery;
32 import com.sun.star.container.XEnumeration;
33 import com.sun.star.container.XNameAccess;
34 import com.sun.star.container.XNameContainer;
35 import com.sun.star.document.XDocumentPropertiesSupplier;
36 import com.sun.star.document.XDocumentProperties;
37 import com.sun.star.frame.XModel;
38 import com.sun.star.frame.XModuleManager;
39 import com.sun.star.io.XInputStream;
40 import com.sun.star.io.XOutputStream;
41 import com.sun.star.lang.IllegalArgumentException;
42 import com.sun.star.lang.XMultiComponentFactory;
43 import com.sun.star.lang.XMultiServiceFactory;
44 import com.sun.star.lang.XComponent;
45 import com.sun.star.system.SystemShellExecuteFlags;
46 import com.sun.star.system.XSystemShellExecute;
47 import com.sun.star.task.UrlRecord;
48 import com.sun.star.task.XInteractionHandler;
49 import com.sun.star.task.XMasterPasswordHandling;
50 import com.sun.star.task.XPasswordContainer;
51 import com.sun.star.uno.AnyConverter;
52 import com.sun.star.uno.UnoRuntime;
53 import com.sun.star.uno.XComponentContext;
54 import com.sun.star.util.XChangesBatch;
55 import java.net.*;
56 import java.io.*;
57 import javax.net.ssl.HttpsURLConnection;
58 import javax.net.ssl.SSLContext;
59 import javax.net.ssl.SSLException;
60 import javax.swing.text.html.HTMLEditorKit;
63 public class Helper
65 public static final int GENERALSEND_ERROR = 0;
66 public static final int NOWIKIFILTER_ERROR = 1;
67 public static final int NOURLCONNECTION_ERROR = 2;
68 public static final int WRONGLOGIN_ERROR = 3;
69 public static final int INVALIDURL_ERROR = 4;
70 public static final int NOURL_ERROR = 5;
72 public static final int DLG_SENDTITLE = 6;
73 public static final int DLG_WIKIARTICLE = 7;
75 public static final int DLG_OK = 9;
77 // 11 is reserved
78 public static final int DLG_ADDBUTTON = 12;
79 public static final int DLG_EDITBUTTON = 13;
80 public static final int DLG_SENDBUTTON = 14;
81 public static final int DLG_REMOVEBUTTON = 15;
83 public static final int DLG_EDITSETTING_URLLABEL = 16;
84 public static final int DLG_EDITSETTING_USERNAMELABEL = 17;
85 public static final int DLG_EDITSETTING_PASSWORDLABEL = 18;
87 public static final int DLG_SENDTOMEDIAWIKI_LABEL1 = 20;
88 public static final int DLG_SENDTOMEDIAWIKI_LABEL2 = 21;
89 public static final int DLG_SENDTOMEDIAWIKI_LABEL3 = 22;
90 public static final int DLG_SENDTOMEDIAWIKI_MINORCHECK = 23;
91 public static final int DLG_SENDTOMEDIAWIKI_BROWSERCHECK = 24;
92 public static final int UNKNOWNCERT_ERROR = 25;
93 public static final int DLG_MEDIAWIKI_TITLE = 26;
94 public static final int DLG_EDITSETTING_ACCOUNTLINE = 27;
95 public static final int DLG_EDITSETTING_WIKILINE = 28;
96 public static final int DLG_EDITSETTING_SAVEBOX = 29;
97 public static final int CANCELSENDING_ERROR = 30;
98 public static final int DLG_MEDIAWIKIEXTENSION_STRING = 31;
99 public static final int DLG_WIKIPAGEEXISTS_LABEL1 = 32;
101 private static final int STRINGS_NUM = 33;
103 private static final String[] m_pEntryNames = { "GeneralSendError",
104 "NoWikiFilter",
105 "NoConnectionToURL",
106 "WrongLogin",
107 "InvalidURL",
108 "NoURL",
109 "Dlg_SendTitle",
110 "Dlg_WikiArticle",
111 "Dlg_No",
112 "Dlg_OK",
113 "Dlg_Yes",
114 null, // reserved
115 "Dlg_AddButton",
116 "Dlg_EditButton",
117 "Dlg_SendButton",
118 "Dlg_RemoveButton",
119 "Dlg_EditSetting_UrlLabel",
120 "Dlg_EditSetting_UsernameLabel",
121 "Dlg_EditSetting_PasswordLabel",
122 "Dlg_NewWikiPage_Label1",
123 "Dlg_SendToMediaWiki_Label1",
124 "Dlg_SendToMediaWiki_Label2",
125 "Dlg_SendToMediaWiki_Label3",
126 "Dlg_SendToMediaWiki_MinorCheck",
127 "Dlg_SendToMediaWiki_BrowserCheck",
128 "UnknownCert",
129 "Dlg_MediaWiki_Title",
130 "Dlg_EditSetting_AccountLine",
131 "Dlg_EditSetting_WikiLine",
132 "Dlg_EditSetting_SaveBox",
133 "CancelSending",
134 "Dlg_MediaWiki_Extension_String",
135 "Dlg_WikiPageExists_Label1" };
137 private static String[] m_pConfigStrings;
139 private static boolean m_bAllowConnection = true;
141 private static Boolean m_bShowInBrowser = null;
143 private static XPasswordContainer m_xPasswordContainer;
144 private static XInteractionHandler m_xInteractionHandler;
146 synchronized protected static String GetLocalizedString( XComponentContext xContext, int nID )
147 throws com.sun.star.uno.Exception
149 if ( nID >= STRINGS_NUM )
150 throw new com.sun.star.uno.RuntimeException();
152 if ( m_pConfigStrings == null )
154 XNameAccess xNameAccess = GetConfigNameAccess( xContext, "org.openoffice.Office.Custom.WikiExtension/Strings" );
156 String[] pStrings = new String[STRINGS_NUM];
157 for ( int nInd = 0; nInd < STRINGS_NUM; nInd++ )
158 if ( m_pEntryNames[nInd] != null )
159 pStrings[nInd] = AnyConverter.toString( xNameAccess.getByName( m_pEntryNames[nInd] ) );
160 else
161 pStrings[nInd] = "";
163 m_pConfigStrings = pStrings;
166 return m_pConfigStrings[nID];
169 synchronized protected static void AllowConnection( boolean bAllow )
171 m_bAllowConnection = bAllow;
172 // TODO: how to shut down any pending connections?
173 // hope it doesn't matter?
176 synchronized protected static boolean IsConnectionAllowed()
178 return m_bAllowConnection;
181 synchronized protected static boolean GetShowInBrowserByDefault( XComponentContext xContext )
183 if ( m_bShowInBrowser == null )
187 XNameAccess xAccess = Helper.GetConfigNameAccess( xContext, "org.openoffice.Office.Custom.WikiExtension/Settings" );
188 m_bShowInBrowser = Boolean.valueOf( AnyConverter.toBoolean( xAccess.getByName( "PreselectShowBrowser" ) ) );
190 catch( com.sun.star.uno.Exception e )
192 e.printStackTrace();
196 return m_bShowInBrowser != null ? m_bShowInBrowser.booleanValue() : false;
199 synchronized protected static void SetShowInBrowserByDefault( XComponentContext xContext, boolean bValue )
203 m_bShowInBrowser = Boolean.valueOf( bValue );
205 XPropertySet xProps = Helper.GetConfigProps( xContext, "org.openoffice.Office.Custom.WikiExtension/Settings" );
206 xProps.setPropertyValue( "PreselectShowBrowser", Boolean.valueOf( bValue ) );
207 XChangesBatch xBatch = UnoRuntime.queryInterface( XChangesBatch.class, xProps );
208 if ( xBatch != null )
209 xBatch.commitChanges();
211 catch( Exception e )
213 e.printStackTrace();
217 synchronized protected static XPasswordContainer GetPasswordContainer( XComponentContext xContext )
218 throws com.sun.star.uno.Exception
220 if ( m_xPasswordContainer == null && xContext != null )
222 XMultiComponentFactory xFactory = xContext.getServiceManager();
223 if ( xFactory != null )
224 m_xPasswordContainer = UnoRuntime.queryInterface(
225 XPasswordContainer.class,
226 xFactory.createInstanceWithContext( "com.sun.star.task.PasswordContainer", xContext ) );
229 if ( m_xPasswordContainer == null )
230 throw new com.sun.star.uno.RuntimeException();
232 return m_xPasswordContainer;
235 synchronized protected static XInteractionHandler GetInteractionHandler( XComponentContext xContext )
236 throws com.sun.star.uno.Exception
238 if ( m_xInteractionHandler == null && xContext != null )
240 XMultiComponentFactory xFactory = xContext.getServiceManager();
241 if ( xFactory != null )
242 m_xInteractionHandler = UnoRuntime.queryInterface(
243 XInteractionHandler.class,
244 xFactory.createInstanceWithContext( "com.sun.star.task.InteractionHandler", xContext ) );
247 if ( m_xInteractionHandler == null )
248 throw new com.sun.star.uno.RuntimeException();
250 return m_xInteractionHandler;
253 protected static String GetMainURL( String sWebPage, String sVURL )
255 String sResultURL = "";
258 StringReader aReader = new StringReader( sWebPage );
259 HTMLEditorKit.Parser aParser = GetHTMLParser();
260 EditPageParser aCallback = new EditPageParser();
262 aParser.parse( aReader, aCallback, true );
263 sResultURL = aCallback.m_sMainURL;
265 if ( !sResultURL.startsWith( "http" ) )
267 //if the url is only relative then complete it
268 URL aURL = new URL( sVURL );
269 sResultURL = aURL.getProtocol() + "://" + aURL.getHost() + sResultURL;
272 catch( Exception e )
274 e.printStackTrace();
277 if ( sResultURL.length() == 0 )
279 // usually that should not happen
280 // workaround: try to get index.php from the provided URL
281 int nIndex = sVURL.indexOf( "index.php" );
282 if ( nIndex >= 0 )
283 sResultURL = sVURL.substring( 0, nIndex );
286 return sResultURL;
289 protected static String GetRedirectURL( String sWebPage, String sURL )
291 //scrape the HTML source and find the EditURL
292 // TODO/LATER: Use parser in future
294 int nInd = sWebPage.indexOf( "http-equiv=\"refresh\"" );
295 if ( nInd == -1 )
296 return "";
298 String sResultURL = "";
299 int nContent = sWebPage.indexOf( "content=", nInd );
300 if ( nContent > 0 )
302 int nURL = sWebPage.indexOf( "URL=", nContent );
303 if ( nURL > 0 )
305 int nEndURL = sWebPage.indexOf('"', nURL );
306 if ( nEndURL > 0 )
307 sResultURL = sWebPage.substring( nURL + 4, nEndURL );
313 URL aURL = new URL( sURL );
314 if ( !sResultURL.startsWith( aURL.getProtocol() ))
316 //if the url is only relative then complete it
317 if ( sResultURL.startsWith( "/" ) )
318 sResultURL = aURL.getProtocol() + "://" + aURL.getHost() + sResultURL;
319 else
320 sResultURL = aURL.getProtocol() + "://" + aURL.getHost() + aURL.getPath() + sResultURL;
323 catch ( MalformedURLException ex )
325 ex.printStackTrace();
328 return sResultURL;
332 protected static String CreateTempFile( XComponentContext xContext )
334 String sURL = "";
337 Object oTempFile = xContext.getServiceManager().createInstanceWithContext( "com.sun.star.io.TempFile", xContext );
338 XPropertySet xPropertySet = UnoRuntime.queryInterface( XPropertySet.class, oTempFile );
339 xPropertySet.setPropertyValue( "RemoveFile", Boolean.FALSE );
340 sURL = ( String ) xPropertySet.getPropertyValue( "Uri" );
342 XInputStream xInputStream = UnoRuntime.queryInterface( XInputStream.class, oTempFile );
343 xInputStream.closeInput();
344 XOutputStream xOutputStream = UnoRuntime.queryInterface( XOutputStream.class, oTempFile );
345 xOutputStream.closeOutput();
346 } catch ( com.sun.star.uno.Exception ex )
348 ex.printStackTrace();
350 return sURL;
353 private static void close(BufferedReader c) {
354 if (c == null) return;
355 try {
356 c.close();
357 } catch (IOException e) {
358 e.printStackTrace();
362 protected static String EachLine( String sURL )
364 String sText = "";
365 BufferedReader aBufReader = null;
368 URL aURL = new URL( sURL );
369 File aFile = new File( aURL.getFile() );
370 InputStreamReader aInputReader = new InputStreamReader( new FileInputStream( aFile ), "UTF-8" );
371 aBufReader = new BufferedReader( aInputReader );
373 StringBuffer aBuf = new StringBuffer();
374 String sEachLine = aBufReader.readLine();
376 while( sEachLine != null )
378 aBuf.append( sEachLine );
379 aBuf.append( "\n" );
381 sEachLine = aBufReader.readLine();
383 sText = aBuf.toString();
385 aBufReader.close();
386 } catch ( Exception e ) {
387 e.printStackTrace();
389 finally {
390 close(aBufReader);
392 return sText;
395 protected static String GetDocTitle( XModel xDoc )
397 XDocumentPropertiesSupplier xDocPropSup =
398 UnoRuntime.queryInterface(XDocumentPropertiesSupplier.class, xDoc);
399 XDocumentProperties xDocProps = xDocPropSup.getDocumentProperties();
400 return xDocProps.getTitle();
403 protected static void SetDocTitle( XModel xDoc, String sTitle )
405 XDocumentPropertiesSupplier xDocPropSup =
406 UnoRuntime.queryInterface(XDocumentPropertiesSupplier.class, xDoc);
407 XDocumentProperties xDocProps = xDocPropSup.getDocumentProperties();
408 xDocProps.setTitle(sTitle);
411 protected static String GetDocServiceName( XComponentContext xContext, XModel xModel )
413 String aDocServiceName = "";
414 if ( xModel != null && xContext != null )
418 XMultiComponentFactory xFactory = xContext.getServiceManager();
419 if ( xFactory == null )
420 throw new com.sun.star.uno.RuntimeException();
422 Object oModuleManager = xFactory.createInstanceWithContext( "com.sun.star.frame.ModuleManager", xContext );
423 XModuleManager xModuleManager = UnoRuntime.queryInterface( XModuleManager.class, oModuleManager );
424 if ( xModuleManager != null )
425 aDocServiceName = xModuleManager.identify( xModel );
427 catch( java.lang.Exception e )
429 e.printStackTrace();
433 return aDocServiceName;
436 protected static String GetFilterName( XComponentContext xContext, String aTypeName, String aDocServiceName )
438 if ( xContext == null || aTypeName == null || aTypeName.length() == 0
439 || aDocServiceName == null || aDocServiceName.length() == 0 ) {
440 return "";
442 String aFilterName = "";
445 Object oFilterFactory = xContext.getServiceManager().createInstanceWithContext( "com.sun.star.document.FilterFactory", xContext );
446 XContainerQuery xQuery = UnoRuntime.queryInterface( XContainerQuery.class, oFilterFactory );
447 if ( xQuery != null )
449 NamedValue[] aRequest = new NamedValue[2];
450 aRequest[0] = new NamedValue( "Type", aTypeName );
451 aRequest[1] = new NamedValue( "DocumentService", aDocServiceName );
453 XEnumeration xSet = xQuery.createSubSetEnumerationByProperties( aRequest );
454 if ( xSet != null )
456 boolean bAcceptable = false;
457 while ( xSet.hasMoreElements() && !bAcceptable )
459 PropertyValue[] pFilterProps = ( PropertyValue[] )AnyConverter.toArray( xSet.nextElement() );
460 if ( pFilterProps != null )
462 int nLen = pFilterProps.length;
463 String aTmpFilter = null;
465 for ( int nInd = 0; nInd < nLen; nInd++ )
467 if ( pFilterProps[nInd].Name.equals( "Name" ) )
468 aTmpFilter = AnyConverter.toString( pFilterProps[nInd].Value );
469 else if ( pFilterProps[nInd].Name.equals( "Flags" ) )
470 bAcceptable = ( ( AnyConverter.toInt( pFilterProps[nInd].Value ) & 2 ) == 2 ); // must allow export
473 if ( bAcceptable )
474 aFilterName = aTmpFilter;
480 catch( java.lang.Exception e )
482 e.printStackTrace();
485 return aFilterName;
488 private static XMultiServiceFactory GetConfigurationProvider( XComponentContext xContext )
489 throws com.sun.star.uno.Exception
491 XMultiServiceFactory xConfigurationProvider = null;
492 if ( xContext != null )
494 XMultiComponentFactory xFactory = xContext.getServiceManager();
495 Object oConfigProvider = xFactory.createInstanceWithContext( "com.sun.star.configuration.ConfigurationProvider", xContext );
496 xConfigurationProvider = UnoRuntime.queryInterface( XMultiServiceFactory.class, oConfigProvider );
499 if ( xConfigurationProvider == null )
500 throw new com.sun.star.uno.RuntimeException();
502 return xConfigurationProvider;
505 private static Object GetConfig( XComponentContext xContext, String sNodepath, boolean bWriteAccess )
506 throws com.sun.star.uno.Exception
508 if ( xContext == null || sNodepath == null )
509 throw new com.sun.star.uno.RuntimeException();
511 PropertyValue aVal = new PropertyValue();
512 aVal.Name = "nodepath";
513 aVal.Value = sNodepath;
514 Object[] aArgs = new Object[1];
515 aArgs[0] = aVal;
517 return GetConfigurationProvider( xContext ).createInstanceWithArguments(
518 ( bWriteAccess ? "com.sun.star.configuration.ConfigurationUpdateAccess"
519 : "com.sun.star.configuration.ConfigurationAccess" ),
520 aArgs );
523 private static XPropertySet GetConfigProps( XComponentContext xContext, String sNodepath )
524 throws com.sun.star.uno.Exception
526 XPropertySet xProps = UnoRuntime.queryInterface( XPropertySet.class, GetConfig( xContext, sNodepath, true ) );
527 if ( xProps == null )
528 throw new com.sun.star.uno.RuntimeException();
530 return xProps;
534 protected static XNameContainer GetConfigNameContainer( XComponentContext xContext, String sNodepath )
535 throws com.sun.star.uno.Exception
537 XNameContainer xContainer = UnoRuntime.queryInterface( XNameContainer.class, GetConfig( xContext, sNodepath, true ) );
538 if ( xContainer == null )
539 throw new com.sun.star.uno.RuntimeException();
541 return xContainer;
544 protected static XNameAccess GetConfigNameAccess( XComponentContext xContext, String sNodepath )
545 throws com.sun.star.uno.Exception
547 XNameAccess xNameAccess = UnoRuntime.queryInterface( XNameAccess.class, GetConfig( xContext, sNodepath, false ) );
548 if ( xNameAccess == null )
549 throw new com.sun.star.uno.RuntimeException();
551 return xNameAccess;
554 private static Proxy GetConfigurationProxy(URI uri, XComponentContext xContext)
556 assert(uri != null);
557 assert(xContext != null);
561 XNameAccess xNameAccess = GetConfigNameAccess( xContext, "org.openoffice.Inet/Settings" );
563 int nProxyType = AnyConverter.toInt( xNameAccess.getByName( "ooInetProxyType" ) );
564 if ( nProxyType == 0 ) {
565 return Proxy.NO_PROXY;
566 } else {
567 if ( nProxyType == 1 )
569 // system proxy
570 return null;
572 else if ( nProxyType == 2 )
574 String aProxyNameProp = "ooInetHTTPProxyName";
575 String aProxyPortProp = "ooInetHTTPProxyPort";
577 if (uri.getScheme().equals("https"))
579 aProxyNameProp = "ooInetHTTPSProxyName";
580 aProxyPortProp = "ooInetHTTPSProxyPort";
583 String aProxyName = AnyConverter.toString( xNameAccess.getByName( aProxyNameProp ) );
585 int nProxyPort = 80;
587 Object aPortNo = xNameAccess.getByName( aProxyPortProp );
588 if ( !AnyConverter.isVoid( aPortNo ) )
589 nProxyPort = AnyConverter.toInt( aPortNo );
591 if ( nProxyPort == -1 )
592 nProxyPort = 80;
594 // TODO: check whether the URL is in the NoProxy list
595 InetSocketAddress address = new InetSocketAddress(aProxyName, nProxyPort);
596 return new Proxy(Proxy.Type.HTTP, address);
600 catch( java.lang.Exception e )
602 e.printStackTrace();
604 return null; // invalid configuration value?
607 protected static void ShowURLInBrowser( XComponentContext xContext, String sURL )
609 if ( xContext != null && sURL != null && sURL.length() > 0 )
613 Object oSystemShell = xContext.getServiceManager().createInstanceWithContext( "com.sun.star.system.SystemShellExecute", xContext );
614 XSystemShellExecute xSystemShell = UnoRuntime.queryInterface( XSystemShellExecute.class, oSystemShell );
615 if ( xSystemShell != null )
616 xSystemShell.execute( sURL, "", SystemShellExecuteFlags.URIS_ONLY );
618 catch( Exception e )
620 e.printStackTrace();
625 protected static HttpURLConnection PrepareMethod(String method, URI uri, XComponentContext xContext)
626 throws WikiCancelException, IOException, SSLException
628 assert(method != null);
629 assert(uri != null);
630 assert(xContext != null);
632 if (!IsConnectionAllowed()) {
633 throw new WikiCancelException();
636 if (java.net.CookieHandler.getDefault() == null) {
637 // set a cookie manager so cookies don't get lost
638 // apparently it's not possible to do that on a per-connection
639 // basis but only globally?
640 java.net.CookieHandler.setDefault(new java.net.CookieManager());
643 Proxy proxy = GetConfigurationProxy(uri, xContext);
644 HttpURLConnection conn = null;
645 if (proxy != null) {
646 conn = (HttpURLConnection) uri.toURL().openConnection(proxy);
647 } else {
648 conn = (HttpURLConnection) uri.toURL().openConnection();
651 boolean isAllowedInsecure;
652 try {
653 XNameAccess xNameAccess = GetConfigNameAccess(xContext, "org.openoffice.Office.Security/Net");
654 isAllowedInsecure = AnyConverter.toBoolean(xNameAccess.getByName("AllowInsecureProtocols"));
655 } catch (Exception e) {
656 throw new RuntimeException("failed to read configuration", e);
658 if (!isAllowedInsecure) {
659 if (!uri.getScheme().equals("https")) {
660 throw new IllegalArgumentException("insecure connection not allowed by configuration", null, (short)0);
662 try {
663 SSLContext context = SSLContext.getInstance("TLSv1.2");
664 context.init(null, null, null); // defaults
665 ((HttpsURLConnection) conn).setSSLSocketFactory(context.getSocketFactory());
666 } catch (Exception e) {
667 throw new RuntimeException("failed to create SSLContext", e);
670 else if (uri.getScheme().equals("https") && AllowUnknownCert(xContext, uri.getHost()))
672 // let unknown certificates be accepted
673 ((HttpsURLConnection) conn).setSSLSocketFactory(new WikiProtocolSocketFactory());
676 // enable this to help debug connections where TLS gets in the way
677 // ((HttpsURLConnection) conn).setSSLSocketFactory(new LoggingProtocolSocketFactory());
679 conn.setRequestMethod(method);
680 // TODO: is it possible to read the version from the extension metadata?
681 conn.setRequestProperty("User-Agent", "LibreOffice Wiki Publisher 1.2.0");
682 // note: don't connect yet so that the caller can do some further setup
684 return conn;
687 protected static String ReadResponseBody(HttpURLConnection conn)
688 throws IOException
690 String ret = null;
691 InputStream stream = conn.getInputStream();
692 try {
693 // there doesn't seem to be an easier way get the content encoding
694 String type = conn.getContentType();
695 String charset = "ISO-8859-1"; // default in RFC2616
696 for (String param : type.split(";")) {
697 if (param.trim().toLowerCase().startsWith("charset=")) {
698 charset = param.trim().substring("charset=".length());
699 break;
702 BufferedReader br =
703 new BufferedReader(new InputStreamReader(stream, charset));
704 StringBuilder buf = new StringBuilder();
705 String line;
706 while ((line = br.readLine()) != null) {
707 buf.append(line);
709 ret = buf.toString();
710 } finally {
711 stream.close();
713 return ret;
716 private static class HTMLParse extends HTMLEditorKit
719 @Override
720 public HTMLEditorKit.Parser getParser()
722 return super.getParser();
726 protected static HTMLEditorKit.Parser GetHTMLParser()
728 return new HTMLParse().getParser();
731 private static boolean LoginReportsError( String sRespond )
733 boolean bResult = true;
734 if ( sRespond != null )
738 StringReader aReader = new StringReader( sRespond );
739 HTMLEditorKit.Parser aParser = GetHTMLParser();
740 EditPageParser aCallback = new EditPageParser();
742 aParser.parse( aReader, aCallback, true );
743 bResult = ( aCallback.m_nErrorInd >= 0 );
745 catch( Exception e )
747 e.printStackTrace();
751 return bResult;
754 private static String GetLoginToken( String sLoginPage )
756 String sResult = "";
757 if ( sLoginPage != null && sLoginPage.length() > 0 )
761 StringReader aReader = new StringReader( sLoginPage );
762 HTMLEditorKit.Parser aParser = Helper.GetHTMLParser();
763 EditPageParser aCallbacks = new EditPageParser();
765 aParser.parse( aReader, aCallbacks, true );
766 sResult = aCallbacks.m_sLoginToken;
768 catch( Exception e )
770 e.printStackTrace();
774 return sResult;
777 protected static boolean Login(URI aMainURL, String sWikiUser, String sWikiPass, XComponentContext xContext)
778 throws java.io.IOException, WikiCancelException, URISyntaxException
780 boolean success = false;
782 if ( sWikiUser != null && sWikiPass != null && xContext != null )
784 String sLoginPage = null;
785 URI aURI = new URI(aMainURL.toString() + "index.php?title=Special:Userlogin");
786 HttpURLConnection connGet = PrepareMethod("GET", aURI, xContext);
787 connGet.setInstanceFollowRedirects(true);
789 connGet.connect();
790 int nResultCode = connGet.getResponseCode();
791 if (nResultCode == 200) {
792 sLoginPage = ReadResponseBody(connGet);
795 if ( sLoginPage != null )
797 String sLoginToken = GetLoginToken( sLoginPage );
799 URI aPostURI = new URI(aMainURL.toString() + "index.php?title=Special:Userlogin&action=submitlogin");
801 HttpURLConnection connPost = PrepareMethod("POST", aPostURI, xContext);
802 connPost.setInstanceFollowRedirects(true);
803 connPost.setDoInput(true);
804 connPost.setDoOutput(true);
805 connPost.connect();
807 OutputStreamWriter post = new OutputStreamWriter(connPost.getOutputStream(), "UTF-8");
810 post.write("wpName=");
811 post.write(URLEncoder.encode(sWikiUser, "UTF-8"));
812 post.write("&wpRemember=1");
813 post.write("&wpPassword=");
814 post.write(URLEncoder.encode(sWikiPass, "UTF-8"));
816 if (sLoginToken.length() > 0) {
817 post.write("&wpLoginToken=");
818 post.write(URLEncoder.encode(sLoginToken, "UTF-8"));
821 String[][] pArgs = GetSpecialArgs( xContext, aMainURL.getHost() );
822 if ( pArgs != null )
823 for ( int nArgInd = 0; nArgInd < pArgs.length; nArgInd++ )
824 if ( pArgs[nArgInd].length == 2 && pArgs[nArgInd][0] != null && pArgs[nArgInd][1] != null )
826 post.write("&");
827 post.write(URLEncoder.encode(pArgs[nArgInd][0], "UTF-8"));
828 post.write("=");
829 post.write(URLEncoder.encode(pArgs[nArgInd][0], "UTF-8"));
832 post.flush();
834 finally
836 post.close();
839 nResultCode = connPost.getResponseCode();
841 if ( nResultCode == 200 )
843 String sResult = ReadResponseBody(connPost);
844 if ( !LoginReportsError( sResult ) )
845 success = true;
850 return success;
853 protected static String[] GetPasswordsForURLAndUser( XComponentContext xContext, String sURL, String sUserName )
855 String[] aResult = null;
859 if ( xContext != null && sURL != null && sURL.length() > 0 && sUserName != null && sUserName.length() > 0 )
861 UrlRecord aRec = GetPasswordContainer( xContext ).findForName( sURL, sUserName, GetInteractionHandler( xContext ) );
862 if ( aRec != null && aRec.UserList != null && aRec.UserList.length > 0
863 && aRec.UserList[0].UserName.equals( sUserName ) )
864 aResult = aRec.UserList[0].Passwords;
867 catch( Exception e )
869 e.printStackTrace();
872 return aResult;
875 protected static boolean PasswordStoringIsAllowed( XComponentContext xContext )
877 boolean bResult = false;
880 XMasterPasswordHandling xMasterHdl = UnoRuntime.queryInterface( XMasterPasswordHandling.class, GetPasswordContainer( xContext ) );
881 if ( xMasterHdl != null )
882 bResult = xMasterHdl.isPersistentStoringAllowed();
884 catch( Exception e )
886 e.printStackTrace();
889 return bResult;
892 protected static void ShowError( XComponentContext xContext, XDialog xDialog, int nTitleID, int nErrorID, String sArg, boolean bQuery )
894 XWindowPeer xPeer = null;
895 XControl xControl = UnoRuntime.queryInterface( XControl.class, xDialog );
896 if ( xControl != null )
897 xPeer = xControl.getPeer();
898 ShowError( xContext, xPeer, nTitleID, nErrorID, sArg, bQuery );
901 protected static boolean ShowError( XComponentContext xContext, XWindowPeer xParentPeer, int nTitleID, int nErrorID, String sArg, boolean bQuery )
903 boolean bResult = false;
905 if ( xContext != null && nErrorID >= 0 && nErrorID < STRINGS_NUM )
907 String sError = null;
908 String sTitle = "";
912 sError = GetLocalizedString( xContext, nErrorID );
913 if ( sError != null && sArg != null )
914 sError = sError.replaceAll( "\\$ARG1", sArg );
916 sTitle = GetLocalizedString( xContext, nTitleID );
918 catch( Exception e )
920 e.printStackTrace();
923 if ( sError == null )
924 sError = "Error: " + nErrorID;
926 if ( xParentPeer != null )
928 XMessageBoxFactory xMBFactory = null;
929 XMessageBox xMB = null;
932 XMultiComponentFactory xFactory = xContext.getServiceManager();
933 if ( xFactory != null )
934 xMBFactory = UnoRuntime.queryInterface(
935 XMessageBoxFactory.class,
936 xFactory.createInstanceWithContext( "com.sun.star.awt.Toolkit", xContext ) );
938 if ( xMBFactory != null )
940 if ( bQuery )
942 xMB = xMBFactory.createMessageBox(
943 xParentPeer,
944 MessageBoxType.QUERYBOX,
945 MessageBoxButtons.BUTTONS_YES_NO | MessageBoxButtons.DEFAULT_BUTTON_NO,
946 sTitle,
947 sError );
949 else
951 xMB = xMBFactory.createMessageBox(
952 xParentPeer,
953 MessageBoxType.ERRORBOX,
954 MessageBoxButtons.BUTTONS_OK,
955 sTitle,
956 sError );
958 if ( xMB != null )
960 bResult = MainThreadDialogExecutor.Execute( xContext, xMB );
964 catch( Exception e )
966 e.printStackTrace();
968 finally
970 if ( xMB != null )
971 Dispose( xMB );
976 return bResult;
979 private static boolean AllowUnknownCert( XComponentContext xContext, String aURL )
983 XNameAccess xNameAccess = GetConfigNameAccess( xContext, "org.openoffice.Office.Custom.WikiExtension/SpecialData" );
984 if ( xNameAccess.hasByName( aURL ) )
986 XNameAccess xEntry = UnoRuntime.queryInterface( XNameAccess.class, xNameAccess.getByName( aURL ) );
987 if ( xEntry != null && xEntry.hasByName( "AllowUnknownCertificate" ) )
988 return AnyConverter.toBoolean( xEntry.getByName( "AllowUnknownCertificate" ) );
991 catch( Exception e )
993 e.printStackTrace();
996 return false;
999 private static String[][] GetSpecialArgs( XComponentContext xContext, String aURL )
1003 XNameAccess xNameAccess = GetConfigNameAccess( xContext, "org.openoffice.Office.Custom.WikiExtension/SpecialData" );
1004 if ( xNameAccess.hasByName( aURL ) )
1006 XNameAccess xEntry = UnoRuntime.queryInterface( XNameAccess.class, xNameAccess.getByName( aURL ) );
1007 if ( xEntry != null )
1009 XNameAccess xArgs = UnoRuntime.queryInterface( XNameAccess.class, xEntry.getByName( "AdditionalLoginArguments" ) );
1010 if ( xArgs != null )
1012 String[] pNames = xArgs.getElementNames();
1013 if ( pNames != null && pNames.length > 0 )
1015 String[][] pResult = new String[pNames.length][2];
1016 for ( int nInd = 0; nInd < pNames.length; nInd++ )
1018 XNameAccess xArgument = UnoRuntime.queryInterface( XNameAccess.class, xArgs.getByName( pNames[nInd] ) );
1019 if ( xArgument == null )
1020 throw new com.sun.star.uno.RuntimeException();
1022 pResult[nInd][0] = pNames[nInd];
1023 pResult[nInd][1] = AnyConverter.toString( xArgument.getByName( "Value" ) );
1026 return pResult;
1032 catch( Exception e )
1034 e.printStackTrace();
1037 return null;
1040 protected static boolean AllowThreadUsage( XComponentContext xContext )
1042 if ( xContext != null )
1046 XMultiComponentFactory xFactory = xContext.getServiceManager();
1047 if ( xFactory == null )
1048 throw new com.sun.star.uno.RuntimeException();
1050 Object oCheckCallback = xFactory.createInstanceWithContext( "com.sun.star.awt.AsyncCallback", xContext );
1051 return ( oCheckCallback != null );
1053 catch( Exception e )
1055 e.printStackTrace();
1059 return false;
1062 public static void Dispose( Object oObject )
1064 if ( oObject != null )
1068 XComponent xComp = UnoRuntime.queryInterface( XComponent.class, oObject );
1069 if ( xComp != null )
1070 xComp.dispose();
1072 catch( Exception e )
1074 e.printStackTrace();