diff options
author | Robert Antoni Buj i Gelonch <robert.buj@gmail.com> | 2014-09-25 19:41:12 +0200 |
---|---|---|
committer | David Tardon <dtardon@redhat.com> | 2014-10-02 15:25:29 +0200 |
commit | 6f42a714399f4d0c46dad95c7c11bcd513c27eaa (patch) | |
tree | b5ea97f0171124e8232fe909e86ac0a087e8a3d0 /scripting/java | |
parent | 36d24bced0ea5fcbbd380b15e9d1a813fbef32cf (diff) |
scripting: Format_java_code.sh initial run
Conflicts:
scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java
Change-Id: I09b94d8c96dfbaf498bd93a0088feb80a9e4afb6
Diffstat (limited to 'scripting/java')
103 files changed, 4049 insertions, 4479 deletions
diff --git a/scripting/java/Framework/com/sun/star/script/framework/security/SecurityDialog.java b/scripting/java/Framework/com/sun/star/script/framework/security/SecurityDialog.java index a1088260f470..e789d86dd647 100644 --- a/scripting/java/Framework/com/sun/star/script/framework/security/SecurityDialog.java +++ b/scripting/java/Framework/com/sun/star/script/framework/security/SecurityDialog.java @@ -49,23 +49,29 @@ import com.sun.star.uno.XComponentContext; import com.sun.star.script.framework.log.LogUtils; -public class SecurityDialog extends WeakBase implements XComponent, XServiceInfo, XDialog, -XInitialization { +public class SecurityDialog extends WeakBase implements XComponent, + XServiceInfo, XDialog, + XInitialization { - static final String __serviceName = "com.sun.star.script.framework.security.SecurityDialog"; + static final String __serviceName = + "com.sun.star.script.framework.security.SecurityDialog"; private static final String _label1Name = "Label1"; - private static final String _label1String = "This document contains macros. Do you want to allow these macros to be run?"; + private static final String _label1String = + "This document contains macros. Do you want to allow these macros to be run?"; private static final String _label2Name = "Label2"; - private static final String _label2String = "This document contains macros. According to the security settings, the"; + private static final String _label2String = + "This document contains macros. According to the security settings, the"; private static final String _label3Name = "Label3"; - private static final String _label3String = "macros in this document should not be run. Do you want to run them"; + private static final String _label3String = + "macros in this document should not be run. Do you want to run them"; private static final String _label4Name = "Label4"; private static final String _label4String = "anyway?"; private static final String _checkBoxName = "CheckBox"; - private static final String _checkBoxString = "Add this directory to the list of secure paths: "; + private static final String _checkBoxString = + "Add this directory to the list of secure paths: "; private static final String _label5Name = "Label5"; private static final String _title = "Run Macro"; @@ -120,9 +126,9 @@ XInitialization { private boolean checkBoxDialog; private short _checkBoxState = 0; - private boolean extraPathLine=false; - private String checkBoxPath=""; - private String checkBoxPath2=""; + private boolean extraPathLine = false; + private String checkBoxPath = ""; + private String checkBoxPath2 = ""; private static final int lineWrapLength = 21; private static final int lineWrapH = 12; private String _pushed = _doNotRunButtonName; @@ -130,96 +136,89 @@ XInitialization { private XComponentContext _xComponentContext; private XDialog _xDialog; - public SecurityDialog( XComponentContext xComponentContext ) - { - LogUtils.DEBUG( "SecurityDialog ctor" ); + public SecurityDialog(XComponentContext xComponentContext) { + LogUtils.DEBUG("SecurityDialog ctor"); _xComponentContext = xComponentContext; } - public void initialize( Object[] args ) throws RuntimeException - { - LogUtils.DEBUG( "SecurityDialog init" ); + public void initialize(Object[] args) throws RuntimeException { + LogUtils.DEBUG("SecurityDialog init"); + // figure out if we need a checkbox - if ( args.length == 1 && AnyConverter.isString( args[0] ) ) - { + if (args.length == 1 && AnyConverter.isString(args[0])) { //check args is a path // set checkBoxPath with the arg - LogUtils.DEBUG( "checkbox" ); - try - { - checkBoxPath = AnyConverter.toString( args[0] ); - } - catch ( IllegalArgumentException e ) - { - throw new RuntimeException( "SecurityDialog::initialize: " + e.getMessage() ); + LogUtils.DEBUG("checkbox"); + + try { + checkBoxPath = AnyConverter.toString(args[0]); + } catch (IllegalArgumentException e) { + throw new RuntimeException("SecurityDialog::initialize: " + e.getMessage()); } - LogUtils.DEBUG( "path: " + checkBoxPath ); + + LogUtils.DEBUG("path: " + checkBoxPath); checkBoxDialog = true; - if( checkBoxPath.length() > lineWrapLength ) - { + + if (checkBoxPath.length() > lineWrapLength) { extraPathLine = true; cbIncrH += lineWrapH; - checkBoxPath2 = checkBoxPath.substring( lineWrapLength ); - checkBoxPath = checkBoxPath.substring( 0, lineWrapLength ); + checkBoxPath2 = checkBoxPath.substring(lineWrapLength); + checkBoxPath = checkBoxPath.substring(0, lineWrapLength); } - } - else - { - LogUtils.DEBUG( "no checkbox: # of args=" + - args.length ); + } else { + LogUtils.DEBUG("no checkbox: # of args=" + + args.length); cbIncrW = 0; cbIncrH = 0; checkBoxDialog = false; } // now try and create the dialog - try - { + try { _xDialog = createDialog(); - } - catch ( com.sun.star.uno.Exception e ) - { - LogUtils.DEBUG( "Couldn't create dialog" ); - LogUtils.DEBUG( "uno message: " + e.getMessage()); - throw new RuntimeException( e.getMessage() ); - } - catch ( Exception e ) - { - LogUtils.DEBUG( "Couldn't create dialog" ); - LogUtils.DEBUG( "message: " + e.getMessage()); - throw new RuntimeException( e.getMessage() ); + } catch (com.sun.star.uno.Exception e) { + LogUtils.DEBUG("Couldn't create dialog"); + LogUtils.DEBUG("uno message: " + e.getMessage()); + throw new RuntimeException(e.getMessage()); + } catch (Exception e) { + LogUtils.DEBUG("Couldn't create dialog"); + LogUtils.DEBUG("message: " + e.getMessage()); + throw new RuntimeException(e.getMessage()); } } // static component operations - public static XSingleServiceFactory __getServiceFactory( String implName, - XMultiServiceFactory multiFactory, - XRegistryKey regKey ) { + public static XSingleServiceFactory __getServiceFactory(String implName, + XMultiServiceFactory multiFactory, + XRegistryKey regKey) { XSingleServiceFactory xSingleServiceFactory = null; - if ( implName.equals( SecurityDialog.class.getName() ) ) { + + if (implName.equals(SecurityDialog.class.getName())) { xSingleServiceFactory = FactoryHelper.getServiceFactory( - SecurityDialog.class, SecurityDialog.__serviceName, multiFactory, regKey ); + SecurityDialog.class, SecurityDialog.__serviceName, multiFactory, regKey); } + return xSingleServiceFactory; } // XServiceInfo - public String getImplementationName( ) { + public String getImplementationName() { return getClass().getName(); } // XServiceInfo - public boolean supportsService( /*IN*/String serviceName ) { - if ( serviceName.equals( __serviceName)) + public boolean supportsService(/*IN*/String serviceName) { + if (serviceName.equals(__serviceName)) return true; + return false; } // XServiceInfo - public String[] getSupportedServiceNames( ) { - String[] retValue= new String[0]; + public String[] getSupportedServiceNames() { + String[] retValue = new String[0]; retValue[0] = __serviceName; return retValue; } @@ -230,299 +229,292 @@ XInitialization { private XDialog createDialog() throws com.sun.star.uno.Exception { // get the service manager from the component context - XMultiComponentFactory xMultiComponentFactory = _xComponentContext.getServiceManager(); + XMultiComponentFactory xMultiComponentFactory = + _xComponentContext.getServiceManager(); // create the dialog model and set the properties Object dialogModel = xMultiComponentFactory.createInstanceWithContext( - "com.sun.star.awt.UnoControlDialogModel", _xComponentContext ); + "com.sun.star.awt.UnoControlDialogModel", _xComponentContext); XPropertySet xPSetDialog = UnoRuntime.queryInterface( - XPropertySet.class, dialogModel ); - xPSetDialog.setPropertyValue( "PositionX", Integer.valueOf( dialogX) ); - xPSetDialog.setPropertyValue( "PositionY", Integer.valueOf( dialogY)); - xPSetDialog.setPropertyValue( "Width", Integer.valueOf( dialogW+cbIncrW )); - xPSetDialog.setPropertyValue( "Height", Integer.valueOf( dialogH+cbIncrH )); - xPSetDialog.setPropertyValue( "Title", _title ); + XPropertySet.class, dialogModel); + xPSetDialog.setPropertyValue("PositionX", Integer.valueOf(dialogX)); + xPSetDialog.setPropertyValue("PositionY", Integer.valueOf(dialogY)); + xPSetDialog.setPropertyValue("Width", Integer.valueOf(dialogW + cbIncrW)); + xPSetDialog.setPropertyValue("Height", Integer.valueOf(dialogH + cbIncrH)); + xPSetDialog.setPropertyValue("Title", _title); // get the service manager from the dialog model XMultiServiceFactory xMultiServiceFactory = UnoRuntime.queryInterface( - XMultiServiceFactory.class, dialogModel ); + XMultiServiceFactory.class, dialogModel); // create the Run Macro button model and set the properties Object runButtonModel = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlButtonModel" ); + "com.sun.star.awt.UnoControlButtonModel"); XPropertySet xPSetButton = UnoRuntime.queryInterface( - XPropertySet.class, runButtonModel ); - LogUtils.DEBUG("run: x="+(((dialogW+cbIncrW)/2)-runButtonW -1) ); - LogUtils.DEBUG("run: y="+(dialogH+cbIncrH-runButtonH-1)); - xPSetButton.setPropertyValue( "PositionX", Integer.valueOf( (((dialogW+cbIncrW)/2)-runButtonW -1) )); - xPSetButton.setPropertyValue( "PositionY", Integer.valueOf( dialogH+cbIncrH-runButtonH-1)); - xPSetButton.setPropertyValue( "Width", Integer.valueOf( runButtonW )); - xPSetButton.setPropertyValue( "Height", Integer.valueOf( runButtonH )); - xPSetButton.setPropertyValue( "Name", _runButtonName ); - xPSetButton.setPropertyValue( "TabIndex", Short.valueOf( (short)1 ) ); - xPSetButton.setPropertyValue( "Label", _runMacro ); + XPropertySet.class, runButtonModel); + LogUtils.DEBUG("run: x=" + (((dialogW + cbIncrW) / 2) - runButtonW - 1)); + LogUtils.DEBUG("run: y=" + (dialogH + cbIncrH - runButtonH - 1)); + xPSetButton.setPropertyValue("PositionX", + Integer.valueOf((((dialogW + cbIncrW) / 2) - runButtonW - 1))); + xPSetButton.setPropertyValue("PositionY", + Integer.valueOf(dialogH + cbIncrH - runButtonH - 1)); + xPSetButton.setPropertyValue("Width", Integer.valueOf(runButtonW)); + xPSetButton.setPropertyValue("Height", Integer.valueOf(runButtonH)); + xPSetButton.setPropertyValue("Name", _runButtonName); + xPSetButton.setPropertyValue("TabIndex", Short.valueOf((short)1)); + xPSetButton.setPropertyValue("Label", _runMacro); // create the Dont Run Macro button model and set the properties Object doNotRunButtonModel = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlButtonModel" ); + "com.sun.star.awt.UnoControlButtonModel"); xPSetButton = UnoRuntime.queryInterface( - XPropertySet.class, doNotRunButtonModel ); - LogUtils.DEBUG("dontrun: x="+(((dialogW+cbIncrW)/2)-1) ); - LogUtils.DEBUG("dontrun: y="+(dialogH+cbIncrH-doNotRunButtonH-1 )); - xPSetButton.setPropertyValue( "PositionX", Integer.valueOf( (((dialogW+cbIncrW)/2) + 1) )); - xPSetButton.setPropertyValue( "PositionY", Integer.valueOf( (dialogH+cbIncrH-doNotRunButtonH-1 ) )); - xPSetButton.setPropertyValue( "Width", Integer.valueOf( doNotRunButtonW )); - xPSetButton.setPropertyValue( "Height", Integer.valueOf( doNotRunButtonH )); - xPSetButton.setPropertyValue( "Name", _doNotRunButtonName ); - xPSetButton.setPropertyValue( "TabIndex", Short.valueOf( (short)0 ) ); - xPSetButton.setPropertyValue( "Label", _doNotRunMacro ); + XPropertySet.class, doNotRunButtonModel); + LogUtils.DEBUG("dontrun: x=" + (((dialogW + cbIncrW) / 2) - 1)); + LogUtils.DEBUG("dontrun: y=" + (dialogH + cbIncrH - doNotRunButtonH - 1)); + xPSetButton.setPropertyValue("PositionX", + Integer.valueOf((((dialogW + cbIncrW) / 2) + 1))); + xPSetButton.setPropertyValue("PositionY", + Integer.valueOf((dialogH + cbIncrH - doNotRunButtonH - 1))); + xPSetButton.setPropertyValue("Width", Integer.valueOf(doNotRunButtonW)); + xPSetButton.setPropertyValue("Height", Integer.valueOf(doNotRunButtonH)); + xPSetButton.setPropertyValue("Name", _doNotRunButtonName); + xPSetButton.setPropertyValue("TabIndex", Short.valueOf((short)0)); + xPSetButton.setPropertyValue("Label", _doNotRunMacro); // insert the control models into the dialog model XNameContainer xNameCont = UnoRuntime.queryInterface( - XNameContainer.class, dialogModel ); - xNameCont.insertByName( _runButtonName, runButtonModel ); - xNameCont.insertByName( _doNotRunButtonName, doNotRunButtonModel ); + XNameContainer.class, dialogModel); + xNameCont.insertByName(_runButtonName, runButtonModel); + xNameCont.insertByName(_doNotRunButtonName, doNotRunButtonModel); - if ( checkBoxDialog ) - { + if (checkBoxDialog) { LogUtils.DEBUG("creating label & checkbox"); // create the label model and set the properties Object label2Model = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlFixedTextModel" ); + "com.sun.star.awt.UnoControlFixedTextModel"); XPropertySet xPSetLabel = UnoRuntime.queryInterface( - XPropertySet.class, label2Model ); - xPSetLabel.setPropertyValue( "PositionX", Integer.valueOf( label2X )); - xPSetLabel.setPropertyValue( "PositionY", Integer.valueOf( label2Y )); - xPSetLabel.setPropertyValue( "Width", Integer.valueOf( label2W )); - xPSetLabel.setPropertyValue( "Height", Integer.valueOf( label2H )); - xPSetLabel.setPropertyValue( "Name", _label2Name ); - xPSetLabel.setPropertyValue( "TabIndex", Short.valueOf( (short)1 ) ); - xPSetLabel.setPropertyValue( "Label", _label2String ); + XPropertySet.class, label2Model); + xPSetLabel.setPropertyValue("PositionX", Integer.valueOf(label2X)); + xPSetLabel.setPropertyValue("PositionY", Integer.valueOf(label2Y)); + xPSetLabel.setPropertyValue("Width", Integer.valueOf(label2W)); + xPSetLabel.setPropertyValue("Height", Integer.valueOf(label2H)); + xPSetLabel.setPropertyValue("Name", _label2Name); + xPSetLabel.setPropertyValue("TabIndex", Short.valueOf((short)1)); + xPSetLabel.setPropertyValue("Label", _label2String); // create the label model and set the properties Object label3Model = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlFixedTextModel" ); + "com.sun.star.awt.UnoControlFixedTextModel"); XPropertySet xPSetLabel3 = UnoRuntime.queryInterface( - XPropertySet.class, label3Model ); - xPSetLabel3.setPropertyValue( "PositionX", Integer.valueOf( label3X )); - xPSetLabel3.setPropertyValue( "PositionY", Integer.valueOf( label3Y )); - xPSetLabel3.setPropertyValue( "Width", Integer.valueOf( label3W )); - xPSetLabel3.setPropertyValue( "Height", Integer.valueOf( label3H )); - xPSetLabel3.setPropertyValue( "Name", _label3Name ); - xPSetLabel3.setPropertyValue( "TabIndex", Short.valueOf( (short)1 ) ); - xPSetLabel3.setPropertyValue( "Label", _label3String ); + XPropertySet.class, label3Model); + xPSetLabel3.setPropertyValue("PositionX", Integer.valueOf(label3X)); + xPSetLabel3.setPropertyValue("PositionY", Integer.valueOf(label3Y)); + xPSetLabel3.setPropertyValue("Width", Integer.valueOf(label3W)); + xPSetLabel3.setPropertyValue("Height", Integer.valueOf(label3H)); + xPSetLabel3.setPropertyValue("Name", _label3Name); + xPSetLabel3.setPropertyValue("TabIndex", Short.valueOf((short)1)); + xPSetLabel3.setPropertyValue("Label", _label3String); // create the label model and set the properties Object label4Model = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlFixedTextModel" ); + "com.sun.star.awt.UnoControlFixedTextModel"); XPropertySet xPSetLabel4 = UnoRuntime.queryInterface( - XPropertySet.class, label4Model ); - xPSetLabel4.setPropertyValue( "PositionX", Integer.valueOf( label4X )); - xPSetLabel4.setPropertyValue( "PositionY", Integer.valueOf( label4Y )); - xPSetLabel4.setPropertyValue( "Width", Integer.valueOf( label4W )); - xPSetLabel4.setPropertyValue( "Height", Integer.valueOf( label4H )); - xPSetLabel4.setPropertyValue( "Name", _label4Name ); - xPSetLabel4.setPropertyValue( "TabIndex", Short.valueOf( (short)1 ) ); - xPSetLabel4.setPropertyValue( "Label", _label4String ); + XPropertySet.class, label4Model); + xPSetLabel4.setPropertyValue("PositionX", Integer.valueOf(label4X)); + xPSetLabel4.setPropertyValue("PositionY", Integer.valueOf(label4Y)); + xPSetLabel4.setPropertyValue("Width", Integer.valueOf(label4W)); + xPSetLabel4.setPropertyValue("Height", Integer.valueOf(label4H)); + xPSetLabel4.setPropertyValue("Name", _label4Name); + xPSetLabel4.setPropertyValue("TabIndex", Short.valueOf((short)1)); + xPSetLabel4.setPropertyValue("Label", _label4String); // create the checkbox model and set the properties Object checkBoxModel = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlCheckBoxModel" ); + "com.sun.star.awt.UnoControlCheckBoxModel"); XPropertySet xPSetCheckBox = UnoRuntime.queryInterface( - XPropertySet.class, checkBoxModel ); - xPSetCheckBox.setPropertyValue( "PositionX", Integer.valueOf( checkBoxX )); - xPSetCheckBox.setPropertyValue( "PositionY", Integer.valueOf( checkBoxY )); - xPSetCheckBox.setPropertyValue( "Width", Integer.valueOf( checkBoxW )); - xPSetCheckBox.setPropertyValue( "Height", Integer.valueOf( checkBoxH )); - xPSetCheckBox.setPropertyValue( "State", Short.valueOf((short)0) ); - xPSetCheckBox.setPropertyValue( "Name", _checkBoxName ); - xPSetCheckBox.setPropertyValue( "TabIndex", Short.valueOf( (short)1 ) ); - xPSetCheckBox.setPropertyValue( "Label", _checkBoxString +checkBoxPath ); + XPropertySet.class, checkBoxModel); + xPSetCheckBox.setPropertyValue("PositionX", Integer.valueOf(checkBoxX)); + xPSetCheckBox.setPropertyValue("PositionY", Integer.valueOf(checkBoxY)); + xPSetCheckBox.setPropertyValue("Width", Integer.valueOf(checkBoxW)); + xPSetCheckBox.setPropertyValue("Height", Integer.valueOf(checkBoxH)); + xPSetCheckBox.setPropertyValue("State", Short.valueOf((short)0)); + xPSetCheckBox.setPropertyValue("Name", _checkBoxName); + xPSetCheckBox.setPropertyValue("TabIndex", Short.valueOf((short)1)); + xPSetCheckBox.setPropertyValue("Label", _checkBoxString + checkBoxPath); // insert the control models into the dialog model - xNameCont.insertByName( _label2Name, label2Model ); - xNameCont.insertByName( _label3Name, label3Model ); - xNameCont.insertByName( _label4Name, label4Model ); - xNameCont.insertByName( _checkBoxName, checkBoxModel ); - - if ( extraPathLine ) - { - // create the label model and set the properties - Object label5Model = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlFixedTextModel" ); - XPropertySet xPSetLabel5 = UnoRuntime.queryInterface( - XPropertySet.class, label5Model ); - xPSetLabel5.setPropertyValue( "PositionX", Integer.valueOf( label5X )); - xPSetLabel5.setPropertyValue( "PositionY", Integer.valueOf( label5Y )); - xPSetLabel5.setPropertyValue( "Width", Integer.valueOf( label5W )); - xPSetLabel5.setPropertyValue( "Height", Integer.valueOf( label5H )); - xPSetLabel5.setPropertyValue( "Name", _label5Name ); - xPSetLabel5.setPropertyValue( "TabIndex", Short.valueOf( (short)1 ) ); - xPSetLabel5.setPropertyValue( "Label", checkBoxPath2 ); - xNameCont.insertByName( _label5Name, label5Model ); + xNameCont.insertByName(_label2Name, label2Model); + xNameCont.insertByName(_label3Name, label3Model); + xNameCont.insertByName(_label4Name, label4Model); + xNameCont.insertByName(_checkBoxName, checkBoxModel); + + if (extraPathLine) { + // create the label model and set the properties + Object label5Model = xMultiServiceFactory.createInstance( + "com.sun.star.awt.UnoControlFixedTextModel"); + XPropertySet xPSetLabel5 = UnoRuntime.queryInterface( + XPropertySet.class, label5Model); + xPSetLabel5.setPropertyValue("PositionX", Integer.valueOf(label5X)); + xPSetLabel5.setPropertyValue("PositionY", Integer.valueOf(label5Y)); + xPSetLabel5.setPropertyValue("Width", Integer.valueOf(label5W)); + xPSetLabel5.setPropertyValue("Height", Integer.valueOf(label5H)); + xPSetLabel5.setPropertyValue("Name", _label5Name); + xPSetLabel5.setPropertyValue("TabIndex", Short.valueOf((short)1)); + xPSetLabel5.setPropertyValue("Label", checkBoxPath2); + xNameCont.insertByName(_label5Name, label5Model); } - } - else - { + } else { // create the label model and set the properties Object labelModel = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlFixedTextModel" ); + "com.sun.star.awt.UnoControlFixedTextModel"); XPropertySet xPSetLabel = UnoRuntime.queryInterface( - XPropertySet.class, labelModel ); - xPSetLabel.setPropertyValue( "PositionX", Integer.valueOf( label1X )); - xPSetLabel.setPropertyValue( "PositionY", Integer.valueOf( label1Y )); - xPSetLabel.setPropertyValue( "Width", Integer.valueOf( label1W )); - xPSetLabel.setPropertyValue( "Height", Integer.valueOf( label1H )); - xPSetLabel.setPropertyValue( "Name", _label1Name ); - xPSetLabel.setPropertyValue( "TabIndex", Short.valueOf( (short)1 ) ); - xPSetLabel.setPropertyValue( "Label", _label1String ); + XPropertySet.class, labelModel); + xPSetLabel.setPropertyValue("PositionX", Integer.valueOf(label1X)); + xPSetLabel.setPropertyValue("PositionY", Integer.valueOf(label1Y)); + xPSetLabel.setPropertyValue("Width", Integer.valueOf(label1W)); + xPSetLabel.setPropertyValue("Height", Integer.valueOf(label1H)); + xPSetLabel.setPropertyValue("Name", _label1Name); + xPSetLabel.setPropertyValue("TabIndex", Short.valueOf((short)1)); + xPSetLabel.setPropertyValue("Label", _label1String); // insert the control models into the dialog model - xNameCont.insertByName( _label1Name, labelModel ); + xNameCont.insertByName(_label1Name, labelModel); } // create the dialog control and set the model Object dialog = xMultiComponentFactory.createInstanceWithContext( - "com.sun.star.awt.UnoControlDialog", _xComponentContext ); + "com.sun.star.awt.UnoControlDialog", _xComponentContext); XControl xControl = UnoRuntime.queryInterface( - XControl.class, dialog ); + XControl.class, dialog); XControlModel xControlModel = UnoRuntime.queryInterface( - XControlModel.class, dialogModel ); - xControl.setModel( xControlModel ); + XControlModel.class, dialogModel); + xControl.setModel(xControlModel); // add an action listener to the button control XControlContainer xControlCont = UnoRuntime.queryInterface( - XControlContainer.class, dialog ); + XControlContainer.class, dialog); // Add to yes button - Object objectButton = xControlCont.getControl( _runButtonName ); + Object objectButton = xControlCont.getControl(_runButtonName); XButton xButton = UnoRuntime.queryInterface( - XButton.class, objectButton ); - xButton.addActionListener( new ActionListenerImpl( _runButtonName ) ); + XButton.class, objectButton); + xButton.addActionListener(new ActionListenerImpl(_runButtonName)); // add to no button - objectButton = xControlCont.getControl( _doNotRunButtonName ); + objectButton = xControlCont.getControl(_doNotRunButtonName); xButton = UnoRuntime.queryInterface( - XButton.class, objectButton ); - xButton.addActionListener( new ActionListenerImpl( _doNotRunButtonName ) ); + XButton.class, objectButton); + xButton.addActionListener(new ActionListenerImpl(_doNotRunButtonName)); - if ( checkBoxDialog ) - { + if (checkBoxDialog) { // add to checkbox - Object objectCheckBox = xControlCont.getControl( _checkBoxName ); + Object objectCheckBox = xControlCont.getControl(_checkBoxName); XCheckBox xCheckBox = UnoRuntime.queryInterface( - XCheckBox.class, objectCheckBox ); - xCheckBox.addItemListener(new ItemListenerImpl( xControlCont ) ); + XCheckBox.class, objectCheckBox); + xCheckBox.addItemListener(new ItemListenerImpl(xControlCont)); } // create a peer Object toolkit = xMultiComponentFactory.createInstanceWithContext( - "com.sun.star.awt.ExtToolkit", _xComponentContext ); + "com.sun.star.awt.ExtToolkit", _xComponentContext); XToolkit xToolkit = UnoRuntime.queryInterface( - XToolkit.class, toolkit ); + XToolkit.class, toolkit); XWindow xWindow = UnoRuntime.queryInterface( - XWindow.class, xControl ); - xWindow.setVisible( false ); - xControl.createPeer( xToolkit, null ); + XWindow.class, xControl); + xWindow.setVisible(false); + xControl.createPeer(xToolkit, null); // return the dialog XDialog xDialog = UnoRuntime.queryInterface( - XDialog.class, dialog ); + XDialog.class, dialog); return xDialog; } - public short execute() - { + public short execute() { short result = 0; _pushed = _doNotRunButtonName; - LogUtils.DEBUG("*DF* Before execute " ); + LogUtils.DEBUG("*DF* Before execute "); _xDialog.execute(); - LogUtils.DEBUG("*DF* After execute " ); + LogUtils.DEBUG("*DF* After execute "); - if ( _pushed.equals( _runButtonName ) ) - { + if (_pushed.equals(_runButtonName)) { result += 1; } - if ( _checkBoxState == 1 ) - { - result +=2; + + if (_checkBoxState == 1) { + result += 2; } + return result; } - public void endExecute() - { + public void endExecute() { _xDialog.endExecute(); } - public String getTitle() - { + public String getTitle() { return _xDialog.getTitle(); - } + } - public void setTitle( String Title ) - { - _xDialog.setTitle( Title ); - } + public void setTitle(String Title) { + _xDialog.setTitle(Title); + } - public void dispose () - { + public void dispose() { XComponent xComponent = UnoRuntime.queryInterface( - XComponent.class, _xDialog ); - xComponent.dispose(); - } + XComponent.class, _xDialog); + xComponent.dispose(); + } - public void addEventListener ( com.sun.star.lang.XEventListener xListener ) - { + public void addEventListener(com.sun.star.lang.XEventListener xListener) { XComponent xComponent = UnoRuntime.queryInterface( - XComponent.class, _xDialog ); - xComponent.addEventListener( xListener ); - } + XComponent.class, _xDialog); + xComponent.addEventListener(xListener); + } - public void removeEventListener ( com.sun.star.lang.XEventListener aListener ) - { + public void removeEventListener(com.sun.star.lang.XEventListener aListener) { XComponent xComponent = UnoRuntime.queryInterface( - XComponent.class, _xDialog ); - xComponent.removeEventListener( aListener ); - } + XComponent.class, _xDialog); + xComponent.removeEventListener(aListener); + } private class ActionListenerImpl implements com.sun.star.awt.XActionListener { private String _buttonName; - private ActionListenerImpl( String buttonName ) { + private ActionListenerImpl(String buttonName) { _buttonName = buttonName; } // XEventListener - public void disposing( EventObject eventObject ) { + public void disposing(EventObject eventObject) { } // XActionListener - public void actionPerformed( ActionEvent actionEvent ) { - _pushed = _buttonName; - LogUtils.DEBUG("** Button pushed ->" + _pushed ); + public void actionPerformed(ActionEvent actionEvent) { + _pushed = _buttonName; + LogUtils.DEBUG("** Button pushed ->" + _pushed); - _xDialog.endExecute(); + _xDialog.endExecute(); } } private class ItemListenerImpl implements com.sun.star.awt.XItemListener { private XCheckBox _xCheckBox; - private ItemListenerImpl( XControlContainer xControlCont ) { - Object objectCheckBox = xControlCont.getControl( _checkBoxName ); + private ItemListenerImpl(XControlContainer xControlCont) { + Object objectCheckBox = xControlCont.getControl(_checkBoxName); _xCheckBox = UnoRuntime.queryInterface( - XCheckBox.class, objectCheckBox ); + XCheckBox.class, objectCheckBox); } // XEventListener - public void disposing( EventObject eventObject ) { + public void disposing(EventObject eventObject) { _xCheckBox = null; } // XAdjustmentListener - public void itemStateChanged( ItemEvent itemEvent ) { - _checkBoxState = _xCheckBox.getState(); - LogUtils.DEBUG("** checkbox state ->" + _checkBoxState ); + public void itemStateChanged(ItemEvent itemEvent) { + _checkBoxState = _xCheckBox.getState(); + LogUtils.DEBUG("** checkbox state ->" + _checkBoxState); } } } diff --git a/scripting/java/com/sun/star/script/framework/browse/DialogFactory.java b/scripting/java/com/sun/star/script/framework/browse/DialogFactory.java index 1708bdc60888..1883b0d2e05a 100644 --- a/scripting/java/com/sun/star/script/framework/browse/DialogFactory.java +++ b/scripting/java/com/sun/star/script/framework/browse/DialogFactory.java @@ -31,26 +31,20 @@ import com.sun.star.container.XNameContainer; import com.sun.star.awt.*; -public class DialogFactory -{ +public class DialogFactory { private static DialogFactory factory; private XComponentContext xComponentContext; // singleton - private DialogFactory(XComponentContext xComponentContext) - { + private DialogFactory(XComponentContext xComponentContext) { this.xComponentContext = xComponentContext; factory = this; - } - - public static void createDialogFactory(XComponentContext xComponentContext) - { - if (factory == null) - { - synchronized(DialogFactory.class) - { - if (factory == null) - { + } + + public static void createDialogFactory(XComponentContext xComponentContext) { + if (factory == null) { + synchronized (DialogFactory.class) { + if (factory == null) { factory = new DialogFactory(xComponentContext); } } @@ -58,65 +52,58 @@ public class DialogFactory } public static DialogFactory getDialogFactory() - throws java.lang.Exception - { - if (factory == null) - { + throws java.lang.Exception { + if (factory == null) { throw new java.lang.Exception("DialogFactory not initialized"); } + return factory; } - public String showInputDialog(String title, String prompt) - { + public String showInputDialog(String title, String prompt) { final XDialog xDialog; - try - { + + try { xDialog = createInputDialog(title, prompt); - } - catch (com.sun.star.uno.Exception e) - { + } catch (com.sun.star.uno.Exception e) { return null; } // add an action listener to the button controls - XControlContainer controls = UnoRuntime.queryInterface(XControlContainer.class, xDialog); + XControlContainer controls = UnoRuntime.queryInterface(XControlContainer.class, + xDialog); XButton okButton = UnoRuntime.queryInterface( - XButton.class, controls.getControl("Ok")); + XButton.class, controls.getControl("Ok")); okButton.setActionCommand("Ok"); XButton cancelButton = UnoRuntime.queryInterface( - XButton.class, controls.getControl("Cancel")); + XButton.class, controls.getControl("Cancel")); cancelButton.setActionCommand("Cancel"); final XTextComponent textField = UnoRuntime.queryInterface( - XTextComponent.class, controls.getControl("NameField")); + XTextComponent.class, controls.getControl("NameField")); final ResultHolder resultHolder = new ResultHolder(); com.sun.star.awt.XActionListener listener = - new com.sun.star.awt.XActionListener() - { - public void actionPerformed(com.sun.star.awt.ActionEvent e) { - if (e.ActionCommand.equals("Cancel")) - { - resultHolder.setResult(null); - xDialog.endExecute(); - } - else - { - resultHolder.setResult(textField.getText()); - xDialog.endExecute(); - } + new com.sun.star.awt.XActionListener() { + public void actionPerformed(com.sun.star.awt.ActionEvent e) { + if (e.ActionCommand.equals("Cancel")) { + resultHolder.setResult(null); + xDialog.endExecute(); + } else { + resultHolder.setResult(textField.getText()); + xDialog.endExecute(); } + } - public void disposing(EventObject o) { - // does nothing - } - }; + public void disposing(EventObject o) { + // does nothing + } + }; okButton.addActionListener(listener); cancelButton.addActionListener(listener); @@ -127,8 +114,7 @@ public class DialogFactory } private void setDimensions(Object o, int x, int y, int width, int height) - throws com.sun.star.uno.Exception - { + throws com.sun.star.uno.Exception { XPropertySet props = UnoRuntime.queryInterface(XPropertySet.class, o); props.setPropertyValue("PositionX", Integer.valueOf(x)); @@ -138,15 +124,12 @@ public class DialogFactory } private XDialog createInputDialog(String title, String prompt) - throws com.sun.star.uno.Exception - { - if (title == null || title.length() == 0) - { + throws com.sun.star.uno.Exception { + if (title == null || title.length() == 0) { title = "Scripting Framework"; } - if (prompt == null || prompt.length() == 0) - { + if (prompt == null || prompt.length() == 0) { prompt = "Enter name"; } @@ -156,64 +139,65 @@ public class DialogFactory // create the dialog model and set the properties Object dialogModel = xMultiComponentFactory.createInstanceWithContext( - "com.sun.star.awt.UnoControlDialogModel", xComponentContext); + "com.sun.star.awt.UnoControlDialogModel", xComponentContext); setDimensions(dialogModel, 100, 100, 157, 58); XPropertySet props = UnoRuntime.queryInterface( - XPropertySet.class, dialogModel); + XPropertySet.class, dialogModel); props.setPropertyValue("Title", title); // get the service manager from the dialog model XMultiServiceFactory xMultiServiceFactory = UnoRuntime.queryInterface( - XMultiServiceFactory.class, dialogModel); + XMultiServiceFactory.class, dialogModel); // create the label model and set the properties Object label = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlFixedTextModel"); + "com.sun.star.awt.UnoControlFixedTextModel"); setDimensions(label, 15, 5, 134, 12); XPropertySet labelProps = UnoRuntime.queryInterface( - XPropertySet.class, label); + XPropertySet.class, label); labelProps.setPropertyValue("Name", "PromptLabel"); labelProps.setPropertyValue("Label", prompt); // create the text field Object edit = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlEditModel"); + "com.sun.star.awt.UnoControlEditModel"); setDimensions(edit, 15, 18, 134, 12); XPropertySet editProps = UnoRuntime.queryInterface( - XPropertySet.class, edit); + XPropertySet.class, edit); editProps.setPropertyValue("Name", "NameField"); // create the OK button Object okButtonModel = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlButtonModel"); + "com.sun.star.awt.UnoControlButtonModel"); setDimensions(okButtonModel, 40, 39, 38, 15); XPropertySet buttonProps = UnoRuntime.queryInterface( - XPropertySet.class, okButtonModel); + XPropertySet.class, okButtonModel); buttonProps.setPropertyValue("Name", "Ok"); buttonProps.setPropertyValue("Label", "Ok"); // create the Cancel button Object cancelButtonModel = xMultiServiceFactory.createInstance( - "com.sun.star.awt.UnoControlButtonModel"); + "com.sun.star.awt.UnoControlButtonModel"); setDimensions(cancelButtonModel, 83, 39, 38, 15); buttonProps = UnoRuntime.queryInterface( - XPropertySet.class, cancelButtonModel); + XPropertySet.class, cancelButtonModel); buttonProps.setPropertyValue("Name", "Cancel"); buttonProps.setPropertyValue("Label", "Cancel"); // insert the control models into the dialog model - XNameContainer xNameCont = UnoRuntime.queryInterface(XNameContainer.class, dialogModel); + XNameContainer xNameCont = UnoRuntime.queryInterface(XNameContainer.class, + dialogModel); xNameCont.insertByName("PromptLabel", label); xNameCont.insertByName("NameField", edit); @@ -222,20 +206,21 @@ public class DialogFactory // create the dialog control and set the model Object dialog = xMultiComponentFactory.createInstanceWithContext( - "com.sun.star.awt.UnoControlDialog", xComponentContext); + "com.sun.star.awt.UnoControlDialog", xComponentContext); XControl xControl = UnoRuntime.queryInterface( - XControl.class, dialog); + XControl.class, dialog); - XControlModel xControlModel = UnoRuntime.queryInterface(XControlModel.class, dialogModel); + XControlModel xControlModel = UnoRuntime.queryInterface(XControlModel.class, + dialogModel); xControl.setModel(xControlModel); // create a peer Object toolkit = xMultiComponentFactory.createInstanceWithContext( - "com.sun.star.awt.ExtToolkit", xComponentContext); + "com.sun.star.awt.ExtToolkit", xComponentContext); XToolkit xToolkit = UnoRuntime.queryInterface( - XToolkit.class, toolkit); + XToolkit.class, toolkit); XWindow xWindow = UnoRuntime.queryInterface( - XWindow.class, xControl); + XWindow.class, xControl); xWindow.setVisible(false); xControl.createPeer(xToolkit, null); @@ -245,13 +230,11 @@ public class DialogFactory private static class ResultHolder { private Object result = null; - public Object getResult() - { + public Object getResult() { return result; } - public void setResult(Object result) - { + public void setResult(Object result) { this.result = result; } } diff --git a/scripting/java/com/sun/star/script/framework/browse/ParcelBrowseNode.java b/scripting/java/com/sun/star/script/framework/browse/ParcelBrowseNode.java index a2e2423ffd56..0e4f2bdea05e 100644 --- a/scripting/java/com/sun/star/script/framework/browse/ParcelBrowseNode.java +++ b/scripting/java/com/sun/star/script/framework/browse/ParcelBrowseNode.java @@ -50,8 +50,7 @@ import java.util.*; import javax.swing.JOptionPane; public class ParcelBrowseNode extends PropertySet - implements XBrowseNode, XInvocation -{ + implements XBrowseNode, XInvocation { private ScriptProvider provider; private Collection<XBrowseNode> browsenodes; private ParcelContainer container; @@ -61,46 +60,43 @@ public class ParcelBrowseNode extends PropertySet - public ParcelBrowseNode( ScriptProvider provider, ParcelContainer container, String parcelName ) { + public ParcelBrowseNode(ScriptProvider provider, ParcelContainer container, + String parcelName) { this.provider = provider; this.container = container; // TODO decide whether exception is propagated out or not - try - { - this.parcel = (Parcel)this.container.getByName( parcelName ); - } - catch ( Exception e ) - { + try { + this.parcel = (Parcel)this.container.getByName(parcelName); + } catch (Exception e) { - LogUtils.DEBUG("** Exception: " + e ); + LogUtils.DEBUG("** Exception: " + e); LogUtils.DEBUG(" ** Failed to get parcel named " + - parcelName + " from container" ); + parcelName + " from container"); } + registerProperty("Deletable", new Type(boolean.class), - (short)0, "deletable"); + (short)0, "deletable"); registerProperty("Editable", new Type(boolean.class), - (short)0, "editable"); + (short)0, "editable"); registerProperty("Creatable", new Type(boolean.class), - (short)0, "creatable"); + (short)0, "creatable"); registerProperty("Renamable", new Type(boolean.class), - (short)0, "renamable"); + (short)0, "renamable"); String parcelDirUrl = parcel.getPathToParcel(); XComponentContext xCtx = provider.getScriptingContext().getComponentContext(); XMultiComponentFactory xFac = xCtx.getServiceManager(); - try - { - XSimpleFileAccess xSFA = UnoRuntime.queryInterface( XSimpleFileAccess.class, - xFac.createInstanceWithContext( - "com.sun.star.ucb.SimpleFileAccess", - xCtx ) ); - } - catch ( com.sun.star.uno.Exception e ) - { + + try { + XSimpleFileAccess xSFA = UnoRuntime.queryInterface(XSimpleFileAccess.class, + xFac.createInstanceWithContext( + "com.sun.star.ucb.SimpleFileAccess", + xCtx)); + } catch (com.sun.star.uno.Exception e) { // TODO propagate potential errors - LogUtils.DEBUG( "Caught exception creating ParcelBrowseNode " + e ); - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + LogUtils.DEBUG("Caught exception creating ParcelBrowseNode " + e); + LogUtils.DEBUG(LogUtils.getTrace(e)); } } @@ -110,36 +106,30 @@ public class ParcelBrowseNode extends PropertySet } public XBrowseNode[] getChildNodes() { - try - { + try { - if ( hasChildNodes() ) - { + if (hasChildNodes()) { String[] names = parcel.getElementNames(); - browsenodes = new ArrayList<XBrowseNode>( names.length ); + browsenodes = new ArrayList<XBrowseNode>(names.length); for (String name : names) { browsenodes.add(new ScriptBrowseNode(provider, parcel, name)); } - } - else - { - LogUtils.DEBUG("ParcelBrowseNode.getChildeNodes no children " ); + } else { + LogUtils.DEBUG("ParcelBrowseNode.getChildeNodes no children "); return new XBrowseNode[0]; } - } - catch ( Exception e ) - { - LogUtils.DEBUG("Failed to getChildeNodes, exception: " + e ); - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + } catch (Exception e) { + LogUtils.DEBUG("Failed to getChildeNodes, exception: " + e); + LogUtils.DEBUG(LogUtils.getTrace(e)); return new XBrowseNode[0]; } + return browsenodes.toArray(new XBrowseNode[browsenodes.size()]); } public boolean hasChildNodes() { - if ( container != null && container.hasByName( getName() ) && parcel != null ) - { + if (container != null && container.hasByName(getName()) && parcel != null) { return parcel.hasElements(); } @@ -151,8 +141,7 @@ public class ParcelBrowseNode extends PropertySet } @Override - public String toString() - { + public String toString() { return getName(); } @@ -163,11 +152,10 @@ public class ParcelBrowseNode extends PropertySet public Object invoke(String aFunctionName, Object[] aParams, short[][] aOutParamIndex, Object[][] aOutParam) - throws com.sun.star.lang.IllegalArgumentException, - com.sun.star.script.CannotConvertException, - com.sun.star.reflection.InvocationTargetException - { - LogUtils.DEBUG("ParcelBrowseNode invoke for " + aFunctionName ); + throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.script.CannotConvertException, + com.sun.star.reflection.InvocationTargetException { + LogUtils.DEBUG("ParcelBrowseNode invoke for " + aFunctionName); // Initialise the out parameters - not used but prevents error in // UNO bridge aOutParamIndex[0] = new short[0]; @@ -175,137 +163,112 @@ public class ParcelBrowseNode extends PropertySet Any result = new Any(new Type(Boolean.class), Boolean.TRUE); - if (aFunctionName.equals("Creatable")) - { - try - { + if (aFunctionName.equals("Creatable")) { + try { String newName; if (aParams == null || aParams.length < 1 || - !AnyConverter.isString(aParams[0])) - { + !AnyConverter.isString(aParams[0])) { String prompt = "Enter name for new Script"; String title = "Create Script"; // try to get a DialogFactory instance, if it fails // just use a Swing JOptionPane to prompt for the name - try - { + try { DialogFactory dialogFactory = DialogFactory.getDialogFactory(); newName = dialogFactory.showInputDialog(title, prompt); - } - catch (Exception e) - { + } catch (Exception e) { newName = JOptionPane.showInputDialog(null, prompt, title, - JOptionPane.QUESTION_MESSAGE); + JOptionPane.QUESTION_MESSAGE); } - } - else { + } else { newName = AnyConverter.toString(aParams[0]); } - if ( newName == null || newName.length() == 0) - { + if (newName == null || newName.length() == 0) { result = new Any(new Type(Boolean.class), Boolean.FALSE); - } - else - { + } else { String source = provider.getScriptEditor().getTemplate(); String languageName = newName + "." + provider.getScriptEditor().getExtension(); String language = container.getLanguage(); - ScriptEntry entry = new ScriptEntry( language, languageName, "", new HashMap<String,String>() ); + ScriptEntry entry = new ScriptEntry(language, languageName, "", + new HashMap<String, String>()); - Parcel parcel = (Parcel)container.getByName( getName() ); - ScriptMetaData data = new ScriptMetaData( parcel, entry, source ); - parcel.insertByName( languageName, data ); + Parcel parcel = (Parcel)container.getByName(getName()); + ScriptMetaData data = new ScriptMetaData(parcel, entry, source); + parcel.insertByName(languageName, data); - ScriptBrowseNode sbn = new ScriptBrowseNode( provider, parcel, languageName ); + ScriptBrowseNode sbn = new ScriptBrowseNode(provider, parcel, languageName); - if(browsenodes==null) - { - LogUtils.DEBUG("browsenodes null!!"); - browsenodes = new ArrayList<XBrowseNode>(4); + if (browsenodes == null) { + LogUtils.DEBUG("browsenodes null!!"); + browsenodes = new ArrayList<XBrowseNode>(4); } + browsenodes.add(sbn); result = new Any(new Type(XBrowseNode.class), sbn); } - } - catch (Exception e) - { - LogUtils.DEBUG("ParcelBrowseNode[create] failed with: " + e ); - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + } catch (Exception e) { + LogUtils.DEBUG("ParcelBrowseNode[create] failed with: " + e); + LogUtils.DEBUG(LogUtils.getTrace(e)); result = new Any(new Type(Boolean.class), Boolean.FALSE); } - } - else if (aFunctionName.equals("Deletable")) - { - try - { - if ( container.deleteParcel(getName()) ) - { + } else if (aFunctionName.equals("Deletable")) { + try { + if (container.deleteParcel(getName())) { result = new Any(new Type(Boolean.class), Boolean.TRUE); - } - else - { + } else { result = new Any(new Type(Boolean.class), Boolean.FALSE); } - } - catch (Exception e) - { + } catch (Exception e) { result = new Any(new Type(Boolean.class), Boolean.FALSE); } - } - else if (aFunctionName.equals("Renamable")) - { + } else if (aFunctionName.equals("Renamable")) { String newName = null; - try - { + + try { if (aParams == null || aParams.length < 1 || - !AnyConverter.isString(aParams[0])) - { + !AnyConverter.isString(aParams[0])) { String prompt = "Enter new name for Library"; String title = "Rename Library"; // try to get a DialogFactory instance, if it fails // just use a Swing JOptionPane to prompt for the name - try - { + try { DialogFactory dialogFactory = DialogFactory.getDialogFactory(); newName = dialogFactory.showInputDialog(title, prompt); - } - catch (Exception e) - { + } catch (Exception e) { newName = JOptionPane.showInputDialog(null, prompt, title, - JOptionPane.QUESTION_MESSAGE); + JOptionPane.QUESTION_MESSAGE); } - } - else { + } else { newName = AnyConverter.toString(aParams[0]); } - container.renameParcel( getName(), newName ); - Parcel p = (Parcel)container.getByName( newName ); - if(browsenodes == null ) - { + + container.renameParcel(getName(), newName); + Parcel p = (Parcel)container.getByName(newName); + + if (browsenodes == null) { getChildNodes(); } - ScriptBrowseNode[] childNodes = browsenodes.toArray(new ScriptBrowseNode[browsenodes.size()]); - for ( int index = 0; index < childNodes.length; index++ ) - { - childNodes[ index ].updateURI( p ); + ScriptBrowseNode[] childNodes = browsenodes.toArray(new + ScriptBrowseNode[browsenodes.size()]); + + for (int index = 0; index < childNodes.length; index++) { + childNodes[ index ].updateURI(p); } + result = new Any(new Type(XBrowseNode.class), this); - } - catch (Exception e) - { + } catch (Exception e) { result = new Any(new Type(Boolean.class), Boolean.FALSE); } } @@ -319,15 +282,13 @@ public class ParcelBrowseNode extends PropertySet } public void setValue(String aPropertyName, Object aValue) - throws com.sun.star.beans.UnknownPropertyException, - com.sun.star.script.CannotConvertException, - com.sun.star.reflection.InvocationTargetException - { + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.script.CannotConvertException, + com.sun.star.reflection.InvocationTargetException { } public Object getValue(String aPropertyName) - throws com.sun.star.beans.UnknownPropertyException - { + throws com.sun.star.beans.UnknownPropertyException { return null; } diff --git a/scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java b/scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java index ca5d94de02a3..d611c074acfe 100644 --- a/scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java +++ b/scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java @@ -25,14 +25,17 @@ import com.sun.star.script.framework.log.*; import com.sun.star.script.framework.container.*; -public class PkgProviderBrowseNode extends ProviderBrowseNode -{ - - public PkgProviderBrowseNode( ScriptProvider provider, ParcelContainer container, XComponentContext xCtx ) { - super( provider, container, xCtx ); - LogUtils.DEBUG("*** PkgProviderBrowseNode ctor container name = " + container.getName()); - LogUtils.DEBUG("*** PkgProviderBrowseNode ctor container path = " + container.getParcelContainerDir()); - LogUtils.DEBUG("*** PkgProviderBrowseNode ctor, container has num parcels = " + container.getElementNames().length); +public class PkgProviderBrowseNode extends ProviderBrowseNode { + + public PkgProviderBrowseNode(ScriptProvider provider, ParcelContainer container, + XComponentContext xCtx) { + super(provider, container, xCtx); + LogUtils.DEBUG("*** PkgProviderBrowseNode ctor container name = " + + container.getName()); + LogUtils.DEBUG("*** PkgProviderBrowseNode ctor container path = " + + container.getParcelContainerDir()); + LogUtils.DEBUG("*** PkgProviderBrowseNode ctor, container has num parcels = " + + container.getElementNames().length); } @Override diff --git a/scripting/java/com/sun/star/script/framework/browse/ProviderBrowseNode.java b/scripting/java/com/sun/star/script/framework/browse/ProviderBrowseNode.java index 18cefb0d817c..d9b74e5a7807 100644 --- a/scripting/java/com/sun/star/script/framework/browse/ProviderBrowseNode.java +++ b/scripting/java/com/sun/star/script/framework/browse/ProviderBrowseNode.java @@ -43,8 +43,7 @@ import java.util.*; import javax.swing.JOptionPane; public class ProviderBrowseNode extends PropertySet - implements XBrowseNode, XInvocation -{ + implements XBrowseNode, XInvocation { private ScriptProvider provider; private Collection<XBrowseNode> browsenodes; private String name; @@ -56,7 +55,8 @@ public class ProviderBrowseNode extends PropertySet - public ProviderBrowseNode( ScriptProvider provider, ParcelContainer container, XComponentContext xCtx ) { + public ProviderBrowseNode(ScriptProvider provider, ParcelContainer container, + XComponentContext xCtx) { LogUtils.DEBUG("*** ProviderBrowseNode ctor"); this.container = container; this.name = this.container.getLanguage(); @@ -64,25 +64,24 @@ public class ProviderBrowseNode extends PropertySet this.m_xCtx = xCtx; registerProperty("Deletable", new Type(boolean.class), - (short)0, "deletable"); + (short)0, "deletable"); registerProperty("Creatable", new Type(boolean.class), - (short)0, "creatable"); + (short)0, "creatable"); registerProperty("Editable", new Type(boolean.class), - (short)0, "editable"); + (short)0, "editable"); XSimpleFileAccess xSFA = null; XMultiComponentFactory xFac = m_xCtx.getServiceManager(); - try - { - xSFA = UnoRuntime.queryInterface( XSimpleFileAccess.class, - xFac.createInstanceWithContext( - "com.sun.star.ucb.SimpleFileAccess", - xCtx ) ); + + try { + xSFA = UnoRuntime.queryInterface(XSimpleFileAccess.class, + xFac.createInstanceWithContext( + "com.sun.star.ucb.SimpleFileAccess", + xCtx)); } // TODO propage errors - catch( com.sun.star.uno.Exception e ) - { - LogUtils.DEBUG("Caught exception in creation of ProviderBrowseNode "); - LogUtils.DEBUG( LogUtils.getTrace(e)); + catch (com.sun.star.uno.Exception e) { + LogUtils.DEBUG("Caught exception in creation of ProviderBrowseNode "); + LogUtils.DEBUG(LogUtils.getTrace(e)); } } @@ -93,51 +92,55 @@ public class ProviderBrowseNode extends PropertySet public XBrowseNode[] getChildNodes() { LogUtils.DEBUG("***** ProviderBrowseNode.getChildNodes()"); - if ( hasChildNodes() ) - { + + if (hasChildNodes()) { // needs initialisation? - LogUtils.DEBUG("** ProviderBrowseNode.getChildNodes(), container is " + container ); + LogUtils.DEBUG("** ProviderBrowseNode.getChildNodes(), container is " + + container); String[] parcels = container.getElementNames(); - browsenodes = new ArrayList<XBrowseNode>( parcels.length ); + browsenodes = new ArrayList<XBrowseNode>(parcels.length); + for (String parcel : parcels) { try { XBrowseNode node = new ParcelBrowseNode(provider, container, parcel); - browsenodes.add( node ); + browsenodes.add(node); } catch (Exception e) { LogUtils.DEBUG("*** Failed to create parcel node for " + parcel); - LogUtils.DEBUG( e.toString() ); + LogUtils.DEBUG(e.toString()); } } + ParcelContainer[] packageContainers = container.getChildContainers(); - LogUtils.DEBUG("**** For container named " + container.getName() + " with root path " + container.getParcelContainerDir() + " has " + packageContainers.length + " child containers " ); + LogUtils.DEBUG("**** For container named " + container.getName() + + " with root path " + container.getParcelContainerDir() + " has " + + packageContainers.length + " child containers "); for (ParcelContainer packageContainer : packageContainers) { - XBrowseNode node = new PkgProviderBrowseNode(provider, packageContainer, m_xCtx); - browsenodes.add( node ); + XBrowseNode node = new PkgProviderBrowseNode(provider, packageContainer, + m_xCtx); + browsenodes.add(node); } - } - else - { + } else { LogUtils.DEBUG("*** No container available"); return new XBrowseNode[0]; } - return browsenodes.toArray( new XBrowseNode[browsenodes.size()] ); + + return browsenodes.toArray(new XBrowseNode[browsenodes.size()]); } public boolean hasChildNodes() { boolean result = true; - if ( container == null || - ( !container.hasElements() && - container.getChildContainers().length == 0 ) ) - { + if (container == null || + (!container.hasElements() && + container.getChildContainers().length == 0)) { result = false; } LogUtils.DEBUG("***** ProviderBrowseNode.hasChildNodes(): " + - "name=" + name + - ", path=" + container.getParcelContainerDir() + - ", result=" + result ); + "name=" + name + + ", path=" + container.getParcelContainerDir() + + ", result=" + result); return result; } @@ -147,8 +150,7 @@ public class ProviderBrowseNode extends PropertySet } @Override - public String toString() - { + public String toString() { return getName(); } @@ -159,10 +161,9 @@ public class ProviderBrowseNode extends PropertySet public Object invoke(String aFunctionName, Object[] aParams, short[][] aOutParamIndex, Object[][] aOutParam) - throws com.sun.star.lang.IllegalArgumentException, - com.sun.star.script.CannotConvertException, - com.sun.star.reflection.InvocationTargetException - { + throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.script.CannotConvertException, + com.sun.star.reflection.InvocationTargetException { // Initialise the out parameters - not used but prevents error in // UNO bridge aOutParamIndex[0] = new short[0]; @@ -170,57 +171,45 @@ public class ProviderBrowseNode extends PropertySet Any result = new Any(new Type(Boolean.class), Boolean.TRUE); - if (aFunctionName.equals("Creatable")) - { - try - { + if (aFunctionName.equals("Creatable")) { + try { String name; if (aParams == null || aParams.length < 1 || - !AnyConverter.isString(aParams[0])) - { + !AnyConverter.isString(aParams[0])) { String prompt = "Enter name for new Parcel"; String title = "Create Parcel"; // try to get a DialogFactory instance, if it fails // just use a Swing JOptionPane to prompt for the name - try - { + try { DialogFactory dialogFactory = DialogFactory.getDialogFactory(); name = dialogFactory.showInputDialog(title, prompt); - } - catch (Exception e) - { + } catch (Exception e) { name = JOptionPane.showInputDialog(null, prompt, title, - JOptionPane.QUESTION_MESSAGE); + JOptionPane.QUESTION_MESSAGE); } - } - else { + } else { name = AnyConverter.toString(aParams[0]); } - if (name == null || name.length() == 0) - { + if (name == null || name.length() == 0) { result = new Any(new Type(Boolean.class), Boolean.FALSE); - } - else - { + } else { - Object newParcel = container.createParcel( name ); - LogUtils.DEBUG("Parcel created " + name + " " + newParcel ); - if ( newParcel == null ) - { + Object newParcel = container.createParcel(name); + LogUtils.DEBUG("Parcel created " + name + " " + newParcel); + + if (newParcel == null) { result = new Any(new Type(Boolean.class), Boolean.FALSE); - } - else - { - ParcelBrowseNode parcel = new ParcelBrowseNode( provider, container, name ); + } else { + ParcelBrowseNode parcel = new ParcelBrowseNode(provider, container, name); LogUtils.DEBUG("created parcel node "); - if ( browsenodes == null ) - { - browsenodes = new ArrayList<XBrowseNode>( 5 ); + + if (browsenodes == null) { + browsenodes = new ArrayList<XBrowseNode>(5); } browsenodes.add(parcel); @@ -229,15 +218,12 @@ public class ProviderBrowseNode extends PropertySet result = new Any(new Type(XBrowseNode.class), parcel); } } - } - catch (Exception e) - { - LogUtils.DEBUG("ProviderBrowseNode[create] failed with: " + e ); - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + } catch (Exception e) { + LogUtils.DEBUG("ProviderBrowseNode[create] failed with: " + e); + LogUtils.DEBUG(LogUtils.getTrace(e)); result = new Any(new Type(Boolean.class), Boolean.FALSE); } - } - else { + } else { throw new com.sun.star.lang.IllegalArgumentException( "Function " + aFunctionName + " not supported."); } @@ -246,15 +232,13 @@ public class ProviderBrowseNode extends PropertySet } public void setValue(String aPropertyName, Object aValue) - throws com.sun.star.beans.UnknownPropertyException, - com.sun.star.script.CannotConvertException, - com.sun.star.reflection.InvocationTargetException - { + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.script.CannotConvertException, + com.sun.star.reflection.InvocationTargetException { } public Object getValue(String aPropertyName) - throws com.sun.star.beans.UnknownPropertyException - { + throws com.sun.star.beans.UnknownPropertyException { return null; } diff --git a/scripting/java/com/sun/star/script/framework/browse/ScriptBrowseNode.java b/scripting/java/com/sun/star/script/framework/browse/ScriptBrowseNode.java index 6073eb03b243..f259da90f097 100644 --- a/scripting/java/com/sun/star/script/framework/browse/ScriptBrowseNode.java +++ b/scripting/java/com/sun/star/script/framework/browse/ScriptBrowseNode.java @@ -46,8 +46,7 @@ import com.sun.star.script.framework.provider.ScriptProvider; import com.sun.star.script.framework.container.*; public class ScriptBrowseNode extends PropertySet - implements XBrowseNode, XInvocation -{ + implements XBrowseNode, XInvocation { private ScriptProvider provider; private Parcel parent; @@ -58,37 +57,33 @@ public class ScriptBrowseNode extends PropertySet private boolean deletable = false; private boolean renamable = false; - public ScriptBrowseNode( ScriptProvider provider, Parcel parent, - String name ) - { + public ScriptBrowseNode(ScriptProvider provider, Parcel parent, + String name) { this.provider = provider; this.name = name; this.parent = parent; XComponentContext xCtx = provider.getScriptingContext().getComponentContext(); XMultiComponentFactory xFac = xCtx.getServiceManager(); - try - { - ScriptMetaData data = (ScriptMetaData)parent.getByName( name ); - XSimpleFileAccess xSFA = UnoRuntime.queryInterface( XSimpleFileAccess.class, - xFac.createInstanceWithContext( - "com.sun.star.ucb.SimpleFileAccess", - xCtx ) ); - - if (provider.hasScriptEditor()) - { + + try { + ScriptMetaData data = (ScriptMetaData)parent.getByName(name); + XSimpleFileAccess xSFA = UnoRuntime.queryInterface(XSimpleFileAccess.class, + xFac.createInstanceWithContext( + "com.sun.star.ucb.SimpleFileAccess", + xCtx)); + + if (provider.hasScriptEditor()) { this.editable = true; - try - { + + try { if (!parent.isUnoPkg() - && !xSFA.isReadOnly(parent.getPathToParcel())) - { + && !xSFA.isReadOnly(parent.getPathToParcel())) { this.deletable = true; this.renamable = true; } } // TODO propagate errors - catch (Exception e) - { + catch (Exception e) { LogUtils.DEBUG("Caught exception in creation of ScriptBrowseNode"); LogUtils.DEBUG(LogUtils.getTrace(e)); } @@ -97,21 +92,21 @@ public class ScriptBrowseNode extends PropertySet } // TODO fix exception types to be caught here, should we rethrow? - catch ( Exception e ) - { - LogUtils.DEBUG("** caught exception getting script data for " + name + " ->" + e.toString() ); + catch (Exception e) { + LogUtils.DEBUG("** caught exception getting script data for " + name + " ->" + + e.toString()); } registerProperty("Deletable", new Type(boolean.class), - (short)0, "deletable"); + (short)0, "deletable"); registerProperty("Editable", new Type(boolean.class), - (short)0, "editable"); + (short)0, "editable"); registerProperty("Renamable", new Type(boolean.class), - (short)0, "renamable"); + (short)0, "renamable"); registerProperty("URI", new Type(String.class), - (short)0, "uri"); + (short)0, "uri"); registerProperty("Description", new Type(String.class), - (short)0, "description"); + (short)0, "description"); } @@ -136,18 +131,18 @@ public class ScriptBrowseNode extends PropertySet return getName(); } - public void updateURI( Parcel p ) { + public void updateURI(Parcel p) { parent = p; ScriptMetaData data = null; - try - { - data = (ScriptMetaData)parent.getByName( name ); + + try { + data = (ScriptMetaData)parent.getByName(name); } // TODO fix exception types to be caught here, should we rethrow? - catch ( Exception e ) - { - LogUtils.DEBUG("** caught exception getting script data for " + name + " ->" + e.toString() ); + catch (Exception e) { + LogUtils.DEBUG("** caught exception getting script data for " + name + " ->" + + e.toString()); } } // implementation of XInvocation interface @@ -157,10 +152,9 @@ public class ScriptBrowseNode extends PropertySet public Object invoke(String aFunctionName, Object[] aParams, short[][] aOutParamIndex, Object[][] aOutParam) - throws com.sun.star.lang.IllegalArgumentException, - com.sun.star.script.CannotConvertException, - com.sun.star.reflection.InvocationTargetException - { + throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.script.CannotConvertException, + com.sun.star.reflection.InvocationTargetException { // Initialise the out parameters - not used but prevents error in // UNO bridge aOutParamIndex[0] = new short[0]; @@ -168,83 +162,67 @@ public class ScriptBrowseNode extends PropertySet Any result = new Any(new Type(Boolean.class), Boolean.TRUE); - if (aFunctionName.equals("Editable")) - { - if (!editable) - { + if (aFunctionName.equals("Editable")) { + if (!editable) { NoSupportException nse = new NoSupportException( - aFunctionName + " is not editable " ); + aFunctionName + " is not editable "); throw new InvocationTargetException( - "Scripting framework error editing script", null, nse ); + "Scripting framework error editing script", null, nse); } XScriptContext ctxt = provider.getScriptingContext(); ScriptMetaData data = null; - try - { - data = (ScriptMetaData)parent.getByName( name ); - } - catch ( NoSuchElementException nse ) - { + + try { + data = (ScriptMetaData)parent.getByName(name); + } catch (NoSuchElementException nse) { throw new com.sun.star.lang.IllegalArgumentException( - name + " does not exist or can't be found " ); - } - catch ( com.sun.star.lang.WrappedTargetException wte ) - { + name + " does not exist or can't be found "); + } catch (com.sun.star.lang.WrappedTargetException wte) { // rethrow throw new InvocationTargetException( "Scripting framework editing script ", - null, wte.TargetException ); + null, wte.TargetException); } provider.getScriptEditor().edit(ctxt, data); - } - else if (aFunctionName.equals("Deletable")) - { - if (!deletable) - { + } else if (aFunctionName.equals("Deletable")) { + if (!deletable) { NoSupportException nse = new NoSupportException( - aFunctionName + " is not supported for this node" ); + aFunctionName + " is not supported for this node"); throw new InvocationTargetException( - "Scripting framework error deleting script", null, nse ); + "Scripting framework error deleting script", null, nse); } - try - { - parent.removeByName( name ); + + try { + parent.removeByName(name); result = new Any(new Type(Boolean.class), Boolean.TRUE); - } - catch ( NoSuchElementException nse ) - { + } catch (NoSuchElementException nse) { throw new com.sun.star.lang.IllegalArgumentException( - name + " does not exist or can't be found " ); - } - catch ( WrappedTargetException wte ) - { + name + " does not exist or can't be found "); + } catch (WrappedTargetException wte) { // rethrow throw new InvocationTargetException( "Scripting framework deleting script ", - null, wte.TargetException ); + null, wte.TargetException); } - } - else if (aFunctionName.equals("Renamable")) - { + } else if (aFunctionName.equals("Renamable")) { result = new Any(new Type(XBrowseNode.class), new XBrowseNode[0]); - if (!renamable) - { + + if (!renamable) { NoSupportException nse = new NoSupportException( - aFunctionName + " is not supported for this node" ); + aFunctionName + " is not supported for this node"); throw new InvocationTargetException( - "Scripting framework error renaming script", null, nse ); + "Scripting framework error renaming script", null, nse); } - try - { + try { String newName = AnyConverter.toString(aParams[0]); - ScriptMetaData oldData = (ScriptMetaData)parent.getByName( name ); + ScriptMetaData oldData = (ScriptMetaData)parent.getByName(name); oldData.loadSource(); String oldSource = oldData.getSource(); @@ -254,40 +232,33 @@ public class ScriptBrowseNode extends PropertySet String language = provider.getName(); ScriptEntry entry = new ScriptEntry( - language, languageName, "", new HashMap<String,String>() ); + language, languageName, "", new HashMap<String, String>()); ScriptMetaData data = new ScriptMetaData( - parent, entry, oldSource ); + parent, entry, oldSource); - parent.insertByName( languageName, data ); + parent.insertByName(languageName, data); LogUtils.DEBUG("Now remove old script"); - parent.removeByName( name ); + parent.removeByName(name); name = languageName; result = new Any(new Type(XBrowseNode.class), this); - } - catch ( NoSuchElementException nse ) - { + } catch (NoSuchElementException nse) { throw new com.sun.star.lang.IllegalArgumentException( - name + " does not exist or can't be found " ); - } - catch ( ElementExistException eee ) - { + name + " does not exist or can't be found "); + } catch (ElementExistException eee) { // rethrow throw new InvocationTargetException( "Scripting framework error renaming script ", - null, eee ); - } - catch ( WrappedTargetException wte ) - { + null, eee); + } catch (WrappedTargetException wte) { // rethrow throw new InvocationTargetException( "Scripting framework rename script ", - null, wte.TargetException ); + null, wte.TargetException); } - } - else { + } else { throw new com.sun.star.lang.IllegalArgumentException( "Function " + aFunctionName + " not supported."); } @@ -296,15 +267,13 @@ public class ScriptBrowseNode extends PropertySet } public void setValue(String aPropertyName, Object aValue) - throws com.sun.star.beans.UnknownPropertyException, - com.sun.star.script.CannotConvertException, - com.sun.star.reflection.InvocationTargetException - { + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.script.CannotConvertException, + com.sun.star.reflection.InvocationTargetException { } public Object getValue(String aPropertyName) - throws com.sun.star.beans.UnknownPropertyException - { + throws com.sun.star.beans.UnknownPropertyException { return null; } diff --git a/scripting/java/com/sun/star/script/framework/container/DeployedUnoPackagesDB.java b/scripting/java/com/sun/star/script/framework/container/DeployedUnoPackagesDB.java index efc9347d5d04..4ac952778c87 100644 --- a/scripting/java/com/sun/star/script/framework/container/DeployedUnoPackagesDB.java +++ b/scripting/java/com/sun/star/script/framework/container/DeployedUnoPackagesDB.java @@ -40,11 +40,11 @@ public class DeployedUnoPackagesDB { public DeployedUnoPackagesDB() throws IOException { ByteArrayInputStream bis = null; + try { bis = new ByteArrayInputStream(EMPTY_DOCUMENT); this.document = XMLParserFactory.getParser().parse(bis); - } - finally { + } finally { if (bis != null) bis.close(); } @@ -58,8 +58,7 @@ public class DeployedUnoPackagesDB { this(XMLParserFactory.getParser().parse(is)); } - public String[] getDeployedPackages( String language ) - { + public String[] getDeployedPackages(String language) { ArrayList<String> packageUrls = new ArrayList<String>(4); Element main = document.getDocumentElement(); Element root = null; @@ -67,38 +66,36 @@ public class DeployedUnoPackagesDB { NodeList langNodes = null; if ((langNodes = main.getElementsByTagName("language")) != null && - (len = langNodes.getLength()) != 0) - { - for ( int i=0; i<len; i++ ) - { - Element e = (Element)langNodes.item( i ); - if ( e.getAttribute("value").equals(language) ) - { + (len = langNodes.getLength()) != 0) { + for (int i = 0; i < len; i++) { + Element e = (Element)langNodes.item(i); + + if (e.getAttribute("value").equals(language)) { root = e; break; } } } - if ( root != null ) - { + + if (root != null) { len = 0; NodeList packages = null; + if ((packages = root.getElementsByTagName("package")) != null && - (len = packages.getLength()) != 0) - { + (len = packages.getLength()) != 0) { - for ( int i=0; i<len; i++ ) - { + for (int i = 0; i < len; i++) { - Element e = (Element)packages.item( i ); - packageUrls.add( e.getAttribute("value") ); + Element e = (Element)packages.item(i); + packageUrls.add(e.getAttribute("value")); } } } - if ( !packageUrls.isEmpty() ) - { - return packageUrls.toArray( new String[packageUrls.size()] ); + + if (!packageUrls.isEmpty()) { + return packageUrls.toArray(new String[packageUrls.size()]); } + return new String[0]; } @@ -111,52 +108,49 @@ public class DeployedUnoPackagesDB { } - public boolean removePackage( String language, String url ) - { + public boolean removePackage(String language, String url) { Element main = document.getDocumentElement(); Element langNode = null; int len = 0; NodeList langNodes = null; boolean result = false; + if ((langNodes = main.getElementsByTagName("language")) != null && - (len = langNodes.getLength()) != 0) - { - for ( int i=0; i<len; i++ ) - { - Element e = (Element)langNodes.item( i ); - if ( e.getAttribute("value").equals(language) ) - { + (len = langNodes.getLength()) != 0) { + for (int i = 0; i < len; i++) { + Element e = (Element)langNodes.item(i); + + if (e.getAttribute("value").equals(language)) { langNode = e; break; } } } - if ( langNode != null ) - { + + if (langNode != null) { len = 0; NodeList packages = null; + if ((packages = langNode.getElementsByTagName("package")) != null && - (len = packages.getLength()) != 0) - { - for ( int i=0; i<len; i++ ) - { + (len = packages.getLength()) != 0) { + for (int i = 0; i < len; i++) { - Element e = (Element)packages.item( i ); + Element e = (Element)packages.item(i); String value = e.getAttribute("value"); - if ( value.equals(url) ) - { - langNode.removeChild( e ); + if (value.equals(url)) { + langNode.removeChild(e); result = true; break; } } } } + return result; } - public void addPackage(String language, String url ) { + public void addPackage(String language, String url) { Element main = document.getDocumentElement(); Element langNode = null; Element pkgNode = null; @@ -165,25 +159,24 @@ public class DeployedUnoPackagesDB { NodeList langNodes = null; if ((langNodes = document.getElementsByTagName("language")) != null && - (len = langNodes.getLength()) != 0) - { - for ( int i=0; i<len; i++ ) - { - Element e = (Element)langNodes.item( i ); - if ( e.getAttribute("value").equals(language) ) - { + (len = langNodes.getLength()) != 0) { + for (int i = 0; i < len; i++) { + Element e = (Element)langNodes.item(i); + + if (e.getAttribute("value").equals(language)) { langNode = e; break; } } } - if ( langNode == null ) - { + + if (langNode == null) { langNode = document.createElement("language"); - langNode.setAttribute( "value", language ); + langNode.setAttribute("value", language); } + pkgNode = document.createElement("package"); - pkgNode.setAttribute( "value", url ); + pkgNode.setAttribute("value", url); langNode.appendChild(pkgNode); //add to the Top Element diff --git a/scripting/java/com/sun/star/script/framework/container/Parcel.java b/scripting/java/com/sun/star/script/framework/container/Parcel.java index bf47b60e1800..bcc24b66c2e3 100644 --- a/scripting/java/com/sun/star/script/framework/container/Parcel.java +++ b/scripting/java/com/sun/star/script/framework/container/Parcel.java @@ -28,20 +28,19 @@ import com.sun.star.ucb.XSimpleFileAccess2; import java.io.*; -public class Parcel implements XNameContainer -{ +public class Parcel implements XNameContainer { private ParcelDescriptor m_descriptor; private String name; protected ParcelContainer parent; protected XSimpleFileAccess m_xSFA; - public Parcel( XSimpleFileAccess xSFA, ParcelContainer parent, ParcelDescriptor desc, String parcelName ) - { - this( parent, desc, parcelName ); - this.m_xSFA = xSFA; + public Parcel(XSimpleFileAccess xSFA, ParcelContainer parent, + ParcelDescriptor desc, String parcelName) { + this(parent, desc, parcelName); + this.m_xSFA = xSFA; } - private Parcel( ParcelContainer parent, ParcelDescriptor desc, String parcelName ) - { + private Parcel(ParcelContainer parent, ParcelDescriptor desc, + String parcelName) { this.parent = parent; this.m_descriptor = desc; this.name = parcelName; @@ -53,23 +52,24 @@ public class Parcel implements XNameContainer * * @return <tt>true</tt> if has parent <tt>false</tt> otherwise */ - public boolean isUnoPkg() { return parent.isUnoPkg(); } + public boolean isUnoPkg() { + return parent.isUnoPkg(); + } - public String getName() - { + public String getName() { return name; } - public java.lang.Object getByName( String aName ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException - { - LogUtils.DEBUG("** Parcel.getByName for " + aName ); + public java.lang.Object getByName(String aName) throws + com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { + LogUtils.DEBUG("** Parcel.getByName for " + aName); ScriptEntry thescript = null; - try - { - if ( m_descriptor != null && hasElements() ) - { + + try { + if (m_descriptor != null && hasElements()) { ScriptEntry[] scripts = m_descriptor.getScriptEntries(); - if ( scripts.length != 0 ) - { + + if (scripts.length != 0) { for (ScriptEntry script : scripts) { if (script.getLanguageName().equals(aName)) { thescript = script; @@ -80,51 +80,50 @@ public class Parcel implements XNameContainer } } // catch unknown or un-checked exceptions - catch ( Exception e ) - { + catch (Exception e) { throw new com.sun.star.lang.WrappedTargetException(e); } - if ( thescript == null ) - { - LogUtils.DEBUG("No script for " + aName ); - throw new com.sun.star.container.NoSuchElementException("No script named " + aName ); + + if (thescript == null) { + LogUtils.DEBUG("No script for " + aName); + throw new com.sun.star.container.NoSuchElementException("No script named " + + aName); } - ScriptMetaData data = new ScriptMetaData( this, thescript, null ); - LogUtils.DEBUG("returning date for " + aName ); + ScriptMetaData data = new ScriptMetaData(this, thescript, null); + + LogUtils.DEBUG("returning date for " + aName); return data; } - public String[] getElementNames() - { + public String[] getElementNames() { String[] results = new String[0]; - if ( m_descriptor != null ) - { + + if (m_descriptor != null) { ScriptEntry[] scripts = m_descriptor.getScriptEntries(); results = new String[ scripts.length ]; - for ( int index = 0; index < scripts.length; index++ ) - { + + for (int index = 0; index < scripts.length; index++) { results[ index ] = scripts[ index ].getLanguageName(); } } + return results; } - public boolean hasByName( String aName ) - { + public boolean hasByName(String aName) { boolean result = true; Object containee = null; - try - { - containee = getByName( aName ); - if ( containee != null ) - { + + try { + containee = getByName(aName); + + if (containee != null) { result = true; } - } - catch( Exception e ) - { + } catch (Exception e) { result = false; } + return result; } @@ -136,68 +135,64 @@ public class Parcel implements XNameContainer return new Type(); } - public boolean hasElements() - { + public boolean hasElements() { return m_descriptor != null && m_descriptor.getScriptEntries().length > 0; } - public void replaceByName( String aName, java.lang.Object aElement ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException - { - // TODO check type of aElement - // if not ok, throw IllegalArgument - if ( m_descriptor != null ) - { - try - { - ScriptEntry script = (ScriptEntry)getByName( aName ); - if ( script != null ) - { - //m_descriptor.removeScriptEntry( script ); - // TODO needs to create source file ( if there is one ) - //m_descriptor.write(); - } - else - { - throw new com.sun.star.container.NoSuchElementException("No script named " + aName ); - } - - - } - // TO DO should catch specified exceptions - catch ( Exception e ) - { - throw new com.sun.star.lang.WrappedTargetException(); - } - - } - } + public void replaceByName(String aName, + java.lang.Object aElement) throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { + // TODO check type of aElement + // if not ok, throw IllegalArgument + if (m_descriptor != null) { + try { + ScriptEntry script = (ScriptEntry)getByName(aName); + + if (script != null) { + //m_descriptor.removeScriptEntry( script ); + // TODO needs to create source file ( if there is one ) + //m_descriptor.write(); + } else { + throw new com.sun.star.container.NoSuchElementException("No script named " + + aName); + } + + + } + // TO DO should catch specified exceptions + catch (Exception e) { + throw new com.sun.star.lang.WrappedTargetException(); + } + + } + } // create - public void insertByName( String aName, java.lang.Object aElement ) throws com.sun.star.lang.IllegalArgumentException, ElementExistException, com.sun.star.lang.WrappedTargetException - { + public void insertByName(String aName, + java.lang.Object aElement) throws com.sun.star.lang.IllegalArgumentException, + ElementExistException, com.sun.star.lang.WrappedTargetException { // TODO check the type of aElement and throw# // if not appropriate - try - { - if ( hasByName( aName ) ) - { - throw new ElementExistException( aName ); + try { + if (hasByName(aName)) { + throw new ElementExistException(aName); } + ScriptMetaData script = (ScriptMetaData)aElement; - if ( script.hasSource() ) - { + if (script.hasSource()) { LogUtils.DEBUG("Inserting source: " + script.getSource()); - if ( !script.writeSourceFile() ) - { - throw new com.sun.star.lang.WrappedTargetException( "Failed to create source file " + script.getLanguageName() ); + + if (!script.writeSourceFile()) { + throw new com.sun.star.lang.WrappedTargetException("Failed to create source file " + + script.getLanguageName()); } } - m_descriptor.addScriptEntry( script ); + + m_descriptor.addScriptEntry(script); writeParcelDescriptor(); - } - catch ( Exception e ) - { + } catch (Exception e) { LogUtils.DEBUG("Failed to insert entry " + aName + ": " + e.getMessage()); throw new com.sun.star.lang.WrappedTargetException(e); } @@ -205,82 +200,80 @@ public class Parcel implements XNameContainer private void writeParcelDescriptor() - throws com.sun.star.ucb.CommandAbortedException, - com.sun.star.io.IOException, - com.sun.star.uno.Exception, java.io.IOException - { + throws com.sun.star.ucb.CommandAbortedException, + com.sun.star.io.IOException, + com.sun.star.uno.Exception, java.io.IOException { String pathToDescriptor = PathUtils.make_url( - getPathToParcel(), ParcelDescriptor.PARCEL_DESCRIPTOR_NAME ); + getPathToParcel(), ParcelDescriptor.PARCEL_DESCRIPTOR_NAME); - XSimpleFileAccess2 xSFA2 = UnoRuntime.queryInterface( XSimpleFileAccess2.class, m_xSFA ); + XSimpleFileAccess2 xSFA2 = UnoRuntime.queryInterface(XSimpleFileAccess2.class, + m_xSFA); - if ( xSFA2 != null ) - { + if (xSFA2 != null) { ByteArrayOutputStream bos = null; ByteArrayInputStream bis = null; XInputStreamImpl xis = null; - try - { - bos = new ByteArrayOutputStream( 1024 ); - m_descriptor.write( bos ); - bis = new ByteArrayInputStream( bos.toByteArray() ); - - xis = new XInputStreamImpl( bis ); - xSFA2.writeFile( pathToDescriptor, xis ); - } - finally - { + + try { + bos = new ByteArrayOutputStream(1024); + m_descriptor.write(bos); + bis = new ByteArrayInputStream(bos.toByteArray()); + + xis = new XInputStreamImpl(bis); + xSFA2.writeFile(pathToDescriptor, xis); + } finally { if (bos != null) bos.close(); + if (bis != null) bis.close(); + if (xis != null) xis.closeInput(); } } } // delete - public void removeByName( String Name ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException - { - try - { - ScriptMetaData script = (ScriptMetaData)getByName( Name ); - if ( script != null ) - { - if ( !script.removeSourceFile() ) - { + public void removeByName(String Name) throws + com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { + try { + ScriptMetaData script = (ScriptMetaData)getByName(Name); + + if (script != null) { + if (!script.removeSourceFile()) { LogUtils.DEBUG("** Parcel.removeByName Failed to remove script " + Name); - throw new com.sun.star.lang.WrappedTargetException("Failed to remove script " + Name); + throw new com.sun.star.lang.WrappedTargetException("Failed to remove script " + + Name); } - LogUtils.DEBUG("** Parcel.removeByName have removed script source file " + Name); - m_descriptor.removeScriptEntry( script ); + + LogUtils.DEBUG("** Parcel.removeByName have removed script source file " + + Name); + m_descriptor.removeScriptEntry(script); writeParcelDescriptor(); - } - else - { - throw new com.sun.star.container.NoSuchElementException( "No script named " + Name ); + } else { + throw new com.sun.star.container.NoSuchElementException("No script named " + + Name); } - } - catch ( Exception e ) - { - LogUtils.DEBUG("** Parcel.removeByName Exception: " + e ); + } catch (Exception e) { + LogUtils.DEBUG("** Parcel.removeByName Exception: " + e); throw new com.sun.star.lang.WrappedTargetException(e); } } // rename parcel - public void rename( String name ) - { + public void rename(String name) { this.name = name; } - public ParcelContainer getParent() { return parent; } + public ParcelContainer getParent() { + return parent; + } /** * Returns the path of this <tt>Parcel</tt> * * @return <tt>String</tt> path to parcel */ - public String getPathToParcel() - { + public String getPathToParcel() { String path = parent.getParcelContainerDir() + "/" + name; return path; } diff --git a/scripting/java/com/sun/star/script/framework/container/ParcelContainer.java b/scripting/java/com/sun/star/script/framework/container/ParcelContainer.java index 6e954af9b970..75cd6ce542ed 100644 --- a/scripting/java/com/sun/star/script/framework/container/ParcelContainer.java +++ b/scripting/java/com/sun/star/script/framework/container/ParcelContainer.java @@ -43,15 +43,15 @@ import com.sun.star.uri.XVndSunStarScriptUrl; * ScripingFramework specific Libraries. */ -public class ParcelContainer implements XNameAccess -{ +public class ParcelContainer implements XNameAccess { protected String language; protected String containerUrl; private Collection<Parcel> parcels = new ArrayList<Parcel>(10); static protected XSimpleFileAccess m_xSFA; protected XComponentContext m_xCtx; private ParcelContainer parent = null; - private Collection<ParcelContainer> childContainers = new ArrayList<ParcelContainer>(10); + private Collection<ParcelContainer> childContainers = new + ArrayList<ParcelContainer>(10); private boolean isPkgContainer = false; /** @@ -60,7 +60,9 @@ public class ParcelContainer implements XNameAccess * * @return <tt>true</tt> if has parent <tt>false</tt> otherwise */ - public boolean isUnoPkg() { return isPkgContainer; } + public boolean isUnoPkg() { + return isPkgContainer; + } /** @@ -68,8 +70,7 @@ public class ParcelContainer implements XNameAccess * * @return <tt>ParcelContainer</tt> if has parent null otherwise */ - public ParcelContainer parent() - { + public ParcelContainer parent() { return parent; } @@ -80,13 +81,12 @@ public class ParcelContainer implements XNameAccess * @return a new array of ParcelContainers. A zero * length array is returned if no child ParcelContainers. */ - public ParcelContainer[] getChildContainers() - { - if ( childContainers.isEmpty() ) - { + public ParcelContainer[] getChildContainers() { + if (childContainers.isEmpty()) { return new ParcelContainer[0]; } - return childContainers.toArray( new ParcelContainer[childContainers.size()] ); + + return childContainers.toArray(new ParcelContainer[childContainers.size()]); } /** @@ -96,9 +96,8 @@ public class ParcelContainer implements XNameAccess * * @return <tt>true</tt> if child successfully removed */ - public boolean removeChildContainer( ParcelContainer child ) - { - return childContainers.remove( child ); + public boolean removeChildContainer(ParcelContainer child) { + return childContainers.remove(child); } /** @@ -107,9 +106,8 @@ public class ParcelContainer implements XNameAccess * @param child <tt>ParcelContainer</tt> to be added. * */ - public void addChildContainer( ParcelContainer child ) - { - childContainers.add( child ); + public void addChildContainer(ParcelContainer child) { + childContainers.add(child); } /** @@ -121,19 +119,19 @@ public class ParcelContainer implements XNameAccess * @return child <tt>ParcelContainer</tt> or {@code null} if none * found. */ - public ParcelContainer getChildContainer(String key) - { + public ParcelContainer getChildContainer(String key) { ParcelContainer result = null; - for (ParcelContainer c : childContainers) - { + + for (ParcelContainer c : childContainers) { String location = ScriptMetaData.getLocationPlaceHolder( - c.containerUrl, c.getName()); - if ( key.equals( location ) ) - { + c.containerUrl, c.getName()); + + if (key.equals(location)) { result = c; break; } } + return result; } @@ -147,17 +145,16 @@ public class ParcelContainer implements XNameAccess * @return child <tt>ParcelContainer</tt> or {@code null} if none * found. */ - public ParcelContainer getChildContainerForURL( String containerUrl ) - { + public ParcelContainer getChildContainerForURL(String containerUrl) { ParcelContainer result = null; - for (ParcelContainer c : childContainers) - { - if ( containerUrl.equals( c.containerUrl ) ) - { + + for (ParcelContainer c : childContainers) { + if (containerUrl.equals(c.containerUrl)) { result = c; break; } } + return result; } @@ -168,33 +165,28 @@ public class ParcelContainer implements XNameAccess * @return name of <tt>ParcelContainer</tt> * found. */ - public String getName() - { + public String getName() { String name = null; + // TODO handler package ParcelContainer? - if ( !containerUrl.startsWith( "vnd.sun.star.tdoc:" ) ) - { - try - { + if (!containerUrl.startsWith("vnd.sun.star.tdoc:")) { + try { // return name - String decodedUrl = java.net.URLDecoder.decode( containerUrl, "UTF-8" ); + String decodedUrl = java.net.URLDecoder.decode(containerUrl, "UTF-8"); int indexOfSlash = decodedUrl.lastIndexOf('/'); - if ( indexOfSlash != -1 ) - { - name = decodedUrl.substring( indexOfSlash + 1 ); + + if (indexOfSlash != -1) { + name = decodedUrl.substring(indexOfSlash + 1); } - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { com.sun.star.uno.RuntimeException e2 = new com.sun.star.uno.RuntimeException(); e2.initCause(e); throw e2; } - } - else - { + } else { name = "document"; } + return name; } @@ -204,10 +196,12 @@ public class ParcelContainer implements XNameAccess * @param containerUrl location of this container. * @param language language for which entries are stored */ - public ParcelContainer( XComponentContext xCtx, String containerUrl, String language ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException + public ParcelContainer(XComponentContext xCtx, String containerUrl, + String language) throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.lang.WrappedTargetException { - this( null, xCtx, containerUrl, language, true ); + this(null, xCtx, containerUrl, language, true); } /** @@ -218,9 +212,11 @@ public class ParcelContainer implements XNameAccess * @param loadParcels set to <tt>true</tt> if parcels are to be loaded * on construction. */ - public ParcelContainer( XComponentContext xCtx, String containerUrl, String language, boolean loadParcels ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException - { - this( null, xCtx, containerUrl, language, loadParcels ); + public ParcelContainer(XComponentContext xCtx, String containerUrl, + String language, boolean loadParcels) throws + com.sun.star.lang.IllegalArgumentException, + com.sun.star.lang.WrappedTargetException { + this(null, xCtx, containerUrl, language, loadParcels); } /** @@ -232,10 +228,14 @@ public class ParcelContainer implements XNameAccess * @param loadParcels set to <tt>true</tt> if parcels are to be loaded * on construction. */ - public ParcelContainer( ParcelContainer parent, XComponentContext xCtx, String containerUrl, String language, boolean loadParcels ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException + public ParcelContainer(ParcelContainer parent, XComponentContext xCtx, + String containerUrl, String language, + boolean loadParcels) throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.lang.WrappedTargetException { - LogUtils.DEBUG("Creating ParcelContainer for " + containerUrl + " loadParcels = " + loadParcels + " language = " + language ); + LogUtils.DEBUG("Creating ParcelContainer for " + containerUrl + + " loadParcels = " + loadParcels + " language = " + language); this.m_xCtx = xCtx; this.language = language; this.parent = parent; @@ -244,437 +244,413 @@ public class ParcelContainer implements XNameAccess initSimpleFileAccess(); boolean parentIsPkgContainer = false; - if ( parent != null ) - { + if (parent != null) { parentIsPkgContainer = parent.isUnoPkg(); } - if ( containerUrl.endsWith("uno_packages") || parentIsPkgContainer ) - { + if (containerUrl.endsWith("uno_packages") || parentIsPkgContainer) { isPkgContainer = true; } - if ( loadParcels ) - { + if (loadParcels) { loadParcels(); } } - public String getContainerURL() { return this.containerUrl; } + public String getContainerURL() { + return this.containerUrl; + } - private synchronized void initSimpleFileAccess() - { - if ( m_xSFA != null ) - { + private synchronized void initSimpleFileAccess() { + if (m_xSFA != null) { return; } - try - { + + try { m_xSFA = UnoRuntime.queryInterface( - XSimpleFileAccess.class, - m_xCtx.getServiceManager().createInstanceWithContext( - "com.sun.star.ucb.SimpleFileAccess", m_xCtx ) ); - } - catch ( Exception e ) - { + XSimpleFileAccess.class, + m_xCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.ucb.SimpleFileAccess", m_xCtx)); + } catch (Exception e) { // TODO should throw LogUtils.DEBUG("Error instantiating simplefile access "); - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + LogUtils.DEBUG(LogUtils.getTrace(e)); } } - public String getParcelContainerDir() - { + public String getParcelContainerDir() { // If this container does not represent an uno-package // then then it is a document, user or share // in each case the convention is to have a Scripts/[language] // dir where scripts reside - if ( !isUnoPkg() ) - { - return PathUtils.make_url( containerUrl , "Scripts/" + language.toLowerCase() ); + if (!isUnoPkg()) { + return PathUtils.make_url(containerUrl , "Scripts/" + language.toLowerCase()); } + return containerUrl; } - public Object getByName( String aName ) throws com.sun.star.container.NoSuchElementException, WrappedTargetException - { + public Object getByName(String aName) throws + com.sun.star.container.NoSuchElementException, WrappedTargetException { Parcel parcel = null; - try - { - if ( hasElements() ) - { - for (Parcel parcelToCheck : parcels) - { - if ( parcelToCheck.getName().equals( aName ) ) - { - parcel = parcelToCheck; - break; + + try { + if (hasElements()) { + for (Parcel parcelToCheck : parcels) { + if (parcelToCheck.getName().equals(aName)) { + parcel = parcelToCheck; + break; } } } - } - catch ( Exception e) - { + } catch (Exception e) { throw new WrappedTargetException(e); } - if ( parcel == null ) - { - throw new com.sun.star.container.NoSuchElementException( "Macro Library " + aName + " not found" ); + + if (parcel == null) { + throw new com.sun.star.container.NoSuchElementException("Macro Library " + aName + + " not found"); } + return parcel; } - public String[] getElementNames() - { - if ( hasElements() ) - { - Parcel[] theParcels = parcels.toArray( new Parcel[parcels.size()] ); + public String[] getElementNames() { + if (hasElements()) { + Parcel[] theParcels = parcels.toArray(new Parcel[parcels.size()]); String[] names = new String[ theParcels.length ]; - for ( int count = 0; count < names.length; count++ ) - { + + for (int count = 0; count < names.length; count++) { names[count] = theParcels[ count ].getName(); } + return names; } return new String[0]; } - public boolean hasByName( String aName ) - { + public boolean hasByName(String aName) { boolean isFound = false; - try - { - if ( getByName( aName ) != null ) - { + + try { + if (getByName(aName) != null) { isFound = true; } - } - catch ( Exception e ) - { + } catch (Exception e) { //TODO - handle trace } + return isFound; } - public Type getElementType() - { + public Type getElementType() { return new Type(); } - public boolean hasElements() - { + public boolean hasElements() { return !(parcels == null || parcels.isEmpty()); } - private void loadParcels() throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException - { - try - { - LogUtils.DEBUG("About to load parcels from " + containerUrl ); - if ( m_xSFA.isFolder( getParcelContainerDir() ) ) - { - LogUtils.DEBUG( getParcelContainerDir() + " is a folder " ); - String[] children = m_xSFA.getFolderContents( getParcelContainerDir(), true ); + private void loadParcels() throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.lang.WrappedTargetException { + try { + LogUtils.DEBUG("About to load parcels from " + containerUrl); + + if (m_xSFA.isFolder(getParcelContainerDir())) { + LogUtils.DEBUG(getParcelContainerDir() + " is a folder "); + String[] children = m_xSFA.getFolderContents(getParcelContainerDir(), true); parcels = new ArrayList<Parcel>(children.length); - for (String child : children) - { + + for (String child : children) { LogUtils.DEBUG("Processing " + child); - try - { + + try { loadParcel(child); - } - catch (java.lang.Exception e) - { + } catch (java.lang.Exception e) { // print an error message and move on to // the next parcel - LogUtils.DEBUG("ParcelContainer.loadParcels caught " + e.getClass().getName() + " exception loading parcel " + child + ": " + e.getMessage()); + LogUtils.DEBUG("ParcelContainer.loadParcels caught " + e.getClass().getName() + + " exception loading parcel " + child + ": " + e.getMessage()); } } - } - else - { - LogUtils.DEBUG(" ParcelCOntainer.loadParcels " + getParcelContainerDir() + " is not a folder "); + } else { + LogUtils.DEBUG(" ParcelCOntainer.loadParcels " + getParcelContainerDir() + + " is not a folder "); } - } - catch ( com.sun.star.ucb.CommandAbortedException e ) - { - LogUtils.DEBUG("ParcelContainer.loadParcels caught exception processing folders for " + getParcelContainerDir() ); - LogUtils.DEBUG("TRACE: " + LogUtils.getTrace(e) ); + } catch (com.sun.star.ucb.CommandAbortedException e) { + LogUtils.DEBUG("ParcelContainer.loadParcels caught exception processing folders for " + + getParcelContainerDir()); + LogUtils.DEBUG("TRACE: " + LogUtils.getTrace(e)); throw new com.sun.star.lang.WrappedTargetException(e); - } - catch ( com.sun.star.uno.Exception e ) - { - LogUtils.DEBUG("ParcelContainer.loadParcels caught exception processing folders for " + getParcelContainerDir() ); - LogUtils.DEBUG("TRACE: " + LogUtils.getTrace(e) ); + } catch (com.sun.star.uno.Exception e) { + LogUtils.DEBUG("ParcelContainer.loadParcels caught exception processing folders for " + + getParcelContainerDir()); + LogUtils.DEBUG("TRACE: " + LogUtils.getTrace(e)); throw new com.sun.star.lang.WrappedTargetException(e); } } - public XNameContainer createParcel(String name) throws ElementExistException, com.sun.star.lang.WrappedTargetException - { + public XNameContainer createParcel(String name) throws ElementExistException, + com.sun.star.lang.WrappedTargetException { Parcel p = null; - if ( hasByName( name ) ) - { - throw new ElementExistException( "Parcel " + name + " already exists" ); + + if (hasByName(name)) { + throw new ElementExistException("Parcel " + name + " already exists"); } - String pathToParcel = PathUtils.make_url( getParcelContainerDir() , name ); - try - { - LogUtils.DEBUG("ParcelContainer.createParcel, creating folder " + pathToParcel ); - m_xSFA.createFolder( pathToParcel ); + String pathToParcel = PathUtils.make_url(getParcelContainerDir() , name); + + try { + LogUtils.DEBUG("ParcelContainer.createParcel, creating folder " + pathToParcel); + m_xSFA.createFolder(pathToParcel); - LogUtils.DEBUG("ParcelContainer.createParcel, folder " + pathToParcel + " created "); + LogUtils.DEBUG("ParcelContainer.createParcel, folder " + pathToParcel + + " created "); ParcelDescriptor pd = new ParcelDescriptor(); - pd.setLanguage( language ); - String parcelDesc = PathUtils.make_url( pathToParcel, ParcelDescriptor.PARCEL_DESCRIPTOR_NAME ); - XSimpleFileAccess2 xSFA2 = UnoRuntime.queryInterface( XSimpleFileAccess2.class, m_xSFA ); - if ( xSFA2 != null ) - { - LogUtils.DEBUG("createParcel() Using XSIMPLEFILEACCESS2 " + parcelDesc ); - ByteArrayOutputStream bos = new ByteArrayOutputStream( 1024 ); - pd.write( bos ); + pd.setLanguage(language); + String parcelDesc = PathUtils.make_url(pathToParcel, + ParcelDescriptor.PARCEL_DESCRIPTOR_NAME); + XSimpleFileAccess2 xSFA2 = UnoRuntime.queryInterface(XSimpleFileAccess2.class, + m_xSFA); + + if (xSFA2 != null) { + LogUtils.DEBUG("createParcel() Using XSIMPLEFILEACCESS2 " + parcelDesc); + ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); + pd.write(bos); bos.close(); - ByteArrayInputStream bis = new ByteArrayInputStream( bos.toByteArray() ); - XInputStreamImpl xis = new XInputStreamImpl( bis ); - xSFA2.writeFile( parcelDesc, xis ); + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + XInputStreamImpl xis = new XInputStreamImpl(bis); + xSFA2.writeFile(parcelDesc, xis); xis.closeInput(); - p = loadParcel( pathToParcel ); + p = loadParcel(pathToParcel); } - } - catch ( Exception e ) - { + } catch (Exception e) { - LogUtils.DEBUG("createParcel() Exception while attempting to create = " + name ); + LogUtils.DEBUG("createParcel() Exception while attempting to create = " + name); throw new com.sun.star.lang.WrappedTargetException(e); } + return p; } - public Parcel loadParcel( String parcelUrl ) throws com.sun.star.lang.WrappedTargetException, com.sun.star.lang.IllegalArgumentException - { + public Parcel loadParcel(String parcelUrl) throws + com.sun.star.lang.WrappedTargetException, + com.sun.star.lang.IllegalArgumentException { - String parcelDescUrl = PathUtils.make_url( parcelUrl, ParcelDescriptor.PARCEL_DESCRIPTOR_NAME ); + String parcelDescUrl = PathUtils.make_url(parcelUrl, + ParcelDescriptor.PARCEL_DESCRIPTOR_NAME); Parcel parcel = null; XInputStream xis = null; InputStream is = null; - try - { - if ( m_xSFA.exists( parcelDescUrl ) ) - { - LogUtils.DEBUG("ParcelContainer.loadParcel opening " + parcelDescUrl ); - xis = m_xSFA.openFileRead( parcelDescUrl ); - is = new XInputStreamWrapper( xis ); + try { + if (m_xSFA.exists(parcelDescUrl)) { + LogUtils.DEBUG("ParcelContainer.loadParcel opening " + parcelDescUrl); + xis = m_xSFA.openFileRead(parcelDescUrl); + is = new XInputStreamWrapper(xis); ParcelDescriptor pd = new ParcelDescriptor(is) ; - try - { + + try { is.close(); is = null; + } catch (Exception e) { + LogUtils.DEBUG("ParcelContainer.loadParcel Exception when closing stream for " + + parcelDescUrl + " :" + e); } - catch ( Exception e ) - { - LogUtils.DEBUG("ParcelContainer.loadParcel Exception when closing stream for " + parcelDescUrl + " :" + e ); - } - LogUtils.DEBUG("ParcelContainer.loadParcel closed " + parcelDescUrl ); - if ( !pd.getLanguage().equals( language ) ) - { + + LogUtils.DEBUG("ParcelContainer.loadParcel closed " + parcelDescUrl); + + if (!pd.getLanguage().equals(language)) { LogUtils.DEBUG("ParcelContainer.loadParcel Language of Parcel does not match this container "); return null; } - LogUtils.DEBUG("Processing " + parcelDescUrl + " closed " ); + + LogUtils.DEBUG("Processing " + parcelDescUrl + " closed "); int indexOfSlash = parcelUrl.lastIndexOf('/'); - String name = parcelUrl.substring( indexOfSlash + 1 ); + String name = parcelUrl.substring(indexOfSlash + 1); - parcel = new Parcel( m_xSFA, this, pd, name ); + parcel = new Parcel(m_xSFA, this, pd, name); - LogUtils.DEBUG(" ParcelContainer.loadParcel created parcel for " + parcelDescUrl + " for language " + language ); - parcels.add( parcel ); - } - else - { - throw new java.io.IOException( parcelDescUrl + " does NOT exist!"); + LogUtils.DEBUG(" ParcelContainer.loadParcel created parcel for " + parcelDescUrl + + " for language " + language); + parcels.add(parcel); + } else { + throw new java.io.IOException(parcelDescUrl + " does NOT exist!"); } - } - catch ( com.sun.star.ucb.CommandAbortedException e ) - { + } catch (com.sun.star.ucb.CommandAbortedException e) { - LogUtils.DEBUG("loadParcel() Exception while accessing filesystem url = " + parcelDescUrl + e ); + LogUtils.DEBUG("loadParcel() Exception while accessing filesystem url = " + + parcelDescUrl + e); throw new com.sun.star.lang.WrappedTargetException(e); - } - catch ( java.io.IOException e ) - { - LogUtils.DEBUG("ParcelContainer.loadParcel() caught IOException while accessing " + parcelDescUrl + ": " + e ); + } catch (java.io.IOException e) { + LogUtils.DEBUG("ParcelContainer.loadParcel() caught IOException while accessing " + + parcelDescUrl + ": " + e); throw new com.sun.star.lang.WrappedTargetException(e); - } - catch ( com.sun.star.uno.Exception e ) - { + } catch (com.sun.star.uno.Exception e) { - LogUtils.DEBUG("loadParcel() Exception while accessing filesystem url = " + parcelDescUrl + e ); + LogUtils.DEBUG("loadParcel() Exception while accessing filesystem url = " + + parcelDescUrl + e); throw new com.sun.star.lang.WrappedTargetException(e); } - finally - { - if ( is != null ) - { - try - { + finally { + if (is != null) { + try { is.close(); // is will close xis + } catch (Exception ignore) { } - catch ( Exception ignore ) - { - } - } - else if ( xis != null ) - { - try - { + } else if (xis != null) { + try { xis.closeInput(); - } - catch ( Exception ignore ) - { + } catch (Exception ignore) { } } } + return parcel; } - public void renameParcel(String oldName, String newName) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException - { - LogUtils.DEBUG(" ** ParcelContainer Renaming parcel " + oldName + " to " + newName ); - LogUtils.DEBUG(" ** ParcelContainer is " + this ); - Parcel p = (Parcel)getByName( oldName ); - if ( p == null ) - { - throw new com.sun.star.container.NoSuchElementException( "No parcel named " + oldName ); - } - String oldParcelDirUrl = PathUtils.make_url( getParcelContainerDir(), - oldName ); - String newParcelDirUrl = PathUtils.make_url( getParcelContainerDir(), - newName ); - try - { - if (!m_xSFA.isFolder( oldParcelDirUrl ) ) - { - Exception e = new com.sun.star.io.IOException("Invalid Parcel directory: " + oldName ); + public void renameParcel(String oldName, + String newName) throws com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { + LogUtils.DEBUG(" ** ParcelContainer Renaming parcel " + oldName + " to " + + newName); + LogUtils.DEBUG(" ** ParcelContainer is " + this); + Parcel p = (Parcel)getByName(oldName); + + if (p == null) { + throw new com.sun.star.container.NoSuchElementException("No parcel named " + + oldName); + } + + String oldParcelDirUrl = PathUtils.make_url(getParcelContainerDir(), + oldName); + String newParcelDirUrl = PathUtils.make_url(getParcelContainerDir(), + newName); + + try { + if (!m_xSFA.isFolder(oldParcelDirUrl)) { + Exception e = new com.sun.star.io.IOException("Invalid Parcel directory: " + + oldName); throw new com.sun.star.lang.WrappedTargetException(e); } - LogUtils.DEBUG(" ** ParcelContainer Renaming folder " + oldParcelDirUrl + " to " + newParcelDirUrl ); - m_xSFA.move( oldParcelDirUrl, newParcelDirUrl ); - } - catch ( com.sun.star.ucb.CommandAbortedException ce ) - { - LogUtils.DEBUG(" ** ParcelContainer Renaming failed with " + ce ); + + LogUtils.DEBUG(" ** ParcelContainer Renaming folder " + oldParcelDirUrl + " to " + + newParcelDirUrl); + m_xSFA.move(oldParcelDirUrl, newParcelDirUrl); + } catch (com.sun.star.ucb.CommandAbortedException ce) { + LogUtils.DEBUG(" ** ParcelContainer Renaming failed with " + ce); throw new com.sun.star.lang.WrappedTargetException(ce); - } - catch ( com.sun.star.uno.Exception e ) - { - LogUtils.DEBUG(" ** ParcelContainer Renaming failed with " + e ); + } catch (com.sun.star.uno.Exception e) { + LogUtils.DEBUG(" ** ParcelContainer Renaming failed with " + e); throw new com.sun.star.lang.WrappedTargetException(e); } - p.rename( newName ); + p.rename(newName); } // removes but doesn't physically delele parcel from container - public boolean removeParcel(String name) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException - { - Parcel p = (Parcel)getByName( name ); - if ( p == null ) - { - throw new com.sun.star.container.NoSuchElementException("No parcel named " + name ); + public boolean removeParcel(String name) throws + com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { + Parcel p = (Parcel)getByName(name); + + if (p == null) { + throw new com.sun.star.container.NoSuchElementException("No parcel named " + + name); } - return parcels.remove( p ); + return parcels.remove(p); } - public boolean deleteParcel(String name) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException - { - LogUtils.DEBUG( "deleteParcel for containerURL " + containerUrl + " name = " + name + " Langueg = " + language ); + public boolean deleteParcel(String name) throws + com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { + LogUtils.DEBUG("deleteParcel for containerURL " + containerUrl + " name = " + + name + " Langueg = " + language); - Parcel p = (Parcel)getByName( name ); - if ( p == null ) - { - throw new com.sun.star.container.NoSuchElementException("No parcel named " + name ); - } + Parcel p = (Parcel)getByName(name); - try - { - String pathToParcel = PathUtils.make_url( getParcelContainerDir(), name ); - m_xSFA.kill( pathToParcel ); + if (p == null) { + throw new com.sun.star.container.NoSuchElementException("No parcel named " + + name); } - catch( Exception e ) - { - LogUtils.DEBUG("Error deleteing parcel " + name ); + + try { + String pathToParcel = PathUtils.make_url(getParcelContainerDir(), name); + m_xSFA.kill(pathToParcel); + } catch (Exception e) { + LogUtils.DEBUG("Error deleteing parcel " + name); throw new com.sun.star.lang.WrappedTargetException(e); } - return parcels.remove( p ); + return parcels.remove(p); } - public String getLanguage() { return language; } + public String getLanguage() { + return language; + } - public ScriptMetaData findScript( ParsedScriptUri parsedUri ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException - { - Parcel p = (Parcel)getByName( parsedUri.parcel); - ScriptMetaData scriptData = (ScriptMetaData)p.getByName( parsedUri.function); - LogUtils.DEBUG("** found script data for " + parsedUri.function + " script is " + scriptData ); + public ScriptMetaData findScript(ParsedScriptUri parsedUri) throws + com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { + Parcel p = (Parcel)getByName(parsedUri.parcel); + ScriptMetaData scriptData = (ScriptMetaData)p.getByName(parsedUri.function); + LogUtils.DEBUG("** found script data for " + parsedUri.function + " script is " + + scriptData); return scriptData; } -public ParsedScriptUri parseScriptUri( String scriptURI ) throws com.sun.star.lang.IllegalArgumentException -{ + public ParsedScriptUri parseScriptUri(String scriptURI) throws + com.sun.star.lang.IllegalArgumentException { XMultiComponentFactory xMcFac = null; XUriReferenceFactory xFac = null; - try - { + try { xMcFac = m_xCtx.getServiceManager(); - xFac = UnoRuntime.queryInterface( XUriReferenceFactory.class, - xMcFac.createInstanceWithContext( - "com.sun.star.uri.UriReferenceFactory", m_xCtx ) ); - } - catch( com.sun.star.uno.Exception e ) - { - LogUtils.DEBUG("Problems parsing URL:" + e.toString() ); + xFac = UnoRuntime.queryInterface(XUriReferenceFactory.class, + xMcFac.createInstanceWithContext( + "com.sun.star.uri.UriReferenceFactory", m_xCtx)); + } catch (com.sun.star.uno.Exception e) { + LogUtils.DEBUG("Problems parsing URL:" + e.toString()); throw new com.sun.star.lang.IllegalArgumentException(e, "Problems parsing URL"); } - if ( xFac == null ) - { + + if (xFac == null) { LogUtils.DEBUG("Failed to create UrlReference factory"); - throw new com.sun.star.lang.IllegalArgumentException( "Failed to create UrlReference factory for url " + scriptURI ); + throw new com.sun.star.lang.IllegalArgumentException("Failed to create UrlReference factory for url " + + scriptURI); } - XUriReference uriRef = xFac.parse( scriptURI ); - XVndSunStarScriptUrl sfUri = UnoRuntime.queryInterface( XVndSunStarScriptUrl.class, uriRef ); + XUriReference uriRef = xFac.parse(scriptURI); + XVndSunStarScriptUrl sfUri = UnoRuntime.queryInterface( + XVndSunStarScriptUrl.class, uriRef); - if ( sfUri == null ) - { + if (sfUri == null) { LogUtils.DEBUG("Failed to parse url"); - throw new com.sun.star.lang.IllegalArgumentException( "Failed to parse url " + scriptURI ); + throw new com.sun.star.lang.IllegalArgumentException("Failed to parse url " + + scriptURI); } ParsedScriptUri parsedUri = new ParsedScriptUri(); - parsedUri.function= sfUri.getName(); + parsedUri.function = sfUri.getName(); parsedUri.parcel = ""; // parse parcel name; - StringTokenizer tokenizer = new StringTokenizer( parsedUri.function, "." ); + StringTokenizer tokenizer = new StringTokenizer(parsedUri.function, "."); - if ( tokenizer.hasMoreElements() ) - { + if (tokenizer.hasMoreElements()) { parsedUri.parcel = (String)tokenizer.nextElement(); - LogUtils.DEBUG("** parcelName = " + parsedUri.parcel ); + LogUtils.DEBUG("** parcelName = " + parsedUri.parcel); } - if ( parsedUri.function != null && ( parsedUri.function.length() > 0 ) ) - { + if (parsedUri.function != null && (parsedUri.function.length() > 0)) { // strip out parcel name - parsedUri.function = parsedUri.function.substring( parsedUri.parcel.length() + 1); + parsedUri.function = parsedUri.function.substring(parsedUri.parcel.length() + + 1); } // parse location @@ -685,11 +661,11 @@ public ParsedScriptUri parseScriptUri( String scriptURI ) throws com.sun.star.l // time its got to here LogUtils.DEBUG("** location = " + parsedUri.location + - "\nfunction = " + parsedUri.function + - "\nparcel = " + parsedUri.parcel + - "\nlocation = " + parsedUri.location ); + "\nfunction = " + parsedUri.function + + "\nparcel = " + parsedUri.parcel + + "\nlocation = " + parsedUri.location); return parsedUri; -} + } } diff --git a/scripting/java/com/sun/star/script/framework/container/ParcelDescriptor.java b/scripting/java/com/sun/star/script/framework/container/ParcelDescriptor.java index 2d44ff55944e..77b2f9fb3810 100644 --- a/scripting/java/com/sun/star/script/framework/container/ParcelDescriptor.java +++ b/scripting/java/com/sun/star/script/framework/container/ParcelDescriptor.java @@ -38,10 +38,11 @@ public class ParcelDescriptor { // File name to be used for parcel descriptor files public static final String - PARCEL_DESCRIPTOR_NAME = "parcel-descriptor.xml"; + PARCEL_DESCRIPTOR_NAME = "parcel-descriptor.xml"; // Collection of all ParcelDescriptor created for files - private static final Map<File,ParcelDescriptor> PARCEL_DESCRIPTOR_MAP = new HashMap<File,ParcelDescriptor>(5); + private static final Map<File, ParcelDescriptor> PARCEL_DESCRIPTOR_MAP = new + HashMap<File, ParcelDescriptor>(5); // This is the default contents of a parcel descriptor to be used when // creating empty descriptors @@ -53,7 +54,7 @@ public class ParcelDescriptor { private File file = null; private Document document = null; private String language = null; - private Map<String,String> languagedepprops = new HashMap<String,String>(3); + private Map<String, String> languagedepprops = new HashMap<String, String>(3); @@ -61,11 +62,11 @@ public class ParcelDescriptor { public ParcelDescriptor() throws IOException { ByteArrayInputStream bis = null; + try { bis = new ByteArrayInputStream(EMPTY_DOCUMENT); this.document = XMLParserFactory.getParser().parse(bis); - } - finally { + } finally { if (bis != null) bis.close(); } @@ -89,27 +90,28 @@ public class ParcelDescriptor { if (file.exists()) { FileInputStream fis = null; + try { fis = new FileInputStream(file); this.document = XMLParserFactory.getParser().parse(fis); - } - finally { + } finally { if (fis != null) fis.close(); } - } - else { + } else { ByteArrayInputStream bis = null; + try { bis = new ByteArrayInputStream(EMPTY_DOCUMENT); this.document = XMLParserFactory.getParser().parse(bis); - } - finally { + } finally { if (bis != null) bis.close(); } + setLanguage(language); } + initLanguageProperties(); } @@ -128,6 +130,7 @@ public class ParcelDescriptor { language = e.getAttribute("language"); } } + return language; } @@ -138,8 +141,7 @@ public class ParcelDescriptor { try { Element e = document.getDocumentElement(); e.setAttribute("language", language); - } - catch (DOMException de) { + } catch (DOMException de) { } } } @@ -156,7 +158,7 @@ public class ParcelDescriptor { for (int i = 0; i < len; i++) { String language, languagename, logicalname, description = ""; - Map<String,String> langProps = new HashMap<String,String>(); + Map<String, String> langProps = new HashMap<String, String>(); NodeList nl; Element tmp; @@ -164,6 +166,7 @@ public class ParcelDescriptor { language = scriptElement.getAttribute("language"); nl = scriptElement.getElementsByTagName("logicalname"); + if (nl == null) logicalname = ""; else { @@ -173,15 +176,13 @@ public class ParcelDescriptor { // get the text of the description element nl = scriptElement.getElementsByTagName("locale"); - if (nl != null) - { + + if (nl != null) { nl = nl.item(0).getChildNodes(); - if (nl != null) - { - for (int j = 0 ; j < nl.getLength(); j++) - { - if (nl.item(j).getNodeName().equals("description")) - { + + if (nl != null) { + for (int j = 0 ; j < nl.getLength(); j++) { + if (nl.item(j).getNodeName().equals("description")) { CharacterData cd = (CharacterData)nl.item(j).getFirstChild(); description = cd.getData().trim(); @@ -191,36 +192,41 @@ public class ParcelDescriptor { } nl = scriptElement.getElementsByTagName("functionname"); + if (nl == null) { languagename = ""; } else { tmp = (Element)nl.item(0); languagename = tmp.getAttribute("value"); } + nl = scriptElement.getElementsByTagName("languagedepprops"); - if ( nl != null && nl.getLength() > 0 ) - { + + if (nl != null && nl.getLength() > 0) { NodeList props = ((Element)nl.item(0)).getElementsByTagName("prop"); - if ( props != null ) - { - for ( int j=0; j < props.getLength(); j++ ) - { + + if (props != null) { + for (int j = 0; j < props.getLength(); j++) { tmp = (Element)props.item(j); String key = tmp.getAttribute("name"); String val = tmp.getAttribute("value"); - langProps.put( key,val ); + langProps.put(key, val); } } } - ScriptEntry entry = new ScriptEntry(language, languagename, "", langProps,description); + + ScriptEntry entry = new ScriptEntry(language, languagename, "", langProps, + description); scripts.add(entry); } + return scripts.toArray(new ScriptEntry[scripts.size()]); } public void setScriptEntries(ScriptEntry[] scripts) { clearEntries(); + for (ScriptEntry script : scripts) { addScriptEntry(script); } @@ -228,6 +234,7 @@ public class ParcelDescriptor { public void setScriptEntries(Iterator<ScriptEntry> scripts) { clearEntries(); + while (scripts.hasNext()) addScriptEntry(scripts.next()); } @@ -271,13 +278,11 @@ public class ParcelDescriptor { int len; if ((scriptNodes = document.getElementsByTagName("script")) != null && - (len = scriptNodes.getLength()) != 0) - { + (len = scriptNodes.getLength()) != 0) { for (int i = len - 1; i >= 0; i--) { try { main.removeChild(scriptNodes.item(i)); - } - catch (DOMException de) { + } catch (DOMException de) { // ignore } } @@ -290,8 +295,7 @@ public class ParcelDescriptor { int len; if ((scriptNodes = document.getElementsByTagName("script")) != null && - (len = scriptNodes.getLength()) != 0) - { + (len = scriptNodes.getLength()) != 0) { for (int i = len - 1; i >= 0; i--) { try { Element scriptElement = (Element)scriptNodes.item(i); @@ -299,6 +303,7 @@ public class ParcelDescriptor { NodeList nl = scriptElement.getElementsByTagName("functionname"); + if (nl == null) { continue; } else { @@ -309,8 +314,7 @@ public class ParcelDescriptor { if (languagename.equals(script.getLanguageName())) { main.removeChild(scriptElement); } - } - catch (DOMException de) { + } catch (DOMException de) { // ignore } } @@ -332,10 +336,11 @@ public class ParcelDescriptor { tempitem = document.createElement("description"); String description = script.getDescription(); - if (description == null || description.length() == 0) - { + + if (description == null || description.length() == 0) { description = script.getLogicalName(); } + tempitem.appendChild(document.createTextNode(description)); item.appendChild(tempitem); @@ -354,6 +359,7 @@ public class ParcelDescriptor { item = document.createElement("languagedepprops"); Iterator<String> iter = languagedepprops.keySet().iterator(); + while (iter.hasNext()) { tempitem = document.createElement("prop"); key = iter.next(); @@ -361,6 +367,7 @@ public class ParcelDescriptor { tempitem.setAttribute("value", languagedepprops.get(key)); item.appendChild(tempitem); } + root.appendChild(item); } diff --git a/scripting/java/com/sun/star/script/framework/container/ParsedScriptUri.java b/scripting/java/com/sun/star/script/framework/container/ParsedScriptUri.java index 477604c721ac..65d6f4e68a28 100644 --- a/scripting/java/com/sun/star/script/framework/container/ParsedScriptUri.java +++ b/scripting/java/com/sun/star/script/framework/container/ParsedScriptUri.java @@ -17,8 +17,7 @@ */ package com.sun.star.script.framework.container; -public class ParsedScriptUri -{ +public class ParsedScriptUri { public String location; public String function; diff --git a/scripting/java/com/sun/star/script/framework/container/ScriptEntry.java b/scripting/java/com/sun/star/script/framework/container/ScriptEntry.java index b4d6a70e8e22..6f0ae24e9647 100644 --- a/scripting/java/com/sun/star/script/framework/container/ScriptEntry.java +++ b/scripting/java/com/sun/star/script/framework/container/ScriptEntry.java @@ -27,7 +27,7 @@ public class ScriptEntry implements Cloneable { private String logicalname = ""; private String description = ""; - private Map<String,String> languagedepprops; + private Map<String, String> languagedepprops; public ScriptEntry(String language, String languagename, String location) { @@ -39,11 +39,10 @@ public class ScriptEntry implements Cloneable { // as logical name also this.logicalname = languagename; this.location = location; - this.languagedepprops = new HashMap<String,String>(); + this.languagedepprops = new HashMap<String, String>(); } - public ScriptEntry(ScriptEntry entry) - { + public ScriptEntry(ScriptEntry entry) { this.language = entry.language; this.languagename = entry.languagename; this.logicalname = entry.languagename; @@ -53,15 +52,15 @@ public class ScriptEntry implements Cloneable { } public ScriptEntry(String language, String languagename, - String location, Map<String,String> languagedepprops) { - this( language, languagename, location ); + String location, Map<String, String> languagedepprops) { + this(language, languagename, location); this.languagedepprops = languagedepprops; } public ScriptEntry(String language, String languagename, - String location, Map<String,String> languagedepprops, + String location, Map<String, String> languagedepprops, String description) { - this( language, languagename, location ); + this(language, languagename, location); this.languagedepprops = languagedepprops; this.description = description; } @@ -77,14 +76,13 @@ public class ScriptEntry implements Cloneable { public boolean equals(ScriptEntry other) { return language.equals(other.getLanguage()) && - languagename.equals(other.getLanguageName()) && - logicalname.equals(other.getLogicalName()) && - languagedepprops.equals(other.getLanguageProperties()) && - location.equals(other.getLocation()); + languagename.equals(other.getLanguageName()) && + logicalname.equals(other.getLogicalName()) && + languagedepprops.equals(other.getLanguageProperties()) && + location.equals(other.getLocation()); } - public Map<String,String> getLanguageProperties() - { + public Map<String, String> getLanguageProperties() { return languagedepprops; } @@ -114,6 +112,7 @@ public class ScriptEntry implements Cloneable { @Override public String toString() { - return "\nLogicalName = " + logicalname + "\nLanguageName = " + languagename + "\nLocation = " + location + "\nLanguaguageProperties = " + languagedepprops; + return "\nLogicalName = " + logicalname + "\nLanguageName = " + languagename + + "\nLocation = " + location + "\nLanguaguageProperties = " + languagedepprops; } } diff --git a/scripting/java/com/sun/star/script/framework/container/ScriptMetaData.java b/scripting/java/com/sun/star/script/framework/container/ScriptMetaData.java index d55b226d83df..42d237d44ec5 100644 --- a/scripting/java/com/sun/star/script/framework/container/ScriptMetaData.java +++ b/scripting/java/com/sun/star/script/framework/container/ScriptMetaData.java @@ -42,49 +42,47 @@ public class ScriptMetaData extends ScriptEntry { private Parcel parent; - public ScriptMetaData( Parcel parent, ScriptEntry entry, - String source ) - { - super( entry ); + public ScriptMetaData(Parcel parent, ScriptEntry entry, + String source) { + super(entry); this.parent = parent; - if ( source != null ) - { + + if (source != null) { this.hasSource = true; this.source = source; } } - public boolean hasSource() - { + public boolean hasSource() { return hasSource; } public String getSource() { - return ( source !=null && hasSource ) ? source : null; + return (source != null && hasSource) ? source : null; } public byte[] getSourceBytes() { - return ( source !=null && hasSource ) ? source.getBytes() : null; + return (source != null && hasSource) ? source.getBytes() : null; } public boolean equals(ScriptMetaData other) { return super.equals(other) && hasSource == other.hasSource(); } - public String getScriptFullURL() - { - String url = "vnd.sun.star.script:" + parent.getName() + "." + getLanguageName() + - "?" + "language=" + getLanguage() + - "&location=" + getParcelLocation(); - return url; + public String getScriptFullURL() { + String url = "vnd.sun.star.script:" + parent.getName() + "." + getLanguageName() + + + "?" + "language=" + getLanguage() + + "&location=" + getParcelLocation(); + return url; } - public String getShortFormScriptURL() - { - String url = "vnd.sun.star.script:" + parent.getName() + "." + getLanguageName() + - "?" + "language=" + getLanguage() + - "&location=" + getLocationPlaceHolder(); + public String getShortFormScriptURL() { + String url = "vnd.sun.star.script:" + parent.getName() + "." + getLanguageName() + + + "?" + "language=" + getLanguage() + + "&location=" + getLocationPlaceHolder(); return url; } @@ -111,78 +109,60 @@ public class ScriptMetaData extends ScriptEntry { private static final String UNO_SHARED_PACKAGES2 = SHARE + "/uno_packages"; - public static String getLocationPlaceHolder(String url, String pkgname) - { + public static String getLocationPlaceHolder(String url, String pkgname) { String result = "Unknown"; - if ( url.contains(UNO_USER_PACKAGES1) || - url.contains(UNO_USER_PACKAGES2) ) - { - result = PathUtils.make_url( "user:uno_packages", pkgname ); - } - else if ( url.contains(UNO_SHARED_PACKAGES1) || - url.contains(UNO_SHARED_PACKAGES2) ) - { - result = PathUtils.make_url( "share:uno_packages", pkgname ); - } - else if ( url.indexOf(SHARE) == 0 ) - { + if (url.contains(UNO_USER_PACKAGES1) || + url.contains(UNO_USER_PACKAGES2)) { + result = PathUtils.make_url("user:uno_packages", pkgname); + } else if (url.contains(UNO_SHARED_PACKAGES1) || + url.contains(UNO_SHARED_PACKAGES2)) { + result = PathUtils.make_url("share:uno_packages", pkgname); + } else if (url.indexOf(SHARE) == 0) { result = "share"; - } - else if ( url.indexOf(USER) == 0 ) - { + } else if (url.indexOf(USER) == 0) { result = "user"; - } - else if ( url.indexOf("vnd.sun.star.tdoc:") == 0 ) - { + } else if (url.indexOf("vnd.sun.star.tdoc:") == 0) { result = "document"; } + return result; } - public String getLocationPlaceHolder() - { + public String getLocationPlaceHolder() { String placeHolder = "Unknown"; String pathToParcel = parent.getPathToParcel(); - if ( pathToParcel.contains(UNO_USER_PACKAGES1) || - pathToParcel.contains(UNO_USER_PACKAGES2) ) - { + if (pathToParcel.contains(UNO_USER_PACKAGES1) || + pathToParcel.contains(UNO_USER_PACKAGES2)) { // it's a package placeHolder = "user:uno_packages"; String unoPkg = parent.parent.getName(); - if ( unoPkg != null ) - { - placeHolder = PathUtils.make_url( placeHolder, unoPkg ); + + if (unoPkg != null) { + placeHolder = PathUtils.make_url(placeHolder, unoPkg); } - } - else if ( pathToParcel.contains(UNO_SHARED_PACKAGES1) || - pathToParcel.contains(UNO_SHARED_PACKAGES2) ) - { + } else if (pathToParcel.contains(UNO_SHARED_PACKAGES1) || + pathToParcel.contains(UNO_SHARED_PACKAGES2)) { //its a package placeHolder = "share:uno_packages"; String unoPkg = parent.parent.getName(); - if ( unoPkg != null ) - { - placeHolder = PathUtils.make_url( placeHolder, unoPkg ); + + if (unoPkg != null) { + placeHolder = PathUtils.make_url(placeHolder, unoPkg); } - } - else if ( pathToParcel.indexOf(SHARE) == 0 ) - { + } else if (pathToParcel.indexOf(SHARE) == 0) { placeHolder = "share"; - } - else if ( pathToParcel.indexOf(USER) == 0 ) - { + } else if (pathToParcel.indexOf(USER) == 0) { placeHolder = "user"; - } - else if ( pathToParcel.indexOf("vnd.sun.star.tdoc:") == 0 ) - { + } else if (pathToParcel.indexOf("vnd.sun.star.tdoc:") == 0) { placeHolder = "document"; } + // TODO handling document packages ??? not really sure of package url -/* else - { - } */ + /* else + { + } */ return placeHolder; } @@ -193,76 +173,69 @@ public class ScriptMetaData extends ScriptEntry { // Also if it is to remain needs to be renamed to getParcelLocationURL // return URL string to parcel - public String getParcelLocation() - { + public String getParcelLocation() { return parent.getPathToParcel(); } @Override - public String toString() - { - return "\nParcelLocation = " + getParcelLocation() + "\nLocationPlaceHolder = " + locationPlaceHolder + super.toString(); + public String toString() { + return "\nParcelLocation = " + getParcelLocation() + "\nLocationPlaceHolder = " + + locationPlaceHolder + super.toString(); } - public URL[] getClassPath() - { - try - { - String classpath = getLanguageProperties().get("classpath"); + public URL[] getClassPath() { + try { + String classpath = getLanguageProperties().get("classpath"); - if ( classpath == null ) - { - classpath = ""; - } + if (classpath == null) { + classpath = ""; + } - String parcelPath = getParcelLocation(); - // make sure path ends with / - if ( !parcelPath.endsWith("/") ) - { - parcelPath += "/"; - } + String parcelPath = getParcelLocation(); + + // make sure path ends with / + if (!parcelPath.endsWith("/")) { + parcelPath += "/"; + } - // replace \ with / - parcelPath = parcelPath.replace( '\\', '/' ); + // replace \ with / + parcelPath = parcelPath.replace('\\', '/'); + + ArrayList<URL> classPathVec = new ArrayList<URL>(); + StringTokenizer stk = new StringTokenizer(classpath, ":"); + + while (stk.hasMoreElements()) { + String relativeClasspath = stk.nextToken(); + String pathToProcess = PathUtils.make_url(parcelPath, relativeClasspath); + URL url = createURL(pathToProcess); + + if (url != null) { + classPathVec.add(url); + } - ArrayList<URL> classPathVec = new ArrayList<URL>(); - StringTokenizer stk = new StringTokenizer(classpath, ":"); - while ( stk.hasMoreElements() ) - { - String relativeClasspath = stk.nextToken(); - String pathToProcess = PathUtils.make_url( parcelPath, relativeClasspath); - URL url = createURL( pathToProcess ); - if ( url != null ) - { - classPathVec.add ( url ); } - } - if ( classPathVec.size() == 0) - { - URL url = createURL( parcelPath ); - if ( url != null ) - { - classPathVec.add(url); + if (classPathVec.size() == 0) { + URL url = createURL(parcelPath); + + if (url != null) { + classPathVec.add(url); + } } - } - return classPathVec.toArray( new URL[classPathVec.size()]); - } - catch ( Exception e ) - { - LogUtils.DEBUG("Failed to build class path " + e.toString() ); - LogUtils.DEBUG( LogUtils.getTrace( e ) ); - return new URL[0]; - } + return classPathVec.toArray(new URL[classPathVec.size()]); + } catch (Exception e) { + LogUtils.DEBUG("Failed to build class path " + e.toString()); + LogUtils.DEBUG(LogUtils.getTrace(e)); + return new URL[0]; + } } - private URL createURL( String path ) throws java.net.MalformedURLException - { + private URL createURL(String path) throws java.net.MalformedURLException { int indexOfColon = path.indexOf(':'); - String scheme = path.substring( 0, indexOfColon ); - UCBStreamHandler handler = new UCBStreamHandler( scheme, parent.m_xSFA); + String scheme = path.substring(0, indexOfColon); + UCBStreamHandler handler = new UCBStreamHandler(scheme, parent.m_xSFA); path += UCBStreamHandler.separator; return new URL(null, path, handler); @@ -270,87 +243,81 @@ public class ScriptMetaData extends ScriptEntry { // TODO should decide whether this should throw or not // decide whether it should be public or protected ( final ? ) - public void loadSource() - { - try - { - URL sourceUrl = getSourceURL(); - LogUtils.DEBUG("** In load source BUT not loading yet for " + sourceUrl ); - - if ( sourceUrl != null ) - { - StringBuilder buf = new StringBuilder(); - InputStream in = sourceUrl.openStream(); - - byte[] contents = new byte[1024]; - int len; - while ((len = in.read(contents, 0, 1024)) != -1) { - buf.append(new String(contents, 0, len)); - } - - try { - in.close(); - } - catch (java.io.IOException ignore ) { - LogUtils.DEBUG("** Failed to read scriot from url " + ignore.toString() ); - } - - source = buf.toString(); - hasSource = true; + public void loadSource() { + try { + URL sourceUrl = getSourceURL(); + LogUtils.DEBUG("** In load source BUT not loading yet for " + sourceUrl); + + if (sourceUrl != null) { + StringBuilder buf = new StringBuilder(); + InputStream in = sourceUrl.openStream(); + + byte[] contents = new byte[1024]; + int len; + + while ((len = in.read(contents, 0, 1024)) != -1) { + buf.append(new String(contents, 0, len)); + } + + try { + in.close(); + } catch (java.io.IOException ignore) { + LogUtils.DEBUG("** Failed to read scriot from url " + ignore.toString()); } - } - catch (java.io.IOException e) { - LogUtils.DEBUG("** Failed to read scriot from url " + e.toString()); - } + source = buf.toString(); + hasSource = true; + } + } catch (java.io.IOException e) { + LogUtils.DEBUG("** Failed to read scriot from url " + e.toString()); } - protected boolean writeSourceFile() - { + + } + protected boolean writeSourceFile() { String sourceFilePath = parent.getPathToParcel() + "/" + getLanguageName(); boolean result = false; - try - { - XSimpleFileAccess2 xSFA2 = UnoRuntime.queryInterface( XSimpleFileAccess2.class, - parent.m_xSFA ); - if ( xSFA2 != null ) - { - ByteArrayInputStream bis = new ByteArrayInputStream( getSourceBytes() ); - XInputStreamImpl xis = new XInputStreamImpl( bis ); - xSFA2.writeFile( sourceFilePath, xis ); + + try { + XSimpleFileAccess2 xSFA2 = UnoRuntime.queryInterface(XSimpleFileAccess2.class, + parent.m_xSFA); + + if (xSFA2 != null) { + ByteArrayInputStream bis = new ByteArrayInputStream(getSourceBytes()); + XInputStreamImpl xis = new XInputStreamImpl(bis); + xSFA2.writeFile(sourceFilePath, xis); xis.closeInput(); result = true; } } // TODO re-examine exception processing should probably throw // exceptions back to caller - catch ( Exception ignore ) + catch (Exception ignore) { } + return result; } - protected boolean removeSourceFile() - { + protected boolean removeSourceFile() { String parcelLocation = parent.getPathToParcel(); String sourceFilePath = parcelLocation + "/" + getLanguageName(); boolean result = false; - try - { - parent.m_xSFA.kill( sourceFilePath ); + + try { + parent.m_xSFA.kill(sourceFilePath); result = true; } // TODO reexamine exception handling - catch ( Exception e ) - { + catch (Exception e) { } + return result; } - public URL getSourceURL() throws java.net.MalformedURLException - { + public URL getSourceURL() throws java.net.MalformedURLException { String sUrl = getParcelLocation(); - sUrl = PathUtils.make_url( sUrl, getLanguageName() ); - LogUtils.DEBUG("Creating script url for " + sUrl ); - return createURL( sUrl ); + sUrl = PathUtils.make_url(sUrl, getLanguageName()); + LogUtils.DEBUG("Creating script url for " + sUrl); + return createURL(sUrl); } } diff --git a/scripting/java/com/sun/star/script/framework/container/UnoPkgContainer.java b/scripting/java/com/sun/star/script/framework/container/UnoPkgContainer.java index be9dd42db9f1..9a338e06e35f 100644 --- a/scripting/java/com/sun/star/script/framework/container/UnoPkgContainer.java +++ b/scripting/java/com/sun/star/script/framework/container/UnoPkgContainer.java @@ -33,136 +33,128 @@ import com.sun.star.io.XOutputStream; import com.sun.star.io.XTruncate; import com.sun.star.deployment.XPackage; -public class UnoPkgContainer extends ParcelContainer -{ +public class UnoPkgContainer extends ParcelContainer { - private Map<String,ParcelContainer> registeredPackages = new HashMap<String,ParcelContainer>(); + private Map<String, ParcelContainer> registeredPackages = new + HashMap<String, ParcelContainer>(); private String extensionDb; private String extensionRepository; - public UnoPkgContainer( XComponentContext xCtx, String locationURL, - String _extensionDb, String _extensionRepository, String language ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException - { - super( xCtx, locationURL, language, false ); + public UnoPkgContainer(XComponentContext xCtx, String locationURL, + String _extensionDb, String _extensionRepository, + String language) throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.lang.WrappedTargetException { + super(xCtx, locationURL, language, false); extensionDb = _extensionDb; extensionRepository = _extensionRepository; init(); } // gets the ParcelContainer for persisted uno packages - public ParcelContainer getRegisteredUnoPkgContainer( String url ) - { - if (!url.endsWith("/")) - { + public ParcelContainer getRegisteredUnoPkgContainer(String url) { + if (!url.endsWith("/")) { url += "/"; } - LogUtils.DEBUG("** getRegisterPackage ctx = " + containerUrl ); - LogUtils.DEBUG("** getRegisterPackage for uri " + url ); - LogUtils.DEBUG("** getRegisterPackage for langugage " + language ); - ParcelContainer result = registeredPackages.get( url ); - LogUtils.DEBUG("getRegisterPackage result is " + result ); + LogUtils.DEBUG("** getRegisterPackage ctx = " + containerUrl); + LogUtils.DEBUG("** getRegisterPackage for uri " + url); + LogUtils.DEBUG("** getRegisterPackage for langugage " + language); + ParcelContainer result = registeredPackages.get(url); + LogUtils.DEBUG("getRegisterPackage result is " + result); return result; } - public boolean hasRegisteredUnoPkgContainer( String url ) { - return getRegisteredUnoPkgContainer( url ) != null; + public boolean hasRegisteredUnoPkgContainer(String url) { + return getRegisteredUnoPkgContainer(url) != null; } - private void registerPackageContainer( String url, ParcelContainer c ) - { - if (!url.endsWith("/")) - { + private void registerPackageContainer(String url, ParcelContainer c) { + if (!url.endsWith("/")) { url += "/"; } - LogUtils.DEBUG("RegisterPackage ctx = " + containerUrl ); - LogUtils.DEBUG("RegisterPackage language = " + language ); - LogUtils.DEBUG("RegisterPackage " + c + " for url " + url ); - registeredPackages.put( url, c ); + LogUtils.DEBUG("RegisterPackage ctx = " + containerUrl); + LogUtils.DEBUG("RegisterPackage language = " + language); + LogUtils.DEBUG("RegisterPackage " + c + " for url " + url); + registeredPackages.put(url, c); } - public void deRegisterPackageContainer( String url ) - { - if (!url.endsWith("/")) - { + public void deRegisterPackageContainer(String url) { + if (!url.endsWith("/")) { url += "/"; } - LogUtils.DEBUG("In deRegisterPackageContainer for " + url ); - if ( hasRegisteredUnoPkgContainer( url ) ) - { - try - { + LogUtils.DEBUG("In deRegisterPackageContainer for " + url); + + if (hasRegisteredUnoPkgContainer(url)) { + try { DeployedUnoPackagesDB db = getUnoPackagesDB(); - if ( db != null ) - { - if ( db.removePackage( language, url ) ) - { - writeUnoPackageDB( db ); - ParcelContainer container = registeredPackages.get( url ); - if ( !container.hasElements() ) - { - // When all libraries within a package bundle - // ( for this language ) are removed also - // remove the container from its parent - // Otherwise, a container ( with no containees ) - // representing the uno package bundle will - // still exist and so will get displayed - if ( container.parent() != null ) - { - container.parent().removeChildContainer( container ); - } - } - registeredPackages.remove( url ); - } - } - } - catch (Exception e) - { - //TODO revisit exception handling and exception here - //means something very wrong - LogUtils.DEBUG("***** deRegisterPackageContainer() got exception " + e ); - } + + if (db != null) { + if (db.removePackage(language, url)) { + writeUnoPackageDB(db); + ParcelContainer container = registeredPackages.get(url); + + if (!container.hasElements()) { + // When all libraries within a package bundle + // ( for this language ) are removed also + // remove the container from its parent + // Otherwise, a container ( with no containees ) + // representing the uno package bundle will + // still exist and so will get displayed + if (container.parent() != null) { + container.parent().removeChildContainer(container); + } + } + + registeredPackages.remove(url); + } + } + } catch (Exception e) { + //TODO revisit exception handling and exception here + //means something very wrong + LogUtils.DEBUG("***** deRegisterPackageContainer() got exception " + e); + } } - LogUtils.DEBUG("Leaving deRegisterPackageContainer for " + url ); + + LogUtils.DEBUG("Leaving deRegisterPackageContainer for " + url); } - private void init() throws com.sun.star.lang.IllegalArgumentException - { - LogUtils.DEBUG("getting container for " + containerUrl ); - try - { + private void init() throws com.sun.star.lang.IllegalArgumentException { + LogUtils.DEBUG("getting container for " + containerUrl); + + try { DeployedUnoPackagesDB db = getUnoPackagesDB(); - if ( db != null ) - { - String[] packages = db.getDeployedPackages( language ); + + if (db != null) { + String[] packages = db.getDeployedPackages(language); + for (String thepackage : packages) { try { processUnoPackage(thepackage, language); } catch (com.sun.star.lang.IllegalArgumentException ila) { LogUtils.DEBUG("Failed to process " + thepackage + " for " + language); - LogUtils.DEBUG(" Reason: " + ila ); + LogUtils.DEBUG(" Reason: " + ila); } catch (Exception e) { // TODO proper exception or do we wish // to ignore errors here LogUtils.DEBUG("Something very wrong!!!!!"); LogUtils.DEBUG("Failed to process " + thepackage + " for " + language); - LogUtils.DEBUG(" Reason: " + e ); + LogUtils.DEBUG(" Reason: " + e); } } } - } - catch ( com.sun.star.lang.WrappedTargetException e ) - { + } catch (com.sun.star.lang.WrappedTargetException e) { // no deployed packages - LogUtils.DEBUG("No deployed uno-packages for " + containerUrl ); + LogUtils.DEBUG("No deployed uno-packages for " + containerUrl); } } @Override - public ScriptMetaData findScript( ParsedScriptUri psu ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException + public ScriptMetaData findScript(ParsedScriptUri psu) throws + com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { ScriptMetaData scriptData = null; @@ -172,70 +164,59 @@ public class UnoPkgContainer extends ParcelContainer String location = psu.location; LogUtils.DEBUG("*** UnoPkgContainer.findScript() ***" + - "\ncontainerUrl = " + containerUrl + - "\nfunction = " + functionName + - "\nlocation = " + location + - "\nparcel = " + parcelName ); + "\ncontainerUrl = " + containerUrl + + "\nfunction = " + functionName + + "\nlocation = " + location + + "\nparcel = " + parcelName); - ParcelContainer pc = getChildContainer( location ); + ParcelContainer pc = getChildContainer(location); - if ( pc == null ) - { - throw new com.sun.star.lang.WrappedTargetException( "Failed to resolve script " , null, new com.sun.star.lang.IllegalArgumentException( "Cannot resolve script location for script = " + functionName ) ); + if (pc == null) { + throw new com.sun.star.lang.WrappedTargetException("Failed to resolve script " , + null, new com.sun.star.lang.IllegalArgumentException("Cannot resolve script location for script = " + + functionName)); } - return pc.findScript( psu ); + return pc.findScript(psu); } - private DeployedUnoPackagesDB getUnoPackagesDB() throws com.sun.star.lang.WrappedTargetException - { + private DeployedUnoPackagesDB getUnoPackagesDB() throws + com.sun.star.lang.WrappedTargetException { InputStream is = null; DeployedUnoPackagesDB dp = null; - try - { - String packagesUrl = PathUtils.make_url( extensionDb, "/Scripts/" + extensionRepository + "-extension-desc.xml" ); - LogUtils.DEBUG("getUnoPackagesDB() looking for existing db in " + packagesUrl ); - if ( m_xSFA.exists( packagesUrl ) ) - { - if ( packagesUrl.startsWith( "vnd.sun.star.tdoc" ) ) - { + + try { + String packagesUrl = PathUtils.make_url(extensionDb, + "/Scripts/" + extensionRepository + "-extension-desc.xml"); + LogUtils.DEBUG("getUnoPackagesDB() looking for existing db in " + packagesUrl); + + if (m_xSFA.exists(packagesUrl)) { + if (packagesUrl.startsWith("vnd.sun.star.tdoc")) { // handles using XStorage directly throw new com.sun.star.lang.WrappedTargetException("Can't handle documents yet"); } - is = new XInputStreamWrapper( m_xSFA.openFileRead( packagesUrl ) ); - dp = new DeployedUnoPackagesDB( is ); - try - { + is = new XInputStreamWrapper(m_xSFA.openFileRead(packagesUrl)); + dp = new DeployedUnoPackagesDB(is); + + try { is.close(); is = null; + } catch (Exception ignore) { } - catch ( Exception ignore ) - { - } - } - else - { + } else { LogUtils.DEBUG("getUnoPackagesDB() " + packagesUrl + " does not exist"); } - } - catch( Exception e ) - { - LogUtils.DEBUG("getUnoPackagesDB() caught Exception: " + e ); - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + } catch (Exception e) { + LogUtils.DEBUG("getUnoPackagesDB() caught Exception: " + e); + LogUtils.DEBUG(LogUtils.getTrace(e)); throw new com.sun.star.lang.WrappedTargetException(e); - } - finally - { - if ( is != null ) - { - try - { + } finally { + if (is != null) { + try { is.close(); is = null; - } - catch ( Exception ignore ) - { + } catch (Exception ignore) { } } } @@ -243,160 +224,151 @@ public class UnoPkgContainer extends ParcelContainer return dp; } - private void writeUnoPackageDB( DeployedUnoPackagesDB dp ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException - { + private void writeUnoPackageDB(DeployedUnoPackagesDB dp) throws + com.sun.star.lang.IllegalArgumentException, + com.sun.star.lang.WrappedTargetException { LogUtils.DEBUG("In writeUnoPackageDB() "); XOutputStream xos = null; OutputStream os = null; - try - { - String packagesUrl = PathUtils.make_url( extensionDb, "/Scripts/" + extensionRepository + "-extension-desc.xml" ); - xos = m_xSFA.openFileWrite( packagesUrl ); - XTruncate xTrc = UnoRuntime.queryInterface( XTruncate.class, xos ); - if ( xTrc != null ) - { - LogUtils.DEBUG("In writeUnoPackageDB() Truncating...." ); + + try { + String packagesUrl = PathUtils.make_url(extensionDb, + "/Scripts/" + extensionRepository + "-extension-desc.xml"); + xos = m_xSFA.openFileWrite(packagesUrl); + XTruncate xTrc = UnoRuntime.queryInterface(XTruncate.class, xos); + + if (xTrc != null) { + LogUtils.DEBUG("In writeUnoPackageDB() Truncating...."); xTrc.truncate(); + } else { + LogUtils.DEBUG("In writeUnoPackageDB() CAN'T Truncate...."); } - else - { - LogUtils.DEBUG("In writeUnoPackageDB() CAN'T Truncate...." ); - } - os = new XOutputStreamWrapper( xos ); - dp.write( os ); - try - { + + os = new XOutputStreamWrapper(xos); + dp.write(os); + + try { os.close(); // will close xos os = null; + } catch (Exception ignore) { } - catch( Exception ignore ) - { - } - } - catch( Exception e ) - { - LogUtils.DEBUG("In writeUnoPackageDB() Exception: " + e ); + } catch (Exception e) { + LogUtils.DEBUG("In writeUnoPackageDB() Exception: " + e); throw new com.sun.star.lang.WrappedTargetException(e); - } - finally - { - if ( os != null ) - { - try - { + } finally { + if (os != null) { + try { os.close(); // will close xos os = null; - } - catch ( Exception ignore ) - { + } catch (Exception ignore) { } } } } - public void processUnoPackage( XPackage dPackage, String language ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException, com.sun.star.container.ElementExistException - { - LogUtils.DEBUG("** in processUnoPackage " ); + public void processUnoPackage(XPackage dPackage, + String language) throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.lang.WrappedTargetException, + com.sun.star.container.ElementExistException { + LogUtils.DEBUG("** in processUnoPackage "); String uri = dPackage.getURL(); - if ( !uri.endsWith( "/" ) ) - { + if (!uri.endsWith("/")) { uri += "/"; } - LogUtils.DEBUG("** processUnoPackage getURL() -> " + uri ); - LogUtils.DEBUG("** processUnoPackage getName() -> " + dPackage.getName() ); - LogUtils.DEBUG("** processUnoPackage getMediaType() -> " + dPackage.getPackageType().getMediaType() ); - try - { - LogUtils.DEBUG("** processUnoPackage getDisplayName() -> " + dPackage.getDisplayName() ); - } - catch (com.sun.star.deployment.ExtensionRemovedException e) - { + LogUtils.DEBUG("** processUnoPackage getURL() -> " + uri); + LogUtils.DEBUG("** processUnoPackage getName() -> " + dPackage.getName()); + LogUtils.DEBUG("** processUnoPackage getMediaType() -> " + + dPackage.getPackageType().getMediaType()); + + try { + LogUtils.DEBUG("** processUnoPackage getDisplayName() -> " + + dPackage.getDisplayName()); + } catch (com.sun.star.deployment.ExtensionRemovedException e) { throw new com.sun.star.lang.WrappedTargetException(e.getMessage(), this, e); } - processUnoPackage( uri, language ); + processUnoPackage(uri, language); DeployedUnoPackagesDB db = getUnoPackagesDB(); - if ( db == null ) - { - try - { + + if (db == null) { + try { db = new DeployedUnoPackagesDB(); - } - catch ( java.io.IOException ioe ) - { + } catch (java.io.IOException ioe) { throw new com.sun.star.lang.WrappedTargetException(ioe); } } - db.addPackage( language, uri ); - writeUnoPackageDB( db ); + + db.addPackage(language, uri); + writeUnoPackageDB(db); } - private void processUnoPackage( String uri, String language ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException, com.sun.star.container.ElementExistException - { - if ( hasRegisteredUnoPkgContainer( uri ) ) - { - throw new com.sun.star.container.ElementExistException( "Already a registered uno package " + uri + " for language " + language ); + private void processUnoPackage(String uri, + String language) throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.lang.WrappedTargetException, + com.sun.star.container.ElementExistException { + if (hasRegisteredUnoPkgContainer(uri)) { + throw new com.sun.star.container.ElementExistException("Already a registered uno package " + + uri + " for language " + language); } - LogUtils.DEBUG("processUnoPackage - URL = " + uri ); + + LogUtils.DEBUG("processUnoPackage - URL = " + uri); LogUtils.DEBUG("processUnoPackage - script library package"); String parentUrl = uri; - if ( uri.contains("%2Funo_packages%2F") || - uri.contains("/uno_packages/") || - uri.contains("$UNO_USER_PACKAGES_CACHE/") || - uri.contains("$UNO_SHARED_PACKAGES_CACHE/") || - uri.contains("$BUNDLED_EXTENSIONS/") ) - { + if (uri.contains("%2Funo_packages%2F") || + uri.contains("/uno_packages/") || + uri.contains("$UNO_USER_PACKAGES_CACHE/") || + uri.contains("$UNO_SHARED_PACKAGES_CACHE/") || + uri.contains("$BUNDLED_EXTENSIONS/")) { //its in a bundle need to determine the uno-package file its in LogUtils.DEBUG("processUnoPackage - is part of a uno bundle"); int index = uri.lastIndexOf('/'); - if ( uri.endsWith("/") ) - { - uri = uri.substring( 0, index ); + + if (uri.endsWith("/")) { + uri = uri.substring(0, index); index = uri.lastIndexOf('/'); } - if ( index > -1 ) - { - parentUrl = uri.substring( 0, index ); + if (index > -1) { + parentUrl = uri.substring(0, index); LogUtils.DEBUG("processUnoPackage - composition is contained in " + parentUrl); } - ParcelContainer pkgContainer = getChildContainerForURL( parentUrl ); - if ( pkgContainer == null ) - { - pkgContainer = new ParcelContainer( this, m_xCtx, parentUrl, language, false ); - if ( pkgContainer.loadParcel( uri ) == null ) - { - throw new com.sun.star.lang.IllegalArgumentException( "Couldn't load script library from composition package " + uri + " for language " + language ); + ParcelContainer pkgContainer = getChildContainerForURL(parentUrl); + + if (pkgContainer == null) { + pkgContainer = new ParcelContainer(this, m_xCtx, parentUrl, language, false); + + if (pkgContainer.loadParcel(uri) == null) { + throw new com.sun.star.lang.IllegalArgumentException("Couldn't load script library from composition package " + + uri + " for language " + language); } - addChildContainer( pkgContainer ); - } - else - { - if ( pkgContainer.loadParcel( uri ) == null ) - { - throw new com.sun.star.lang.IllegalArgumentException( "Couldn't load script library from composition package " + uri + " for language " + language ); + + addChildContainer(pkgContainer); + } else { + if (pkgContainer.loadParcel(uri) == null) { + throw new com.sun.star.lang.IllegalArgumentException("Couldn't load script library from composition package " + + uri + " for language " + language); } } - registerPackageContainer( uri, pkgContainer ); - } - else - { + + registerPackageContainer(uri, pkgContainer); + } else { // stand-alone library package, e.g. not contained in // an uno package - if ( loadParcel( uri ) == null ) - { - throw new com.sun.star.lang.IllegalArgumentException( "Couldn't load script library package " + uri + " for language " + language ); + if (loadParcel(uri) == null) { + throw new com.sun.star.lang.IllegalArgumentException("Couldn't load script library package " + + uri + " for language " + language); } - registerPackageContainer( uri, this ); + + registerPackageContainer(uri, this); } } diff --git a/scripting/java/com/sun/star/script/framework/container/XMLParserFactory.java b/scripting/java/com/sun/star/script/framework/container/XMLParserFactory.java index 00d39a6c3332..9e17b2c68822 100644 --- a/scripting/java/com/sun/star/script/framework/container/XMLParserFactory.java +++ b/scripting/java/com/sun/star/script/framework/container/XMLParserFactory.java @@ -39,6 +39,7 @@ public class XMLParserFactory { public static synchronized XMLParser getParser() { if (parser == null) parser = new DefaultParser(); + return parser; } @@ -69,16 +70,14 @@ public class XMLParserFactory { } result = builder.parse(is); - } - catch (SAXParseException spe) { + } catch (SAXParseException spe) { throw new IOException(spe.getMessage()); - } - catch (SAXException se) { + } catch (SAXException se) { throw new IOException(se.getMessage()); - } - catch (ParserConfigurationException pce) { + } catch (ParserConfigurationException pce) { throw new IOException(pce.getMessage()); } + return result; } @@ -97,10 +96,9 @@ public class XMLParserFactory { // these DOM implementations are self writing Method write; write = clazz.getDeclaredMethod("write", - new Class[] {OutputStream.class}); + new Class[] {OutputStream.class}); write.invoke(doc, new Object[] {out}); - } - else { + } else { // try xerces serialize package using introspection ClassLoader cl = this.getClass().getClassLoader(); @@ -109,16 +107,16 @@ public class XMLParserFactory { try { serializerClass = Class.forName( - "org.apache.xml.serialize.XMLSerializer", true, cl); + "org.apache.xml.serialize.XMLSerializer", true, cl); formatterClass = Class.forName( - "org.apache.xml.serialize.OutputFormat", true, cl); + "org.apache.xml.serialize.OutputFormat", true, cl); } catch (ClassNotFoundException cnfe) { String prefix = "com.sun.org.apache.xml.internal."; serializerClass = Class.forName( - prefix + "serialize.XMLSerializer" , true, cl); + prefix + "serialize.XMLSerializer" , true, cl); formatterClass = Class.forName( - prefix + "serialize.OutputFormat", true, cl); + prefix + "serialize.OutputFormat", true, cl); } Object serializerObject = serializerClass.newInstance(); @@ -126,29 +124,29 @@ public class XMLParserFactory { // improve output readability using the OutputFormat class Method method = formatterClass.getMethod("setMethod", - new Class[] {String.class}); + new Class[] {String.class}); method.invoke(formatterObject, new Object[] {"xml"}); method = formatterClass.getMethod("setIndenting", - new Class[] {Boolean.TYPE}); + new Class[] {Boolean.TYPE}); method.invoke(formatterObject, new Object[] {Boolean.TRUE}); // now set up an instance of XMLSerializer with our // OutputStream and serialize our Document method = serializerClass.getMethod("setOutputByteStream", - new Class[] {OutputStream.class}); + new Class[] {OutputStream.class}); method.invoke(serializerObject, new Object[] {out}); method = serializerClass.getMethod("setOutputFormat", - new Class[] {formatterClass}); + new Class[] {formatterClass}); method.invoke(serializerObject, - new Object[] {formatterObject}); + new Object[] {formatterObject}); method = serializerClass.getMethod("asDOMSerializer", - new Class[0]); + new Class[0]); Object impl = method.invoke(serializerObject, - new Object[0]); + new Object[0]); method = impl.getClass().getMethod("serialize", - new Class[] {Document.class}); + new Class[] {Document.class}); method.invoke(impl, new Object[] {doc}); } } catch (NoSuchMethodException ex) { diff --git a/scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java b/scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java index 33bb67419eea..e4a715060d73 100644 --- a/scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java +++ b/scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java @@ -36,28 +36,30 @@ public class UCBStreamHandler extends URLStreamHandler { public final static String separator = "/ucb/"; private XSimpleFileAccess m_xSimpleFileAccess = null; - private HashMap<String,InputStream> m_jarStreamMap = new HashMap<String,InputStream>(12); + private HashMap<String, InputStream> m_jarStreamMap = new + HashMap<String, InputStream>(12); private static String m_ucbscheme; - public UCBStreamHandler( String scheme, XSimpleFileAccess xSFA ) - { - LogUtils.DEBUG( "UCBStreamHandler ctor, scheme = " + scheme ); + public UCBStreamHandler(String scheme, XSimpleFileAccess xSFA) { + LogUtils.DEBUG("UCBStreamHandler ctor, scheme = " + scheme); UCBStreamHandler.m_ucbscheme = scheme; this.m_xSimpleFileAccess = xSFA; } @Override public void parseURL(URL url, String spec, int start, int limit) { - LogUtils.DEBUG("**XUCBStreamHandler, parseURL: " + url + " spec: " + spec + " start: " + start + " limit: " + limit ); + LogUtils.DEBUG("**XUCBStreamHandler, parseURL: " + url + " spec: " + spec + + " start: " + start + " limit: " + limit); String file = url.getFile(); + if (file == null) file = spec.substring(start, limit); else file += spec.substring(start, limit); - LogUtils.DEBUG("**For scheme = " + m_ucbscheme ); - LogUtils.DEBUG("**Setting path = " + file ); + LogUtils.DEBUG("**For scheme = " + m_ucbscheme); + LogUtils.DEBUG("**Setting path = " + file); setURL(url, m_ucbscheme, null, -1, null, null, file, null, null); } @@ -78,73 +80,73 @@ public class UCBStreamHandler extends URLStreamHandler { @Override public InputStream getInputStream() throws IOException { - LogUtils.DEBUG("UCBConnectionHandler GetInputStream on " + url ); + LogUtils.DEBUG("UCBConnectionHandler GetInputStream on " + url); String sUrl = url.toString(); + if (sUrl.lastIndexOf(separator) == -1) { - LogUtils.DEBUG("getInputStream straight file load" ); + LogUtils.DEBUG("getInputStream straight file load"); return getFileStreamFromUCB(sUrl); - } - else { - String path = sUrl.substring(0, sUrl.lastIndexOf(separator) ); + } else { + String path = sUrl.substring(0, sUrl.lastIndexOf(separator)); String file = sUrl.substring( - sUrl.lastIndexOf(separator) + separator.length()); - LogUtils.DEBUG("getInputStream, load of file from another file eg. " + file + " from " + path ); + sUrl.lastIndexOf(separator) + separator.length()); + LogUtils.DEBUG("getInputStream, load of file from another file eg. " + file + + " from " + path); return getUCBStream(file, path); } } @Override public OutputStream getOutputStream() throws IOException { - LogUtils.DEBUG("UCBConnectionHandler getOutputStream on " + url ); + LogUtils.DEBUG("UCBConnectionHandler getOutputStream on " + url); OutputStream os = null; - try - { + + try { String sUrl = url.toString(); - if ( !( sUrl.lastIndexOf(separator) == -1) ) { + + if (!(sUrl.lastIndexOf(separator) == -1)) { String path = sUrl.substring(0, sUrl.lastIndexOf(separator)); - if ( m_xSimpleFileAccess.isReadOnly( path ) ) - { + if (m_xSimpleFileAccess.isReadOnly(path)) { throw new java.io.IOException("File is read only"); } - LogUtils.DEBUG("getOutputStream, create o/p stream for file eg. " + path ); + LogUtils.DEBUG("getOutputStream, create o/p stream for file eg. " + path); // we will only deal with simple file write - XOutputStream xos = m_xSimpleFileAccess.openFileWrite( path ); - XTruncate xtrunc = UnoRuntime.queryInterface( XTruncate.class, xos ); - if ( xtrunc != null ) - { + XOutputStream xos = m_xSimpleFileAccess.openFileWrite(path); + XTruncate xtrunc = UnoRuntime.queryInterface(XTruncate.class, xos); + + if (xtrunc != null) { xtrunc.truncate(); } - os = new XOutputStreamWrapper( xos ); + + os = new XOutputStreamWrapper(xos); } - if ( os == null ) - { - throw new IOException("Failed to get OutputStream for " + sUrl ); + + if (os == null) { + throw new IOException("Failed to get OutputStream for " + sUrl); } - } - catch ( com.sun.star.ucb.CommandAbortedException cae ) - { - LogUtils.DEBUG("caught exception: " + cae.toString() + " getting writable stream from " + url ); + } catch (com.sun.star.ucb.CommandAbortedException cae) { + LogUtils.DEBUG("caught exception: " + cae.toString() + + " getting writable stream from " + url); IOException newEx = new IOException(cae.getMessage()); newEx.initCause(cae); throw newEx; - } - catch ( com.sun.star.uno.Exception e ) - { - LogUtils.DEBUG("caught unknown exception: " + e.toString() + " getting writable stream from " + url ); + } catch (com.sun.star.uno.Exception e) { + LogUtils.DEBUG("caught unknown exception: " + e.toString() + + " getting writable stream from " + url); IOException newEx = new IOException(e.getMessage()); newEx.initCause(e); throw newEx; } + return os; } } private InputStream getUCBStream(String file, String path) - throws IOException - { + throws IOException { InputStream is = null; InputStream result = null; @@ -155,42 +157,37 @@ public class UCBStreamHandler extends URLStreamHandler { if (is == null) { is = getFileStreamFromUCB(path); m_jarStreamMap.put(path, is); - } - else { + } else { try { is.reset(); - } - catch (IOException e) { + } catch (IOException e) { is.close(); is = getFileStreamFromUCB(path); m_jarStreamMap.put(path, is); } } + result = getFileStreamFromJarStream(file, is); - } - else - { - String fileUrl = PathUtils.make_url(path,file); + } else { + String fileUrl = PathUtils.make_url(path, file); result = getFileStreamFromUCB(fileUrl); } - } - finally { + } finally { if (is != null) { try { is.close(); - } - catch (IOException ioe) { + } catch (IOException ioe) { LogUtils.DEBUG("Caught exception closing stream: " + - ioe.getMessage()); + ioe.getMessage()); } } } + return result; } private InputStream getFileStreamFromJarStream(String file, InputStream is) - throws IOException - { + throws IOException { ZipEntry entry; ZipInputStream zis = new ZipInputStream(is); @@ -202,33 +199,33 @@ public class UCBStreamHandler extends URLStreamHandler { return zis; } } + return null; } private InputStream getFileStreamFromUCB(String path) - throws IOException - { + throws IOException { InputStream result = null; XInputStream xInputStream = null; try { - LogUtils.DEBUG("Trying to read from " + path ); + LogUtils.DEBUG("Trying to read from " + path); xInputStream = m_xSimpleFileAccess.openFileRead(path); - LogUtils.DEBUG("sfa appeared to read file " ); + LogUtils.DEBUG("sfa appeared to read file "); byte[][] inputBytes = new byte[1][]; int sz = m_xSimpleFileAccess.getSize(path); + // TODO don't depend on result of available() or size() // just read stream 'till complete - if ( sz == 0 ) - { - if ( xInputStream.available() > 0 ) - { + if (sz == 0) { + if (xInputStream.available() > 0) { sz = xInputStream.available(); } } - LogUtils.DEBUG("size of file " + path + " is " + sz ); - LogUtils.DEBUG("available = " + xInputStream.available() ); + + LogUtils.DEBUG("size of file " + path + " is " + sz); + LogUtils.DEBUG("available = " + xInputStream.available()); inputBytes[0] = new byte[sz]; int ln = xInputStream.readBytes(inputBytes, sz); @@ -239,27 +236,23 @@ public class UCBStreamHandler extends URLStreamHandler { } result = new ByteArrayInputStream(inputBytes[0]); - } - catch (com.sun.star.io.IOException ioe) { - LogUtils.DEBUG("caught exception " + ioe ); + } catch (com.sun.star.io.IOException ioe) { + LogUtils.DEBUG("caught exception " + ioe); throw new IOException(ioe.getMessage()); - } - catch (com.sun.star.uno.Exception e) { - LogUtils.DEBUG("caught exception " + e ); + } catch (com.sun.star.uno.Exception e) { + LogUtils.DEBUG("caught exception " + e); throw new IOException(e.getMessage()); - } - finally - { + } finally { if (xInputStream != null) { try { xInputStream.closeInput(); - } - catch (Exception e2) { + } catch (Exception e2) { LogUtils.DEBUG( "Error closing XInputStream:" + e2.getMessage()); } } } + return result; } diff --git a/scripting/java/com/sun/star/script/framework/io/XInputStreamImpl.java b/scripting/java/com/sun/star/script/framework/io/XInputStreamImpl.java index 801cb0d4be3a..19d9c508923e 100644 --- a/scripting/java/com/sun/star/script/framework/io/XInputStreamImpl.java +++ b/scripting/java/com/sun/star/script/framework/io/XInputStreamImpl.java @@ -23,86 +23,78 @@ import java.io.InputStream; import com.sun.star.io.XInputStream; -public class XInputStreamImpl implements XInputStream -{ +public class XInputStreamImpl implements XInputStream { private InputStream is; - public XInputStreamImpl( InputStream is ) - { + public XInputStreamImpl(InputStream is) { this.is = is; } - public int readBytes( /*OUT*/byte[][] aData, /*IN*/int nBytesToRead ) throws com.sun.star.io.NotConnectedException, com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException - { + public int readBytes(/*OUT*/byte[][] aData, /*IN*/int nBytesToRead) throws + com.sun.star.io.NotConnectedException, + com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException { aData[ 0 ] = new byte[ nBytesToRead ]; int totalBytesRead = 0; - try - { + try { int bytesRead; - while ( ( bytesRead = is.read( aData[ 0 ], totalBytesRead, nBytesToRead ) ) > 0 && ( totalBytesRead < nBytesToRead ) ) - { + + while ((bytesRead = is.read(aData[ 0 ], totalBytesRead, nBytesToRead)) > 0 + && (totalBytesRead < nBytesToRead)) { totalBytesRead += bytesRead; nBytesToRead -= bytesRead; } - } - catch ( IOException e ) - { + } catch (IOException e) { throw new com.sun.star.io.IOException(e); - } - catch ( IndexOutOfBoundsException aie ) - { + } catch (IndexOutOfBoundsException aie) { throw new com.sun.star.io.BufferSizeExceededException(aie); } + return totalBytesRead; } - public int readSomeBytes( /*OUT*/byte[][] aData, /*IN*/int nMaxBytesToRead ) throws com.sun.star.io.NotConnectedException, com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException - { + public int readSomeBytes(/*OUT*/byte[][] aData, /*IN*/int nMaxBytesToRead) + throws com.sun.star.io.NotConnectedException, + com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException { int bytesToRead = nMaxBytesToRead; int availableBytes = available(); - if ( availableBytes < nMaxBytesToRead ) - { + + if (availableBytes < nMaxBytesToRead) { bytesToRead = availableBytes; } - int read = readBytes( aData, bytesToRead ); + + int read = readBytes(aData, bytesToRead); return read; } - public void skipBytes( /*IN*/int nBytesToSkip ) throws com.sun.star.io.NotConnectedException, com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException - { - try - { - is.skip( nBytesToSkip ); - } - catch ( IOException e ) - { + public void skipBytes(/*IN*/int nBytesToSkip) throws + com.sun.star.io.NotConnectedException, + com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException { + try { + is.skip(nBytesToSkip); + } catch (IOException e) { throw new com.sun.star.io.IOException(e); } } - public int available( ) throws com.sun.star.io.NotConnectedException, com.sun.star.io.IOException - { + public int available() throws com.sun.star.io.NotConnectedException, + com.sun.star.io.IOException { int bytesAvail = 0; - try - { + + try { bytesAvail = is.available(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new com.sun.star.io.IOException(e); } + return bytesAvail; } - public void closeInput( ) throws com.sun.star.io.NotConnectedException, com.sun.star.io.IOException - { - try - { + public void closeInput() throws com.sun.star.io.NotConnectedException, + com.sun.star.io.IOException { + try { is.close(); - } - catch( IOException e ) - { + } catch (IOException e) { throw new com.sun.star.io.IOException(e); } } diff --git a/scripting/java/com/sun/star/script/framework/io/XInputStreamWrapper.java b/scripting/java/com/sun/star/script/framework/io/XInputStreamWrapper.java index a1e27793f4f1..8da2bb27ff1b 100644 --- a/scripting/java/com/sun/star/script/framework/io/XInputStreamWrapper.java +++ b/scripting/java/com/sun/star/script/framework/io/XInputStreamWrapper.java @@ -28,69 +28,59 @@ public class XInputStreamWrapper extends InputStream { } @Override - public int read() throws java.io.IOException - { + public int read() throws java.io.IOException { byte[][] byteRet = new byte[1][0]; long numRead; try { numRead = m_xInputStream.readBytes(byteRet, 1); - } - catch (com.sun.star.io.IOException ioe) { + } catch (com.sun.star.io.IOException ioe) { throw new java.io.IOException(ioe.getMessage()); } if (numRead != 1) { return -1; } + return byteRet[0][0]; } @Override - public int read( byte[] b ) throws java.io.IOException - { + public int read(byte[] b) throws java.io.IOException { byte[][] byteRet = new byte[1][]; byteRet[0] = b; - try - { - return m_xInputStream.readBytes( byteRet, b.length ); - } - catch ( com.sun.star.io.IOException ioe) - { + + try { + return m_xInputStream.readBytes(byteRet, b.length); + } catch (com.sun.star.io.IOException ioe) { throw new java.io.IOException(ioe.getMessage()); } } @Override - public long skip(long n) throws java.io.IOException - { + public long skip(long n) throws java.io.IOException { try { m_xInputStream.skipBytes((int)n); return n; - } - catch (com.sun.star.io.IOException ioe) { + } catch (com.sun.star.io.IOException ioe) { throw new java.io.IOException(ioe.getMessage()); } } @Override - public int available() throws java.io.IOException - { + public int available() throws java.io.IOException { try { return m_xInputStream.available(); - } - catch (com.sun.star.io.IOException ioe) { + } catch (com.sun.star.io.IOException ioe) { throw new java.io.IOException(ioe.getMessage()); } } @Override - public void close() throws java.io.IOException - { + public void close() throws java.io.IOException { try { m_xInputStream.closeInput(); - } - catch (com.sun.star.io.IOException ioe) { + } catch (com.sun.star.io.IOException ioe) { throw new java.io.IOException(ioe.getMessage()); } } diff --git a/scripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java b/scripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java index b1c663c54a7c..1d54b136811f 100644 --- a/scripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java +++ b/scripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java @@ -21,101 +21,83 @@ import com.sun.star.io.XOutputStream; public class XOutputStreamWrapper extends OutputStream { - private XOutputStream m_xOutputStream; - public XOutputStreamWrapper(XOutputStream xOs ) { - this.m_xOutputStream = xOs; + private XOutputStream m_xOutputStream; + public XOutputStreamWrapper(XOutputStream xOs) { + this.m_xOutputStream = xOs; + } + @Override + public void write(int b) + throws java.io.IOException { + if (m_xOutputStream == null) { + throw new java.io.IOException("Stream is null"); + } + + byte[] bytes = new byte[1]; + bytes[0] = (byte) b; + + try { + m_xOutputStream.writeBytes(bytes); + } catch (com.sun.star.io.IOException ioe) { + throw new java.io.IOException(ioe.getMessage()); + } + } + @Override + public void write(byte[] b) + throws java.io.IOException { + + if (m_xOutputStream == null) { + throw new java.io.IOException("Stream is null"); + } + + try { + m_xOutputStream.writeBytes(b); + } catch (com.sun.star.io.IOException ioe) { + throw new java.io.IOException(ioe.getMessage()); } - @Override - public void write(int b) - throws java.io.IOException - { - if ( m_xOutputStream == null ) - { - throw new java.io.IOException("Stream is null"); - } - byte[] bytes = new byte[1]; - bytes[0] = (byte) b; - try - { - m_xOutputStream.writeBytes( bytes ); - } - catch ( com.sun.star.io.IOException ioe ) - { - throw new java.io.IOException(ioe.getMessage()); - } + } + @Override + public void write(byte[] b, int off, int len) + throws java.io.IOException { + if (m_xOutputStream == null) { + throw new java.io.IOException("Stream is null"); } - @Override - public void write(byte[] b) - throws java.io.IOException - { - if ( m_xOutputStream == null ) - { - throw new java.io.IOException( "Stream is null" ); - } - try - { - m_xOutputStream.writeBytes( b ); - } - catch ( com.sun.star.io.IOException ioe ) - { - throw new java.io.IOException(ioe.getMessage()); - } + byte[] bytes = new byte[len]; + System.arraycopy(b, off, bytes, 0, len); + + try { + m_xOutputStream.writeBytes(bytes); + } catch (com.sun.star.io.IOException ioe) { + throw new java.io.IOException(ioe.getMessage()); } - @Override - public void write( byte[] b, int off, int len ) - throws java.io.IOException - { - if ( m_xOutputStream == null ) - { - throw new java.io.IOException( "Stream is null" ); - } - byte[] bytes = new byte[len]; - System.arraycopy(b, off, bytes, 0, len); - try - { - m_xOutputStream.writeBytes(bytes); - } - catch ( com.sun.star.io.IOException ioe ) - { - throw new java.io.IOException(ioe.getMessage()); - } + } + + @Override + public void flush() + throws java.io.IOException { + if (m_xOutputStream == null) { + throw new java.io.IOException("Stream is null"); } - @Override - public void flush() - throws java.io.IOException - { - if ( m_xOutputStream == null ) - { - throw new java.io.IOException( "Stream is null" ); - } - try - { - m_xOutputStream.flush(); - } - catch ( com.sun.star.io.IOException ioe ) - { - throw new java.io.IOException(ioe.getMessage()); - } + try { + m_xOutputStream.flush(); + } catch (com.sun.star.io.IOException ioe) { + throw new java.io.IOException(ioe.getMessage()); } - @Override - public void close() - throws java.io.IOException - { - if ( m_xOutputStream == null ) - { - throw new java.io.IOException( "Stream is null" ); - } - try - { - m_xOutputStream.closeOutput(); - } - catch ( com.sun.star.io.IOException ioe ) - { - throw new java.io.IOException(ioe.getMessage()); - } + } + @Override + public void close() + throws java.io.IOException { + if (m_xOutputStream == null) { + throw new java.io.IOException("Stream is null"); } + try { + m_xOutputStream.closeOutput(); + } catch (com.sun.star.io.IOException ioe) { + throw new java.io.IOException(ioe.getMessage()); + } } +} + diff --git a/scripting/java/com/sun/star/script/framework/io/XStorageHelper.java b/scripting/java/com/sun/star/script/framework/io/XStorageHelper.java index c936aacfae07..aed57aee66f7 100644 --- a/scripting/java/com/sun/star/script/framework/io/XStorageHelper.java +++ b/scripting/java/com/sun/star/script/framework/io/XStorageHelper.java @@ -50,182 +50,158 @@ import java.util.*; import java.io.*; -public class XStorageHelper implements XEventListener -{ +public class XStorageHelper implements XEventListener { XStorage[] xStorages; XStream xStream; XInputStream xIs = null; XOutputStream xOs = null; - static Map<String,XModel> modelMap = new HashMap<String,XModel>(); + static Map<String, XModel> modelMap = new HashMap<String, XModel>(); XModel xModel = null; private static XStorageHelper listener = new XStorageHelper(); private XStorageHelper() {} - public XStorageHelper( String path, int mode, boolean create ) throws IOException - { + public XStorageHelper(String path, int mode, + boolean create) throws IOException { String modelUrl = null; - int indexOfScriptsDir = path.lastIndexOf( "Scripts" ); - if ( indexOfScriptsDir > -1 ) - { - modelUrl = path.substring( 0, indexOfScriptsDir - 1 ); - path = path.substring( indexOfScriptsDir, path.length()); + int indexOfScriptsDir = path.lastIndexOf("Scripts"); + + if (indexOfScriptsDir > -1) { + modelUrl = path.substring(0, indexOfScriptsDir - 1); + path = path.substring(indexOfScriptsDir, path.length()); } LogUtils.DEBUG("XStorageHelper ctor, path: " + path); - this.xModel = getModelForURL( modelUrl ); + this.xModel = getModelForURL(modelUrl); - try - { + try { StringTokenizer tokens = new StringTokenizer(path, "/"); - if (tokens.countTokens() == 0) - { - throw new IOException("Invalid path"); + if (tokens.countTokens() == 0) { + throw new IOException("Invalid path"); } + XDocumentSubStorageSupplier xDocumentSubStorageSupplier = UnoRuntime.queryInterface( - XDocumentSubStorageSupplier.class, xModel); + XDocumentSubStorageSupplier.class, xModel); xStorages = new XStorage[tokens.countTokens() ]; - LogUtils.DEBUG("XStorageHelper ctor, path chunks length: " + xStorages.length ); + LogUtils.DEBUG("XStorageHelper ctor, path chunks length: " + xStorages.length); - for ( int i = 0; i < xStorages.length; i++ ) - { - LogUtils.DEBUG("XStorageHelper, processing index " + i ); + for (int i = 0; i < xStorages.length; i++) { + LogUtils.DEBUG("XStorageHelper, processing index " + i); String name = tokens.nextToken(); LogUtils.DEBUG("XStorageHelper, getting: " + name); XStorage storage = null; - if ( i == 0 ) - { - storage = xDocumentSubStorageSupplier.getDocumentSubStorage( name, mode ); - if ( storage == null ) - { - LogUtils.DEBUG("** boo hoo Storage is null " ); + + if (i == 0) { + storage = xDocumentSubStorageSupplier.getDocumentSubStorage(name, mode); + + if (storage == null) { + LogUtils.DEBUG("** boo hoo Storage is null "); } - XPropertySet xProps = UnoRuntime.queryInterface(XPropertySet.class,storage ); - if ( xProps != null ) - { - String mediaType = AnyConverter.toString( xProps.getPropertyValue( "MediaType" ) ); - LogUtils.DEBUG("***** media type is " + mediaType ); - if ( !mediaType.equals("scripts") ) - { - xProps.setPropertyValue("MediaType","scripts"); + + XPropertySet xProps = UnoRuntime.queryInterface(XPropertySet.class, storage); + + if (xProps != null) { + String mediaType = AnyConverter.toString(xProps.getPropertyValue("MediaType")); + LogUtils.DEBUG("***** media type is " + mediaType); + + if (!mediaType.equals("scripts")) { + xProps.setPropertyValue("MediaType", "scripts"); } } - } - else - { - XNameAccess xNameAccess = UnoRuntime.queryInterface(XNameAccess.class, xStorages[i-1]); - if (xNameAccess == null ) - { + } else { + XNameAccess xNameAccess = UnoRuntime.queryInterface(XNameAccess.class, + xStorages[i - 1]); + + if (xNameAccess == null) { disposeObject(); throw new IOException("No name access " + name); - } - else if ( !xNameAccess.hasByName(name) || !xStorages[i-1].isStorageElement(name) ) - { - if ( !create ) - { + } else if (!xNameAccess.hasByName(name) + || !xStorages[i - 1].isStorageElement(name)) { + if (!create) { disposeObject(); throw new IOException("No subdir: " + name); - } - else - { + } else { // attempt to create new storage - LogUtils.DEBUG("Attempt to create new storage for " + name ); + LogUtils.DEBUG("Attempt to create new storage for " + name); } } - storage = xStorages[i-1].openStorageElement( - name, mode ); + storage = xStorages[i - 1].openStorageElement( + name, mode); } - if ( storage == null ) - { + + if (storage == null) { disposeObject(); throw new IOException("storage not found: " + name); } + xStorages[ i ] = storage; } - } - catch ( com.sun.star.io.IOException ioe) - { + } catch (com.sun.star.io.IOException ioe) { disposeObject(); - } - catch (com.sun.star.uno.Exception e) - { + } catch (com.sun.star.uno.Exception e) { disposeObject(); throw new IOException(e.getMessage()); } } - public synchronized static void addNewModel( XModel model ) - { + public synchronized static void addNewModel(XModel model) { // TODO needs to cater for model for untitled document - modelMap.put( PathUtils.getOidForModel( model ), model ); + modelMap.put(PathUtils.getOidForModel(model), model); XComponent xComp = UnoRuntime.queryInterface(XComponent.class, model); - if ( xComp != null ) - { - try - { - xComp.addEventListener( listener ); - } - catch ( Exception e ) - { + if (xComp != null) { + try { + xComp.addEventListener(listener); + } catch (Exception e) { // What TODO here ? - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + LogUtils.DEBUG(LogUtils.getTrace(e)); } } } - public void disposing( EventObject Source ) - { - XModel model = UnoRuntime.queryInterface(XModel.class,Source.Source ); + public void disposing(EventObject Source) { + XModel model = UnoRuntime.queryInterface(XModel.class, Source.Source); - if ( model != null ) - { - LogUtils.DEBUG(" Disposing doc " + model.getURL() ); - modelMap.remove( model ); + if (model != null) { + LogUtils.DEBUG(" Disposing doc " + model.getURL()); + modelMap.remove(model); } } - public XStorage getStorage() - { + public XStorage getStorage() { return xStorages[ xStorages.length - 1 ]; } - public XModel getModel() - { + public XModel getModel() { return xModel; } - public void disposeObject() - { - disposeObject( false ); + public void disposeObject() { + disposeObject(false); } - public void disposeObject( boolean shouldCommit ) - { + public void disposeObject(boolean shouldCommit) { LogUtils.DEBUG("In disposeObject"); - for ( int i = xStorages.length -1 ; i > -1; i-- ) - { - LogUtils.DEBUG("In disposeObject disposing storage " + i ); - try - { + for (int i = xStorages.length - 1 ; i > -1; i--) { + LogUtils.DEBUG("In disposeObject disposing storage " + i); + + try { XStorage xStorage = xStorages[i]; - if ( shouldCommit ) - { + + if (shouldCommit) { commit(xStorage); } + disposeObject(xStorage); - LogUtils.DEBUG("In disposeObject disposed storage " + i ); - } - catch( Exception ignore ) - { - LogUtils.DEBUG("Exception disposing storage " + i ); + LogUtils.DEBUG("In disposeObject disposed storage " + i); + } catch (Exception ignore) { + LogUtils.DEBUG("Exception disposing storage " + i); } } } - static public void disposeObject( XInterface xInterface ) - { + static public void disposeObject(XInterface xInterface) { if (xInterface == null) { return; } @@ -235,28 +211,25 @@ public class XStorageHelper implements XEventListener if (xComponent == null) { return; } + xComponent.dispose(); } - static public void commit( XInterface xInterface ) - { - XTransactedObject xTrans = UnoRuntime.queryInterface(XTransactedObject.class, xInterface); - if ( xTrans != null ) - { - try - { + static public void commit(XInterface xInterface) { + XTransactedObject xTrans = UnoRuntime.queryInterface(XTransactedObject.class, + xInterface); + + if (xTrans != null) { + try { xTrans.commit(); - } - catch ( Exception e ) - { - LogUtils.DEBUG("Something went bellyup exception: " + e ); + } catch (Exception e) { + LogUtils.DEBUG("Something went bellyup exception: " + e); } } } - public XModel getModelForURL( String url ) - { - //TODO does not cater for untitled documents - return modelMap.get( url ); + public XModel getModelForURL(String url) { + //TODO does not cater for untitled documents + return modelMap.get(url); } } diff --git a/scripting/java/com/sun/star/script/framework/log/LogUtils.java b/scripting/java/com/sun/star/script/framework/log/LogUtils.java index 0344db864214..e6ed7ff61dbe 100644 --- a/scripting/java/com/sun/star/script/framework/log/LogUtils.java +++ b/scripting/java/com/sun/star/script/framework/log/LogUtils.java @@ -25,13 +25,11 @@ public class LogUtils { private static boolean m_bDebugEnabled = false; - static - { + static { String debugFlag = System.getProperties().getProperty("ScriptJavaRuntimeDebug"); - if (debugFlag != null && debugFlag.length() > 0) - { + if (debugFlag != null && debugFlag.length() > 0) { m_bDebugEnabled = debugFlag.equalsIgnoreCase("true"); } } @@ -45,42 +43,34 @@ public class LogUtils { * * @param msg message to be displayed */ - public static void DEBUG(String msg) - { - if (m_bDebugEnabled) - { + public static void DEBUG(String msg) { + if (m_bDebugEnabled) { System.out.println(msg); } } - public static String getTrace( Exception e ) - { + public static String getTrace(Exception e) { ByteArrayOutputStream baos = null; PrintStream ps = null; String result = ""; - try - { - baos = new ByteArrayOutputStream( ); - ps = new PrintStream( baos ); - e.printStackTrace( ps ); - } - finally - { - try - { - if ( baos != null ) - { + + try { + baos = new ByteArrayOutputStream(); + ps = new PrintStream(baos); + e.printStackTrace(ps); + } finally { + try { + if (baos != null) { baos.close(); } - if ( ps != null ) - { + + if (ps != null) { ps.close(); } - } - catch ( Exception excp ) - { + } catch (Exception excp) { } } + return result; } } diff --git a/scripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java b/scripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java index 823f2ff731e7..73f3f9c38fd9 100644 --- a/scripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java +++ b/scripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java @@ -26,24 +26,23 @@ import com.sun.star.script.framework.container.ScriptMetaData; /** * Class Loader Factory */ -public class ClassLoaderFactory -{ +public class ClassLoaderFactory { private ClassLoaderFactory() {} - public static ClassLoader getURLClassLoader( ScriptMetaData scriptData ) - { + public static ClassLoader getURLClassLoader(ScriptMetaData scriptData) { ClassLoader parent = scriptData.getClass().getClassLoader(); URL[] classPath = scriptData.getClassPath(); - LogUtils.DEBUG("Classpath has length " + classPath.length ); - for ( int i=0; i < classPath.length; i++ ) - { - LogUtils.DEBUG("ClassPath " + i + "} is " + classPath[ i ].toString() ); + LogUtils.DEBUG("Classpath has length " + classPath.length); + + for (int i = 0; i < classPath.length; i++) { + LogUtils.DEBUG("ClassPath " + i + "} is " + classPath[ i ].toString()); } - return getURLClassLoader( parent, classPath ); + + return getURLClassLoader(parent, classPath); } - private static ClassLoader getURLClassLoader( ClassLoader parent, URL[] classpath) - { - return new URLClassLoader( classpath, parent); + private static ClassLoader getURLClassLoader(ClassLoader parent, + URL[] classpath) { + return new URLClassLoader(classpath, parent); } } diff --git a/scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java b/scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java index 994a62700db0..5755e8cd6a28 100644 --- a/scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java +++ b/scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java @@ -25,13 +25,11 @@ import com.sun.star.document.XScriptInvocationContext; import com.sun.star.script.provider.XScriptContext; -public class EditorScriptContext implements XScriptContext -{ +public class EditorScriptContext implements XScriptContext { private XDesktop m_xDeskTop; private XComponentContext m_xComponentContext; - public EditorScriptContext( XComponentContext xmComponentContext, - XDesktop xDesktop ) - { + public EditorScriptContext(XComponentContext xmComponentContext, + XDesktop xDesktop) { this.m_xComponentContext = xmComponentContext; this.m_xDeskTop = xDesktop; } @@ -41,18 +39,16 @@ public class EditorScriptContext implements XScriptContext @return XModel interface */ - public XModel getDocument() - { - XModel xModel = UnoRuntime.queryInterface( XModel.class, - m_xDeskTop.getCurrentComponent() ); + public XModel getDocument() { + XModel xModel = UnoRuntime.queryInterface(XModel.class, + m_xDeskTop.getCurrentComponent()); return xModel; } - public XScriptInvocationContext getInvocationContext() - { + public XScriptInvocationContext getInvocationContext() { XScriptInvocationContext xContext = UnoRuntime.queryInterface( - XScriptInvocationContext.class, getDocument() ); + XScriptInvocationContext.class, getDocument()); return xContext; } @@ -61,8 +57,7 @@ public class EditorScriptContext implements XScriptContext @return XDesktop interface */ - public XDesktop getDesktop() - { + public XDesktop getDesktop() { return m_xDeskTop; } @@ -71,9 +66,8 @@ public class EditorScriptContext implements XScriptContext @return XComponentContext interface */ - public XComponentContext getComponentContext() - { - return m_xComponentContext; + public XComponentContext getComponentContext() { + return m_xComponentContext; } } diff --git a/scripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java b/scripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java index ea412fc6b678..c9c103256a39 100644 --- a/scripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java +++ b/scripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java @@ -18,14 +18,12 @@ package com.sun.star.script.framework.provider; -public class NoSuitableClassLoaderException extends Exception -{ +public class NoSuitableClassLoaderException extends Exception { /** * Constructs an <code>NoSuitableClassLoaderException</code> with <code>null</code> * as its error detail message. */ - public NoSuitableClassLoaderException() - { + public NoSuitableClassLoaderException() { super(); } /** @@ -36,8 +34,7 @@ public class NoSuitableClassLoaderException extends Exception * * @param s the detail message. */ - public NoSuitableClassLoaderException(String s) - { + public NoSuitableClassLoaderException(String s) { super(s); } diff --git a/scripting/java/com/sun/star/script/framework/provider/PathUtils.java b/scripting/java/com/sun/star/script/framework/provider/PathUtils.java index 1bd7bd28f657..3cb88c929d2a 100644 --- a/scripting/java/com/sun/star/script/framework/provider/PathUtils.java +++ b/scripting/java/com/sun/star/script/framework/provider/PathUtils.java @@ -38,46 +38,41 @@ public class PathUtils { BOOTSTRAP_NAME = m_windows ? "bootstrap.ini" : "bootstraprc"; } - public static String getOidForModel( XModel xModel ) - { + public static String getOidForModel(XModel xModel) { String oid = ""; - if ( xModel != null ) - { - try - { - Method getOid = IQueryInterface.class.getMethod("getOid", (java.lang.Class[])null); - if ( getOid != null ) - { - oid = (String)getOid.invoke( xModel, new Object[0] ); + + if (xModel != null) { + try { + Method getOid = IQueryInterface.class.getMethod("getOid", + (java.lang.Class[])null); + + if (getOid != null) { + oid = (String)getOid.invoke(xModel, new Object[0]); } - } - catch ( Exception ignore ) - { + } catch (Exception ignore) { } } + return oid; } - static public String make_url( String baseUrl, String url ) - { - StringBuilder buff = new StringBuilder( baseUrl.length() + url.length() ); - buff.append( baseUrl ); - StringTokenizer t = new StringTokenizer( url, "/"); - while ( t.hasMoreElements() ) - { - if ( buff.charAt( buff.length() - 1 ) != '/' ) - { - buff.append('/'); - } - try - { - buff.append( java.net.URLEncoder.encode( (String)t.nextElement(), "UTF-8" ) ); - } - catch (java.io.UnsupportedEncodingException e) - { - e.printStackTrace(); - } + static public String make_url(String baseUrl, String url) { + StringBuilder buff = new StringBuilder(baseUrl.length() + url.length()); + buff.append(baseUrl); + StringTokenizer t = new StringTokenizer(url, "/"); + + while (t.hasMoreElements()) { + if (buff.charAt(buff.length() - 1) != '/') { + buff.append('/'); + } + + try { + buff.append(java.net.URLEncoder.encode((String)t.nextElement(), "UTF-8")); + } catch (java.io.UnsupportedEncodingException e) { + e.printStackTrace(); + } } + return buff.toString(); } diff --git a/scripting/java/com/sun/star/script/framework/provider/ScriptContext.java b/scripting/java/com/sun/star/script/framework/provider/ScriptContext.java index 9d922cf30c5a..546755e9e93a 100644 --- a/scripting/java/com/sun/star/script/framework/provider/ScriptContext.java +++ b/scripting/java/com/sun/star/script/framework/provider/ScriptContext.java @@ -31,8 +31,7 @@ import com.sun.star.script.provider.XScriptContext; import com.sun.star.script.framework.log.LogUtils; -public class ScriptContext extends PropertySet implements XScriptContext -{ +public class ScriptContext extends PropertySet implements XScriptContext { private final static String HM_DOC_REF = "DocumentReference"; private final static String HM_DESKTOP = "Desktop"; private final static String HM_COMPONENT_CONTEXT = "ComponentContext"; @@ -47,51 +46,50 @@ public class ScriptContext extends PropertySet implements XScriptContext private XComponentContext m_xComponentContext = null; - private ScriptContext( XComponentContext xmComponentContext, - XDesktop xDesktop, XModel xModel, XScriptInvocationContext xInvocContext) - { + private ScriptContext(XComponentContext xmComponentContext, + XDesktop xDesktop, XModel xModel, XScriptInvocationContext xInvocContext) { this.m_xDeskTop = xDesktop; this.m_xComponentContext = xmComponentContext; this.m_xModel = xModel; this.m_xInvocationContext = xInvocContext; - if ( m_xModel != null ) - { - registerProperty( DOC_URI, new Type(String.class), - (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_sDocURI"); + if (m_xModel != null) { + registerProperty(DOC_URI, new Type(String.class), + (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), + "m_sDocURI"); } - registerProperty( HM_DOC_REF, new Type(XModel.class), - (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_xModel"); - registerProperty( HM_DESKTOP, new Type(XDesktop.class), - (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_xDeskTop"); - registerProperty( HM_COMPONENT_CONTEXT, new Type(XDesktop.class), - (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_xComponentContext"); + registerProperty(HM_DOC_REF, new Type(XModel.class), + (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_xModel"); + registerProperty(HM_DESKTOP, new Type(XDesktop.class), + (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), + "m_xDeskTop"); + registerProperty(HM_COMPONENT_CONTEXT, new Type(XDesktop.class), + (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), + "m_xComponentContext"); } - public static XScriptContext createContext( XModel xModel, XScriptInvocationContext xInvocContext, - XComponentContext xCtxt, XMultiComponentFactory xMCF) - { + public static XScriptContext createContext(XModel xModel, + XScriptInvocationContext xInvocContext, + XComponentContext xCtxt, XMultiComponentFactory xMCF) { XScriptContext sc = null; try { Object xInterface = xMCF.createInstanceWithContext( - "com.sun.star.frame.Desktop", xCtxt); + "com.sun.star.frame.Desktop", xCtxt); XDesktop xDesktop = UnoRuntime.queryInterface(XDesktop.class, xInterface); - if ( xModel != null ) - { + + if (xModel != null) { sc = new ScriptContext(xCtxt, xDesktop, xModel, xInvocContext); - } - else - { - sc = new EditorScriptContext(xCtxt, xDesktop ); + } else { + sc = new EditorScriptContext(xCtxt, xDesktop); } + } catch (Exception e) { + LogUtils.DEBUG(LogUtils.getTrace(e)); } - catch ( Exception e ) { - LogUtils.DEBUG( LogUtils.getTrace( e ) ); - } + return sc; } @@ -101,13 +99,11 @@ public class ScriptContext extends PropertySet implements XScriptContext @return XModel interface */ - public XModel getDocument() - { + public XModel getDocument() { return m_xModel; } - public XScriptInvocationContext getInvocationContext() - { + public XScriptInvocationContext getInvocationContext() { return m_xInvocationContext; } @@ -116,8 +112,7 @@ public class ScriptContext extends PropertySet implements XScriptContext @return XDesktop interface */ - public XDesktop getDesktop() - { + public XDesktop getDesktop() { return m_xDeskTop; } @@ -126,9 +121,8 @@ public class ScriptContext extends PropertySet implements XScriptContext @return XComponentContext interface */ - public XComponentContext getComponentContext() - { - return m_xComponentContext; + public XComponentContext getComponentContext() { + return m_xComponentContext; } } diff --git a/scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java b/scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java index 834108bc62ba..8ae3b510fdf2 100644 --- a/scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java +++ b/scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java @@ -21,10 +21,9 @@ package com.sun.star.script.framework.provider; import com.sun.star.script.provider.XScriptContext; import com.sun.star.script.framework.container.ScriptMetaData; -public interface ScriptEditor -{ +public interface ScriptEditor { Object execute() throws Exception; - void indicateErrorLine( int lineNum ); + void indicateErrorLine(int lineNum); void edit(XScriptContext context, ScriptMetaData entry); String getTemplate(); String getExtension(); diff --git a/scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java b/scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java index 3ee02ecb8dc5..3077ae6da3ec 100644 --- a/scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java +++ b/scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java @@ -80,8 +80,7 @@ import com.sun.star.uno.TypeClass; public abstract class ScriptProvider implements XScriptProvider, XBrowseNode, XPropertySet, XInvocation, - XInitialization, XTypeProvider, XServiceInfo, XNameContainer -{ + XInitialization, XTypeProvider, XServiceInfo, XNameContainer { private final String[] __serviceNames = { "com.sun.star.script.provider.ScriptProviderFor", "com.sun.star.script.provider.LanguageScriptProvider" @@ -100,178 +99,165 @@ public abstract class ScriptProvider // proxies to helper objects which implement interfaces private XPropertySet m_xPropertySetProxy; private XInvocation m_xInvocationProxy; - // TODO should this be implemented in this class + // TODO should this be implemented in this class private XBrowseNode m_xBrowseNodeProxy; private XScriptContext m_xScriptContext; - public ScriptProvider( XComponentContext ctx, String language ) - { + public ScriptProvider(XComponentContext ctx, String language) { this.language = language; __serviceNames[0] += language; - LogUtils.DEBUG( "ScriptProvider: constructor - start. " + language ); + LogUtils.DEBUG("ScriptProvider: constructor - start. " + language); m_xContext = ctx; // Initialize DialogFactory class in case dialogs are required DialogFactory.createDialogFactory(m_xContext); - try - { + try { m_xMultiComponentFactory = m_xContext.getServiceManager(); - if ( m_xMultiComponentFactory == null ) - { - throw new Exception( "Error could not obtain a " + - "multicomponent factory - rethrowing Exception." ); + if (m_xMultiComponentFactory == null) { + throw new Exception("Error could not obtain a " + + "multicomponent factory - rethrowing Exception."); } Object serviceObj = m_xContext.getValueByName( - "/singletons/com.sun.star.util.theMacroExpander"); + "/singletons/com.sun.star.util.theMacroExpander"); XMacroExpander me = (XMacroExpander) AnyConverter.toObject( - new Type(XMacroExpander.class), serviceObj); + new Type(XMacroExpander.class), serviceObj); XMLParserFactory.setOfficeDTDURL(me.expandMacros( - "$BRAND_BASE_DIR/$BRAND_SHARE_SUBDIR/dtd/officedocument/1_0/")); + "$BRAND_BASE_DIR/$BRAND_SHARE_SUBDIR/dtd/officedocument/1_0/")); - } - catch ( Exception e ) - { - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + } catch (Exception e) { + LogUtils.DEBUG(LogUtils.getTrace(e)); com.sun.star.uno.RuntimeException e2 = new com.sun.star.uno.RuntimeException( - "Error constructing ScriptProvider: " + e ); - e2.initCause( e ); + "Error constructing ScriptProvider: " + e); + e2.initCause(e); throw e2; } - LogUtils.DEBUG( "ScriptProvider: constructor - finished." ); + LogUtils.DEBUG("ScriptProvider: constructor - finished."); } - synchronized public XScriptContext getScriptingContext() - { - if ( m_xScriptContext == null ) - { - m_xScriptContext = ScriptContext.createContext( m_xModel, m_xInvocContext, m_xContext, m_xMultiComponentFactory ); + synchronized public XScriptContext getScriptingContext() { + if (m_xScriptContext == null) { + m_xScriptContext = ScriptContext.createContext(m_xModel, m_xInvocContext, + m_xContext, m_xMultiComponentFactory); } + return m_xScriptContext; } - public void initialize( Object[] aArguments ) - throws com.sun.star.uno.Exception - { - LogUtils.DEBUG( "entering XInit for language " + language); + + public void initialize(Object[] aArguments) + throws com.sun.star.uno.Exception { + LogUtils.DEBUG("entering XInit for language " + language); boolean isPkgProvider = false; - if( aArguments.length == 1 ) - { + + if (aArguments.length == 1) { String contextUrl = null; - if ( AnyConverter.getType(aArguments[0]).getTypeClass().equals(TypeClass.INTERFACE) ) - { + + if (AnyConverter.getType(aArguments[0]).getTypeClass().equals( + TypeClass.INTERFACE)) { // try whether it denotes a XScriptInvocationContext m_xInvocContext = UnoRuntime.queryInterface( - XScriptInvocationContext.class, aArguments[0]); - if ( m_xInvocContext != null ) - { + XScriptInvocationContext.class, aArguments[0]); + + if (m_xInvocContext != null) { // if so, obtain the document - by definition, this must be // the ScriptContainer - m_xModel = UnoRuntime.queryInterface( XModel.class, - m_xInvocContext.getScriptContainer() ); - } - else - { + m_xModel = UnoRuntime.queryInterface(XModel.class, + m_xInvocContext.getScriptContainer()); + } else { // otherwise, check whether it's an XModel - m_xModel = UnoRuntime.queryInterface( XModel.class, - m_xInvocContext.getScriptContainer() ); + m_xModel = UnoRuntime.queryInterface(XModel.class, + m_xInvocContext.getScriptContainer()); } - if ( m_xModel == null ) - { + + if (m_xModel == null) { throw new com.sun.star.uno.Exception( - "ScriptProvider argument must be either a string, a valid XScriptInvocationContext, " + + "ScriptProvider argument must be either a string, a valid XScriptInvocationContext, " + + "or an XModel", this); } - contextUrl = getDocUrlFromModel( m_xModel ); - m_container = new ParcelContainer( m_xContext, contextUrl, language ); - } - else if (AnyConverter.isString(aArguments[0])) - { + contextUrl = getDocUrlFromModel(m_xModel); + m_container = new ParcelContainer(m_xContext, contextUrl, language); + } else if (AnyConverter.isString(aArguments[0])) { String originalContextURL = AnyConverter.toString(aArguments[0]); - LogUtils.DEBUG("creating Application, path: " + originalContextURL ); + LogUtils.DEBUG("creating Application, path: " + originalContextURL); contextUrl = originalContextURL; + // TODO no support for packages in documents yet - if ( originalContextURL.startsWith( "vnd.sun.star.tdoc" ) ) - { - m_container = new ParcelContainer( m_xContext, contextUrl, language ); - m_xModel = getModelFromDocUrl( originalContextURL ); - } - else - { + if (originalContextURL.startsWith("vnd.sun.star.tdoc")) { + m_container = new ParcelContainer(m_xContext, contextUrl, language); + m_xModel = getModelFromDocUrl(originalContextURL); + } else { String extensionDb = null; String extensionRepository = null; - if ( originalContextURL.startsWith( "bundled" ) ) - { + + if (originalContextURL.startsWith("bundled")) { contextUrl = "vnd.sun.star.expand:$BUNDLED_EXTENSIONS"; - extensionDb = "vnd.sun.star.expand:${$BRAND_INI_DIR/" + PathUtils.BOOTSTRAP_NAME + "::UserInstallation}/user"; + extensionDb = "vnd.sun.star.expand:${$BRAND_INI_DIR/" + PathUtils.BOOTSTRAP_NAME + + "::UserInstallation}/user"; extensionRepository = "bundled"; - } - else if ( originalContextURL.startsWith( "share" ) ) - { + } else if (originalContextURL.startsWith("share")) { contextUrl = "vnd.sun.star.expand:$BRAND_BASE_DIR/$BRAND_SHARE_SUBDIR"; - extensionDb = "vnd.sun.star.expand:${$BRAND_INI_DIR/" + PathUtils.BOOTSTRAP_NAME + "::UserInstallation}/user"; + extensionDb = "vnd.sun.star.expand:${$BRAND_INI_DIR/" + PathUtils.BOOTSTRAP_NAME + + "::UserInstallation}/user"; extensionRepository = "shared"; - } - else if ( originalContextURL.startsWith( "user" ) ) - { - contextUrl = "vnd.sun.star.expand:${$BRAND_INI_DIR/" + PathUtils.BOOTSTRAP_NAME + "::UserInstallation}/user"; - extensionDb = "vnd.sun.star.expand:${$BRAND_INI_DIR/" + PathUtils.BOOTSTRAP_NAME + "::UserInstallation}/user"; + } else if (originalContextURL.startsWith("user")) { + contextUrl = "vnd.sun.star.expand:${$BRAND_INI_DIR/" + PathUtils.BOOTSTRAP_NAME + + "::UserInstallation}/user"; + extensionDb = "vnd.sun.star.expand:${$BRAND_INI_DIR/" + PathUtils.BOOTSTRAP_NAME + + "::UserInstallation}/user"; extensionRepository = "user"; } - if ( originalContextURL.endsWith( "uno_packages") ) - { + if (originalContextURL.endsWith("uno_packages")) { isPkgProvider = true; + if (!originalContextURL.equals(contextUrl) - && !extensionRepository.equals("bundled")) - { + && !extensionRepository.equals("bundled")) { contextUrl = PathUtils.make_url(contextUrl, "uno_packages"); } } - if ( isPkgProvider ) - { - m_container = new UnoPkgContainer( m_xContext, contextUrl, extensionDb, extensionRepository, language ); - } - else - { - m_container = new ParcelContainer( m_xContext, contextUrl, language ); + if (isPkgProvider) { + m_container = new UnoPkgContainer(m_xContext, contextUrl, extensionDb, + extensionRepository, language); + } else { + m_container = new ParcelContainer(m_xContext, contextUrl, language); } } - } - else - { + } else { throw new com.sun.star.uno.RuntimeException( "ScriptProvider created with invalid argument"); } - LogUtils.DEBUG("Modified Application path is: " + contextUrl ); - LogUtils.DEBUG("isPkgProvider is: " + isPkgProvider ); + LogUtils.DEBUG("Modified Application path is: " + contextUrl); + LogUtils.DEBUG("isPkgProvider is: " + isPkgProvider); // TODO should all be done in this class instead of // deleagation???? - m_xBrowseNodeProxy = new ProviderBrowseNode( this, - m_container, m_xContext ); - - m_xInvocationProxy = UnoRuntime.queryInterface(XInvocation.class, m_xBrowseNodeProxy); - m_xPropertySetProxy = UnoRuntime.queryInterface(XPropertySet.class, m_xBrowseNodeProxy); - } - else - { + m_xBrowseNodeProxy = new ProviderBrowseNode(this, + m_container, m_xContext); + + m_xInvocationProxy = UnoRuntime.queryInterface(XInvocation.class, + m_xBrowseNodeProxy); + m_xPropertySetProxy = UnoRuntime.queryInterface(XPropertySet.class, + m_xBrowseNodeProxy); + } else { // this is ok, for example when executing a script from the // command line - LogUtils.DEBUG( "ScriptProviderFor" + language + - " initialized without a context"); + LogUtils.DEBUG("ScriptProviderFor" + language + + " initialized without a context"); } - LogUtils.DEBUG( "leaving XInit" ); + + LogUtils.DEBUG("leaving XInit"); } /** @@ -279,17 +265,16 @@ public abstract class ScriptProvider * * @return The types value */ - public com.sun.star.uno.Type[] getTypes() - { + public com.sun.star.uno.Type[] getTypes() { Type[] retValue = new Type[ 8 ]; - retValue[ 0 ] = new Type( XScriptProvider.class ); - retValue[ 1 ] = new Type( XBrowseNode.class ); - retValue[ 2 ] = new Type( XInitialization.class ); - retValue[ 3 ] = new Type( XTypeProvider.class ); - retValue[ 4 ] = new Type( XServiceInfo.class ); - retValue[ 5 ] = new Type( XPropertySet.class ); - retValue[ 6 ] = new Type( XInvocation.class ); - retValue[ 7 ] = new Type( com.sun.star.container.XNameContainer.class ); + retValue[ 0 ] = new Type(XScriptProvider.class); + retValue[ 1 ] = new Type(XBrowseNode.class); + retValue[ 2 ] = new Type(XInitialization.class); + retValue[ 3 ] = new Type(XTypeProvider.class); + retValue[ 4 ] = new Type(XServiceInfo.class); + retValue[ 5 ] = new Type(XPropertySet.class); + retValue[ 6 ] = new Type(XInvocation.class); + retValue[ 7 ] = new Type(com.sun.star.container.XNameContainer.class); return retValue; } @@ -298,8 +283,7 @@ public abstract class ScriptProvider * * @return The implementationId value */ - public byte[] getImplementationId() - { + public byte[] getImplementationId() { return new byte[0]; } @@ -308,8 +292,7 @@ public abstract class ScriptProvider * * @return The implementationName value */ - public String getImplementationName() - { + public String getImplementationName() { return getClass().getName(); } @@ -319,15 +302,13 @@ public abstract class ScriptProvider * @param serviceName Description of the Parameter * @return Description of the Return Value */ - public boolean supportsService( String serviceName ) - { - for ( int index = __serviceNames.length; index-- > 0; ) - { - if ( serviceName.equals( __serviceNames[ index ] ) ) - { + public boolean supportsService(String serviceName) { + for (int index = __serviceNames.length; index-- > 0;) { + if (serviceName.equals(__serviceNames[ index ])) { return true; } } + return false; } @@ -336,16 +317,15 @@ public abstract class ScriptProvider * * @return The supportedServiceNames value */ - public String[] getSupportedServiceNames() - { + public String[] getSupportedServiceNames() { return __serviceNames; } - public abstract XScript getScript( /*IN*/String scriptURI ) - throws com.sun.star.uno.RuntimeException, - ScriptFrameworkErrorException; + public abstract XScript getScript(/*IN*/String scriptURI) + throws com.sun.star.uno.RuntimeException, + ScriptFrameworkErrorException; // TODO need to encapsulate this better, // Some factory concept for creating/accessing Editor @@ -358,55 +338,51 @@ public abstract class ScriptProvider // This method is used to get the ScriptEditor for this ScriptProvider public abstract ScriptEditor getScriptEditor(); - public ScriptMetaData getScriptData( /*IN*/String scriptURI ) throws ScriptFrameworkErrorException + public ScriptMetaData getScriptData(/*IN*/String scriptURI) throws + ScriptFrameworkErrorException { - try - { - ParsedScriptUri details = m_container.parseScriptUri( scriptURI ); - try - { + try { + ParsedScriptUri details = m_container.parseScriptUri(scriptURI); + + try { ScriptMetaData scriptData = m_container.findScript(details); - if (scriptData == null) - { + + if (scriptData == null) { throw new ScriptFrameworkErrorException(details.function + " does not exist", - null, details.function, language, ScriptFrameworkErrorType.NO_SUCH_SCRIPT); + null, details.function, language, ScriptFrameworkErrorType.NO_SUCH_SCRIPT); } + return scriptData; - } - catch (com.sun.star.container.NoSuchElementException nse) - { + } catch (com.sun.star.container.NoSuchElementException nse) { ScriptFrameworkErrorException e2 - = new ScriptFrameworkErrorException( - nse.getMessage(), null, details.function, language, - ScriptFrameworkErrorType.NO_SUCH_SCRIPT); + = new ScriptFrameworkErrorException( + nse.getMessage(), null, details.function, language, + ScriptFrameworkErrorType.NO_SUCH_SCRIPT); e2.initCause(nse); throw e2; - } - catch (com.sun.star.lang.WrappedTargetException wta) - { + } catch (com.sun.star.lang.WrappedTargetException wta) { // TODO specify the correct error Type Exception wrapped = (Exception) wta.TargetException; String message = wta.getMessage(); - if (wrapped != null) - { + + if (wrapped != null) { message = wrapped.getMessage(); } + ScriptFrameworkErrorException e2 - = new ScriptFrameworkErrorException( - message, null, details.function, language, - ScriptFrameworkErrorType.UNKNOWN); + = new ScriptFrameworkErrorException( + message, null, details.function, language, + ScriptFrameworkErrorType.UNKNOWN); e2.initCause(wta); throw e2; } - } - catch (com.sun.star.lang.IllegalArgumentException ila) - { + } catch (com.sun.star.lang.IllegalArgumentException ila) { // TODO specify the correct error Type ScriptFrameworkErrorException e2 - = new ScriptFrameworkErrorException( - ila.getMessage(), null, scriptURI, language, - ScriptFrameworkErrorType.UNKNOWN); + = new ScriptFrameworkErrorException( + ila.getMessage(), null, scriptURI, language, + ScriptFrameworkErrorType.UNKNOWN); e2.initCause(ila); throw e2; } @@ -414,39 +390,34 @@ public abstract class ScriptProvider // Implementation of XBrowseNode interface - public String getName() - { + public String getName() { return language; } - public XBrowseNode[] getChildNodes() - { - if ( m_xBrowseNodeProxy == null ) - { + public XBrowseNode[] getChildNodes() { + if (m_xBrowseNodeProxy == null) { LogUtils.DEBUG("No Nodes available "); return new XBrowseNode[0]; } + return m_xBrowseNodeProxy .getChildNodes(); } - public boolean hasChildNodes() - { - if ( m_xBrowseNodeProxy == null ) - { + public boolean hasChildNodes() { + if (m_xBrowseNodeProxy == null) { LogUtils.DEBUG("No Nodes available "); return false; } + return m_xBrowseNodeProxy.hasChildNodes(); } - public short getType() - { + public short getType() { return BrowseNodeTypes.CONTAINER; } @Override - public String toString() - { + public String toString() { return getName(); } @@ -457,25 +428,22 @@ public abstract class ScriptProvider public Object invoke(String aFunctionName, Object[] aParams, short[][] aOutParamIndex, Object[][] aOutParam) - throws com.sun.star.lang.IllegalArgumentException, - com.sun.star.script.CannotConvertException, - com.sun.star.reflection.InvocationTargetException - { + throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.script.CannotConvertException, + com.sun.star.reflection.InvocationTargetException { return m_xInvocationProxy.invoke( - aFunctionName, aParams, aOutParamIndex, aOutParam); + aFunctionName, aParams, aOutParamIndex, aOutParam); } public void setValue(String aPropertyName, Object aValue) - throws com.sun.star.beans.UnknownPropertyException, - com.sun.star.script.CannotConvertException, - com.sun.star.reflection.InvocationTargetException - { + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.script.CannotConvertException, + com.sun.star.reflection.InvocationTargetException { m_xInvocationProxy.setValue(aPropertyName, aValue); } public Object getValue(String aPropertyName) - throws com.sun.star.beans.UnknownPropertyException - { + throws com.sun.star.beans.UnknownPropertyException { return m_xInvocationProxy.getValue(aPropertyName); } @@ -487,203 +455,195 @@ public abstract class ScriptProvider return m_xInvocationProxy.hasProperty(aName); } - public XPropertySetInfo getPropertySetInfo() - { + public XPropertySetInfo getPropertySetInfo() { return m_xPropertySetProxy.getPropertySetInfo(); } public void setPropertyValue(String aPropertyName, Object aValue) - throws com.sun.star.beans.UnknownPropertyException, - com.sun.star.beans.PropertyVetoException, - com.sun.star.lang.IllegalArgumentException, - com.sun.star.lang.WrappedTargetException - { + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.beans.PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, + com.sun.star.lang.WrappedTargetException { m_xPropertySetProxy.setPropertyValue(aPropertyName, aValue); } public Object getPropertyValue(String PropertyName) - throws com.sun.star.beans.UnknownPropertyException, - com.sun.star.lang.WrappedTargetException - { + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.lang.WrappedTargetException { return m_xPropertySetProxy.getPropertyValue(PropertyName); } public void addPropertyChangeListener( String aPropertyName, XPropertyChangeListener xListener) - throws com.sun.star.beans.UnknownPropertyException, - com.sun.star.lang.WrappedTargetException - { + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.lang.WrappedTargetException { m_xPropertySetProxy.addPropertyChangeListener(aPropertyName, xListener); } public void removePropertyChangeListener( String aPropertyName, XPropertyChangeListener aListener) - throws com.sun.star.beans.UnknownPropertyException, - com.sun.star.lang.WrappedTargetException - { + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.lang.WrappedTargetException { m_xPropertySetProxy.removePropertyChangeListener( aPropertyName, aListener); } public void addVetoableChangeListener( String PropertyName, XVetoableChangeListener aListener) - throws com.sun.star.beans.UnknownPropertyException, - com.sun.star.lang.WrappedTargetException - { + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.lang.WrappedTargetException { m_xPropertySetProxy.addVetoableChangeListener(PropertyName, aListener); } public void removeVetoableChangeListener( String PropertyName, XVetoableChangeListener aListener) - throws com.sun.star.beans.UnknownPropertyException, - com.sun.star.lang.WrappedTargetException - { + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.lang.WrappedTargetException { m_xPropertySetProxy.removeVetoableChangeListener( PropertyName, aListener); } - public java.lang.Object getByName( String aName ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException - { + public java.lang.Object getByName(String aName) throws + com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { // TODO needs implementing? throw new com.sun.star.uno.RuntimeException( - "getByName not implemented" ); + "getByName not implemented"); } - public String[] getElementNames() - { + public String[] getElementNames() { // TODO needs implementing? throw new com.sun.star.uno.RuntimeException( - "getElementNames not implemented" ); + "getElementNames not implemented"); } // Performs the getRegStatus functionality for the PkgMgr - public boolean hasByName( String aName ) { - return ((UnoPkgContainer)m_container).hasRegisteredUnoPkgContainer( aName ); + public boolean hasByName(String aName) { + return ((UnoPkgContainer)m_container).hasRegisteredUnoPkgContainer(aName); } - public com.sun.star.uno.Type getElementType() - { + public com.sun.star.uno.Type getElementType() { // TODO at the moment this returns void indicating // type is unknown should indicate XPackage ? do we implement XPackage return new Type(); } - public boolean hasElements() - { + public boolean hasElements() { // TODO needs implementing? throw new com.sun.star.uno.RuntimeException( - "hasElements not implemented" ); + "hasElements not implemented"); } - public void replaceByName( String aName, java.lang.Object aElement ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException - { + public void replaceByName(String aName, + java.lang.Object aElement) throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { // TODO needs implementing - if ( true ) - { + if (true) { throw new com.sun.star.uno.RuntimeException( - "replaceByName not implemented" ); + "replaceByName not implemented"); } } - public void insertByName( String aName, java.lang.Object aElement ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.container.ElementExistException, com.sun.star.lang.WrappedTargetException - { - LogUtils.DEBUG("Provider for " + language + " received register for package " + aName ); - XPackage newPackage = UnoRuntime.queryInterface( XPackage.class, aElement ); - if ( aName.length() == 0 ) - { - throw new com.sun.star.lang.IllegalArgumentException( "Empty name" ); + public void insertByName(String aName, + java.lang.Object aElement) throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.container.ElementExistException, + com.sun.star.lang.WrappedTargetException { + LogUtils.DEBUG("Provider for " + language + " received register for package " + + aName); + XPackage newPackage = UnoRuntime.queryInterface(XPackage.class, aElement); + + if (aName.length() == 0) { + throw new com.sun.star.lang.IllegalArgumentException("Empty name"); } - if ( newPackage == null ) - { - throw new com.sun.star.lang.IllegalArgumentException( "No package supplied" ); + + if (newPackage == null) { + throw new com.sun.star.lang.IllegalArgumentException("No package supplied"); } - ((UnoPkgContainer)m_container).processUnoPackage( newPackage, language ); + ((UnoPkgContainer)m_container).processUnoPackage(newPackage, language); } // de-register for library only !! - public void removeByName( String Name ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException - { - LogUtils.DEBUG("In ScriptProvider.removeByName() for " + Name + " this provider = " + language ); - ParcelContainer c = ((UnoPkgContainer)m_container).getRegisteredUnoPkgContainer( Name ); - if ( c != null ) - { + public void removeByName(String Name) throws + com.sun.star.container.NoSuchElementException, + com.sun.star.lang.WrappedTargetException { + LogUtils.DEBUG("In ScriptProvider.removeByName() for " + Name + + " this provider = " + language); + ParcelContainer c = ((UnoPkgContainer)m_container).getRegisteredUnoPkgContainer( + Name); + + if (c != null) { String libName; - if (Name.endsWith("/")) - { - String tmp = Name.substring( 0, Name.lastIndexOf('/') ); - libName = tmp.substring( tmp.lastIndexOf('/') + 1 ); - } - else - { - libName = Name.substring( Name.lastIndexOf('/') + 1 ); - } - LogUtils.DEBUG("Deregistering library " + libName ); - if ( c.removeParcel( libName ) ) - { - ((UnoPkgContainer)m_container).deRegisterPackageContainer( Name ); + + if (Name.endsWith("/")) { + String tmp = Name.substring(0, Name.lastIndexOf('/')); + libName = tmp.substring(tmp.lastIndexOf('/') + 1); + } else { + libName = Name.substring(Name.lastIndexOf('/') + 1); } - else - { - throw new com.sun.star.container.NoSuchElementException( libName + " cannot be removed from container." ); + + LogUtils.DEBUG("Deregistering library " + libName); + + if (c.removeParcel(libName)) { + ((UnoPkgContainer)m_container).deRegisterPackageContainer(Name); + } else { + throw new com.sun.star.container.NoSuchElementException( + libName + " cannot be removed from container."); } + } else { + throw new com.sun.star.container.NoSuchElementException( + Name + " doesn't exist for " + language); } - else - { - throw new com.sun.star.container.NoSuchElementException( Name + " doesn't exist for " + language ); - } + // TODO see if we want to remove the ParcelContainer is no Parcels/Libraries left } - private String getDocUrlFromModel( XModel document ) - { + private String getDocUrlFromModel(XModel document) { XTransientDocumentsDocumentContentFactory factory = null; - try - { + + try { factory = UnoRuntime.queryInterface( - XTransientDocumentsDocumentContentFactory.class, - m_xMultiComponentFactory.createInstanceWithContext( - "com.sun.star.frame.TransientDocumentsDocumentContentFactory", - m_xContext - ) - ); - } - catch (Exception ex) - { + XTransientDocumentsDocumentContentFactory.class, + m_xMultiComponentFactory.createInstanceWithContext( + "com.sun.star.frame.TransientDocumentsDocumentContentFactory", + m_xContext + ) + ); + } catch (Exception ex) { } - if ( factory == null ) - throw new com.sun.star.uno.RuntimeException( "ScriptProvider: unable to create a TDOC context factory.", this ); + if (factory == null) + throw new com.sun.star.uno.RuntimeException("ScriptProvider: unable to create a TDOC context factory.", + this); - try - { - XContent content = factory.createDocumentContent( document ); + try { + XContent content = factory.createDocumentContent(document); return content.getIdentifier().getContentIdentifier(); - } - catch (com.sun.star.lang.IllegalArgumentException ex) - { + } catch (com.sun.star.lang.IllegalArgumentException ex) { } LogUtils.DEBUG("unable to determine the model's TDOC URL"); return ""; } - private XModel getModelFromDocUrl( String docUrl ) - { - LogUtils.DEBUG("getModelFromDocUrl - searching for match for ->" + docUrl + "<-" ); + private XModel getModelFromDocUrl(String docUrl) { + LogUtils.DEBUG("getModelFromDocUrl - searching for match for ->" + docUrl + + "<-"); XModel xModel = null; - try - { - XUniversalContentBroker ucb = UniversalContentBroker.create( m_xContext ); - XContentIdentifier xCntId = ucb.createContentIdentifier( docUrl ); + try { + XUniversalContentBroker ucb = UniversalContentBroker.create(m_xContext); + + XContentIdentifier xCntId = ucb.createContentIdentifier(docUrl); - XContent xCnt = ucb.queryContent( xCntId ); + XContent xCnt = ucb.queryContent(xCntId); - XCommandProcessor xCmd = UnoRuntime.queryInterface( XCommandProcessor.class, xCnt ); + XCommandProcessor xCmd = UnoRuntime.queryInterface(XCommandProcessor.class, + xCnt); Property[] pArgs = new Property[ ] { new Property() }; @@ -697,19 +657,18 @@ public abstract class ScriptProvider command.Argument = pArgs; com.sun.star.ucb.XCommandEnvironment env = null ; - Object result = xCmd.execute( command, 0, env ) ; + Object result = xCmd.execute(command, 0, env) ; - XRow values = UnoRuntime.queryInterface( XRow.class, - result ); + XRow values = UnoRuntime.queryInterface(XRow.class, + result); - xModel = UnoRuntime.queryInterface( XModel.class, - values.getObject( 1, null ) ); - } - catch ( Exception ignore ) - { - LogUtils.DEBUG("Failed to get model exception " + ignore ); + xModel = UnoRuntime.queryInterface(XModel.class, + values.getObject(1, null)); + } catch (Exception ignore) { + LogUtils.DEBUG("Failed to get model exception " + ignore); } + return xModel; } diff --git a/scripting/java/com/sun/star/script/framework/provider/SwingInvocation.java b/scripting/java/com/sun/star/script/framework/provider/SwingInvocation.java index 74e95546af35..1a0e2ff4f14d 100644 --- a/scripting/java/com/sun/star/script/framework/provider/SwingInvocation.java +++ b/scripting/java/com/sun/star/script/framework/provider/SwingInvocation.java @@ -28,8 +28,10 @@ public final class SwingInvocation { public static void invoke(final Runnable doRun) { new Thread("SwingInvocation") { @Override - public void run() { SwingUtilities.invokeLater(doRun); } - }.start(); + public void run() { + SwingUtilities.invokeLater(doRun); + } + } .start(); } private SwingInvocation() {} diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java index bd8f01c9193a..f1f8e09561cb 100644 --- a/scripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java +++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java @@ -55,14 +55,13 @@ public class PlainSourceView extends JScrollPane so we don't get a storm of DocumentEvents during loading */ ta.getDocument().removeDocumentListener(this); - if (!isModified) - { + if (!isModified) { int pos = ta.getCaretPosition(); ta.setText(model.getText()); + try { ta.setCaretPosition(pos); - } - catch (IllegalArgumentException iae) { + } catch (IllegalArgumentException iae) { // do nothing and allow JTextArea to set it's own position } } @@ -72,8 +71,7 @@ public class PlainSourceView extends JScrollPane int line = ta.getLineStartOffset(model.getCurrentPosition()); Rectangle rect = ta.modelToView(line); ta.scrollRectToVisible(rect); - } - catch (Exception e) { + } catch (Exception e) { // couldn't scroll to line, do nothing } @@ -164,6 +162,7 @@ class GlyphGutter extends JComponent { int lineCount = textArea.getLineCount() + 1; String dummy = Integer.toString(lineCount); + if (dummy.length() < 2) { dummy = DUMMY_STRING; } @@ -195,6 +194,7 @@ class GlyphGutter extends JComponent { int startLine = clip.y / h; int endLine = (clip.y + clip.height) / h + 1; int width = getWidth(); + if (endLine > lineCount) { endLine = lineCount; } @@ -221,12 +221,15 @@ class GlyphGutter extends JComponent { int dy = y; arrow.addPoint(dx, dy + 3); arrow.addPoint(dx + 5, dy + 3); + for (x = dx + 5; x <= dx + 10; x++, y++) { arrow.addPoint(x, y); } + for (x = dx + 9; x >= dx + 5; x--, y++) { arrow.addPoint(x, y); } + arrow.addPoint(dx + 5, dy + 7); arrow.addPoint(dx, dy + 7); diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java index c0cfd1f6a3f0..5991d2285e42 100644 --- a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java +++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java @@ -43,8 +43,7 @@ import com.sun.star.script.framework.container.ScriptMetaData; import com.sun.star.script.framework.provider.ClassLoaderFactory; public class ScriptEditorForBeanShell - implements ScriptEditor, ActionListener -{ + implements ScriptEditor, ActionListener { private JFrame frame; private String filename; @@ -59,7 +58,8 @@ public class ScriptEditorForBeanShell private static ScriptEditorForBeanShell theScriptEditorForBeanShell; // global list of ScriptEditors, key is URL of file being edited - private static Map<URL,ScriptEditorForBeanShell> BEING_EDITED = new HashMap<URL,ScriptEditorForBeanShell>(); + private static Map<URL, ScriptEditorForBeanShell> BEING_EDITED = new + HashMap<URL, ScriptEditorForBeanShell>(); // template for new BeanShell scripts private static String BSHTEMPLATE; @@ -74,6 +74,7 @@ public class ScriptEditorForBeanShell StringBuilder buf = new StringBuilder(); byte[] b = new byte[1024]; int len; + while ((len = in.read(b)) != -1) { buf.append(new String(b, 0, len)); } @@ -81,11 +82,9 @@ public class ScriptEditorForBeanShell in.close(); BSHTEMPLATE = buf.toString(); - } - catch (IOException ioe) { + } catch (IOException ioe) { BSHTEMPLATE = "// BeanShell script"; - } - catch (Exception e) { + } catch (Exception e) { BSHTEMPLATE = "// BeanShell script"; } } @@ -93,13 +92,13 @@ public class ScriptEditorForBeanShell /** * Returns the global ScriptEditorForBeanShell instance. */ - public static synchronized ScriptEditorForBeanShell getEditor() - { - if (theScriptEditorForBeanShell == null) - { + + public static synchronized ScriptEditorForBeanShell getEditor() { + if (theScriptEditorForBeanShell == null) { theScriptEditorForBeanShell = new ScriptEditorForBeanShell(); } + return theScriptEditorForBeanShell; } @@ -111,8 +110,7 @@ public class ScriptEditorForBeanShell * @return The ScriptEditorForBeanShell associated with * the given URL if one exists, otherwise null. */ - public static ScriptEditorForBeanShell getEditor(URL url) - { + public static ScriptEditorForBeanShell getEditor(URL url) { synchronized (BEING_EDITED) { return BEING_EDITED.get(url); } @@ -122,8 +120,7 @@ public class ScriptEditorForBeanShell * Returns whether or not the script source being edited in this * ScriptEditorForBeanShell has been modified */ - public boolean isModified() - { + public boolean isModified() { return view.isModified(); } @@ -132,8 +129,7 @@ public class ScriptEditorForBeanShell * * @return The text displayed in this ScriptEditorForBeanShell */ - public String getText() - { + public String getText() { return view.getText(); } @@ -160,9 +156,8 @@ public class ScriptEditorForBeanShell * Indicates the line where error occurred * */ - public void indicateErrorLine( int lineNum ) - { - model.indicateErrorLine( lineNum ); + public void indicateErrorLine(int lineNum) { + model.indicateErrorLine(lineNum); } /** * Executes the script edited by the editor @@ -170,7 +165,7 @@ public class ScriptEditorForBeanShell */ public Object execute() throws Exception { frame.toFront(); - return model.execute( context, cl ); + return model.execute(context, cl); } /** * Opens an editor window for the specified ScriptMetaData. @@ -181,41 +176,44 @@ public class ScriptEditorForBeanShell * @param entry The metadata describing the script */ public void edit(final XScriptContext context, ScriptMetaData entry) { - if (entry != null ) { + if (entry != null) { try { ClassLoader cl = null; + try { - cl = ClassLoaderFactory.getURLClassLoader( entry ); - } - catch (Exception ignore) // TODO re-examine error handling - { + cl = ClassLoaderFactory.getURLClassLoader(entry); + } catch (Exception ignore) { // TODO re-examine error handling } + final ClassLoader theCl = cl; String sUrl = entry.getParcelLocation(); - if ( !sUrl.endsWith( "/" ) ) - { + + if (!sUrl.endsWith("/")) { sUrl += "/"; } + sUrl += entry.getLanguageName(); final URL url = entry.getSourceURL(); SwingInvocation.invoke( - new Runnable() { - public void run() { - ScriptEditorForBeanShell editor; - synchronized (BEING_EDITED) { - editor = BEING_EDITED.get(url); - if (editor == null) { - editor = new ScriptEditorForBeanShell( - context, theCl, url); - BEING_EDITED.put(url, editor); - } + new Runnable() { + public void run() { + ScriptEditorForBeanShell editor; + + synchronized (BEING_EDITED) { + editor = BEING_EDITED.get(url); + + if (editor == null) { + editor = new ScriptEditorForBeanShell( + context, theCl, url); + BEING_EDITED.put(url, editor); } - editor.frame.toFront(); } - }); - } - catch (IOException ioe) { - showErrorMessage( "Error loading file: " + ioe.getMessage() ); + + editor.frame.toFront(); + } + }); + } catch (IOException ioe) { + showErrorMessage("Error loading file: " + ioe.getMessage()); } } } @@ -224,16 +222,16 @@ public class ScriptEditorForBeanShell } private ScriptEditorForBeanShell(XScriptContext context, ClassLoader cl, - URL url) - { + URL url) { this.context = context; this.scriptURL = url; this.model = new ScriptSourceModel(url); this.filename = url.getFile(); this.cl = cl; + try { Class<?> c = Class.forName( - "org.openoffice.netbeans.editor.NetBeansSourceView"); + "org.openoffice.netbeans.editor.NetBeansSourceView"); Class<?>[] types = new Class[] { ScriptSourceModel.class }; @@ -242,15 +240,12 @@ public class ScriptEditorForBeanShell if (ctor != null) { Object[] args = new Object[] { this.model }; this.view = (ScriptSourceView) ctor.newInstance(args); - } - else { + } else { this.view = new PlainSourceView(model); } - } - catch (java.lang.Error err) { + } catch (java.lang.Error err) { this.view = new PlainSourceView(model); - } - catch (Exception e) { + } catch (Exception e) { this.view = new PlainSourceView(model); } @@ -261,7 +256,7 @@ public class ScriptEditorForBeanShell private void showErrorMessage(String message) { JOptionPane.showMessageDialog(frame, message, - "Error", JOptionPane.ERROR_MESSAGE); + "Error", JOptionPane.ERROR_MESSAGE); } private void initUI() { @@ -269,13 +264,12 @@ public class ScriptEditorForBeanShell frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowListener( - new WindowAdapter() - { - @Override - public void windowClosing(WindowEvent e) { - doClose(); - } + new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + doClose(); } + } ); String[] labels = {"Run", "Clear", "Save", "Close"}; @@ -286,6 +280,7 @@ public class ScriptEditorForBeanShell JButton b = new JButton(label); b.addActionListener(this); p.add(b); + if (label.equals("Save") && filename == null) { b.setEnabled(false); } @@ -301,23 +296,21 @@ public class ScriptEditorForBeanShell private void doClose() { if (view.isModified()) { int result = JOptionPane.showConfirmDialog(frame, - "The script has been modified. " + - "Do you want to save the changes?"); + "The script has been modified. " + + "Do you want to save the changes?"); - if (result == JOptionPane.CANCEL_OPTION) - { + if (result == JOptionPane.CANCEL_OPTION) { // don't close the window, just return return; - } - else if (result == JOptionPane.YES_OPTION) - { + } else if (result == JOptionPane.YES_OPTION) { boolean saveSuccess = saveTextArea(); - if (!saveSuccess) - { + + if (!saveSuccess) { return; } } } + frame.dispose(); shutdown(); } @@ -330,43 +323,40 @@ public class ScriptEditorForBeanShell } OutputStream fos = null; + try { String s = view.getText(); fos = scriptURL.openConnection().getOutputStream(); - if ( fos != null) { + + if (fos != null) { fos.write(s.getBytes()); - } - else - { + } else { showErrorMessage( - "Error saving script: Could not open stream for file" ); + "Error saving script: Could not open stream for file"); result = false; } + view.setModified(false); - } - catch (IOException ioe) { - showErrorMessage( "Error saving script: " + ioe.getMessage() ); - result = false; - } - catch (Exception e) { - showErrorMessage( "Error saving script: " + e.getMessage() ); - result = false; - } - finally { + } catch (IOException ioe) { + showErrorMessage("Error saving script: " + ioe.getMessage()); + result = false; + } catch (Exception e) { + showErrorMessage("Error saving script: " + e.getMessage()); + result = false; + } finally { if (fos != null) { try { fos.flush(); fos.close(); - } - catch (IOException ignore) { + } catch (IOException ignore) { } } } + return result; } - private void shutdown() - { + private void shutdown() { synchronized (BEING_EDITED) { BEING_EDITED.remove(scriptURL); } @@ -374,21 +364,16 @@ public class ScriptEditorForBeanShell public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Run")) { - try - { + try { execute(); - } - catch (Exception invokeException ) { + } catch (Exception invokeException) { showErrorMessage(invokeException.getMessage()); } - } - else if (e.getActionCommand().equals("Close")) { + } else if (e.getActionCommand().equals("Close")) { doClose(); - } - else if (e.getActionCommand().equals("Save")) { + } else if (e.getActionCommand().equals("Save")) { saveTextArea(); - } - else if (e.getActionCommand().equals("Clear")) { + } else if (e.getActionCommand().equals("Clear")) { view.clear(); } } diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java index da534d602d57..1f56cbe325d4 100644 --- a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java +++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java @@ -47,42 +47,36 @@ import com.sun.star.script.framework.provider.*; import com.sun.star.script.framework.log.*; import com.sun.star.script.framework.container.ScriptMetaData; -public class ScriptProviderForBeanShell -{ - public static class ScriptProviderForBeanShell_2 extends ScriptProvider - { - public ScriptProviderForBeanShell_2(XComponentContext ctx) - { - super (ctx, "BeanShell"); +public class ScriptProviderForBeanShell { + public static class ScriptProviderForBeanShell_2 extends ScriptProvider { + public ScriptProviderForBeanShell_2(XComponentContext ctx) { + super(ctx, "BeanShell"); } @Override - public XScript getScript( /*IN*/String scriptURI ) - throws com.sun.star.uno.RuntimeException, - ScriptFrameworkErrorException - { - ScriptMetaData scriptData = getScriptData( scriptURI ); - try - { - ScriptImpl script = new ScriptImpl( m_xContext, scriptData, m_xModel, m_xInvocContext ); + public XScript getScript(/*IN*/String scriptURI) + throws com.sun.star.uno.RuntimeException, + ScriptFrameworkErrorException { + ScriptMetaData scriptData = getScriptData(scriptURI); + + try { + ScriptImpl script = new ScriptImpl(m_xContext, scriptData, m_xModel, + m_xInvocContext); return script; - } - catch ( com.sun.star.uno.RuntimeException re ) - { - throw new ScriptFrameworkErrorException( "Failed to create script object: " + re.getMessage(), - null, scriptData.getLanguageName(), language, ScriptFrameworkErrorType.UNKNOWN ); + } catch (com.sun.star.uno.RuntimeException re) { + throw new ScriptFrameworkErrorException("Failed to create script object: " + + re.getMessage(), + null, scriptData.getLanguageName(), language, ScriptFrameworkErrorType.UNKNOWN); } } @Override - public boolean hasScriptEditor() - { + public boolean hasScriptEditor() { return true; } @Override - public ScriptEditor getScriptEditor() - { + public ScriptEditor getScriptEditor() { return ScriptEditorForBeanShell.getEditor(); } } @@ -99,263 +93,249 @@ public class ScriptProviderForBeanShell * the component * @see com.sun.star.comp.loader.JavaLoader */ - public static XSingleServiceFactory __getServiceFactory( String implName, + public static XSingleServiceFactory __getServiceFactory(String implName, XMultiServiceFactory multiFactory, - XRegistryKey regKey ) - { + XRegistryKey regKey) { XSingleServiceFactory xSingleServiceFactory = null; - if ( implName.equals( ScriptProviderForBeanShell.ScriptProviderForBeanShell_2.class.getName() ) ) - { + if (implName.equals( + ScriptProviderForBeanShell.ScriptProviderForBeanShell_2.class.getName())) { xSingleServiceFactory = FactoryHelper.getServiceFactory( - ScriptProviderForBeanShell.ScriptProviderForBeanShell_2.class, - "com.sun.star.script.provider.ScriptProviderForBeanShell", - multiFactory, - regKey ); + ScriptProviderForBeanShell.ScriptProviderForBeanShell_2.class, + "com.sun.star.script.provider.ScriptProviderForBeanShell", + multiFactory, + regKey); } return xSingleServiceFactory; } } -class ScriptImpl implements XScript -{ +class ScriptImpl implements XScript { private ScriptMetaData metaData; private XComponentContext m_xContext; private XMultiComponentFactory m_xMultiComponentFactory; private XModel m_xModel; private XScriptInvocationContext m_xInvocContext; - ScriptImpl( XComponentContext ctx, ScriptMetaData metaData, XModel xModel, - XScriptInvocationContext xContext ) throws com.sun.star.uno.RuntimeException - { + ScriptImpl(XComponentContext ctx, ScriptMetaData metaData, XModel xModel, + XScriptInvocationContext xContext) throws com.sun.star.uno.RuntimeException { this.metaData = metaData; this.m_xContext = ctx; this.m_xModel = xModel; this.m_xInvocContext = xContext; - try - { + try { this.m_xMultiComponentFactory = m_xContext.getServiceManager(); - } - catch ( Exception e ) - { - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + } catch (Exception e) { + LogUtils.DEBUG(LogUtils.getTrace(e)); throw new com.sun.star.uno.RuntimeException( "Error constructing ScriptImpl [beanshell]: " - + e.getMessage() ); + + e.getMessage()); } - LogUtils.DEBUG("ScriptImpl [beanshell] script data = " + metaData ); + LogUtils.DEBUG("ScriptImpl [beanshell] script data = " + metaData); } - /** - * documentStorageID and document reference - * for use in script name resolving - * - * @param aParams All parameters; pure, out params are - * undefined in sequence, i.e., the value - * has to be ignored by the callee - * - * @param aOutParamIndex Out indices - * - * @param aOutParam Out parameters - * - * @return The value returned from the function - * being invoked - * - * @throws IllegalArgumentException If there is no matching script name - * - * @throws InvocationTargetException If the running script throws - * an exception this information - * is captured and rethrown as - * this exception type. - */ - - public Object invoke( /*IN*/Object[] aParams, - /*OUT*/short[][] aOutParamIndex, - /*OUT*/Object[][] aOutParam ) - throws ScriptFrameworkErrorException, - InvocationTargetException - { - // Initialise the out parameters - not used at the moment - aOutParamIndex[0] = new short[0]; - aOutParam[0] = new Object[0]; - - - ClassLoader cl = null; - URL sourceUrl = null; - try { - cl = ClassLoaderFactory.getURLClassLoader( metaData ); - sourceUrl = metaData.getSourceURL(); - } - catch ( java.net.MalformedURLException mfu ) - { - // Framework error - throw new ScriptFrameworkErrorException( - mfu.getMessage(), null, - metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.MALFORMED_URL ); - } - // Set class loader to be used for class files - // and jar files - Thread.currentThread().setContextClassLoader(cl); - Interpreter interpreter = new Interpreter(); - - interpreter.getNameSpace().clear(); - // Set class loader to be used by interpreter - // to look for classes by source e.g. interpreter - // will use this classloader to search classpath - // for source file ( bla.java ) on import or reference - interpreter.setClassLoader(cl); - try { - interpreter.set("XSCRIPTCONTEXT", - ScriptContext.createContext(m_xModel, m_xInvocContext, - m_xContext, m_xMultiComponentFactory)); - - interpreter.set("ARGUMENTS", aParams); - } - catch (bsh.EvalError e) { - // Framework error setting up context - throw new ScriptFrameworkErrorException( - e.getMessage(), null, - metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.UNKNOWN ); - } - - try { - Object result; + /** + * documentStorageID and document reference + * for use in script name resolving + * + * @param aParams All parameters; pure, out params are + * undefined in sequence, i.e., the value + * has to be ignored by the callee + * + * @param aOutParamIndex Out indices + * + * @param aOutParam Out parameters + * + * @return The value returned from the function + * being invoked + * + * @throws IllegalArgumentException If there is no matching script name + * + * @throws InvocationTargetException If the running script throws + * an exception this information + * is captured and rethrown as + * this exception type. + */ - ScriptEditorForBeanShell editor = - ScriptEditorForBeanShell.getEditor( - sourceUrl ); + public Object invoke(/*IN*/Object[] aParams, + /*OUT*/short[][] aOutParamIndex, + /*OUT*/Object[][] aOutParam) + throws ScriptFrameworkErrorException, + InvocationTargetException { + // Initialise the out parameters - not used at the moment + aOutParamIndex[0] = new short[0]; + aOutParam[0] = new Object[0]; + + + ClassLoader cl = null; + URL sourceUrl = null; + + try { + cl = ClassLoaderFactory.getURLClassLoader(metaData); + sourceUrl = metaData.getSourceURL(); + } catch (java.net.MalformedURLException mfu) { + // Framework error + throw new ScriptFrameworkErrorException( + mfu.getMessage(), null, + metaData.getLanguageName(), metaData.getLanguage(), + ScriptFrameworkErrorType.MALFORMED_URL); + } - if ( editor != null ) - { - result = editor.execute(); + // Set class loader to be used for class files + // and jar files + Thread.currentThread().setContextClassLoader(cl); + Interpreter interpreter = new Interpreter(); + + interpreter.getNameSpace().clear(); + // Set class loader to be used by interpreter + // to look for classes by source e.g. interpreter + // will use this classloader to search classpath + // for source file ( bla.java ) on import or reference + interpreter.setClassLoader(cl); + + try { + interpreter.set("XSCRIPTCONTEXT", + ScriptContext.createContext(m_xModel, m_xInvocContext, + m_xContext, m_xMultiComponentFactory)); + + interpreter.set("ARGUMENTS", aParams); + } catch (bsh.EvalError e) { + // Framework error setting up context + throw new ScriptFrameworkErrorException( + e.getMessage(), null, + metaData.getLanguageName(), metaData.getLanguage(), + ScriptFrameworkErrorType.UNKNOWN); + } - if (result == null) - { - return new Any(new Type(), null); - } - return result; - } + try { + Object result; - metaData.loadSource(); - String source = metaData.getSource(); + ScriptEditorForBeanShell editor = + ScriptEditorForBeanShell.getEditor( + sourceUrl); - if ( source == null || source.length() == 0 ) - { - throw new ScriptFrameworkErrorException( - "Failed to read script", null, - metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.NO_SUCH_SCRIPT ); - } - result = interpreter.eval( source ); + if (editor != null) { + result = editor.execute(); - if (result == null) - { + if (result == null) { return new Any(new Type(), null); } + return result; } - catch ( bsh.ParseException pe ) - { - throw new InvocationTargetException( "Beanshell failed to parse " + metaData.getLanguageName(), null, processBshException( pe, metaData.getLanguageName() ) ); - } - catch ( bsh.TargetError te ) - { - throw new InvocationTargetException( "Beanshell uncaught exception for " + metaData.getLanguageName(), null, processBshException( te, metaData.getLanguageName() ) ); - } - catch ( bsh.EvalError ex ) - { - throw new InvocationTargetException( "Beanshell error for " + metaData.getLanguageName(), null, processBshException( ex, metaData.getLanguageName() ) ); - } - catch ( Exception e ) - { + + metaData.loadSource(); + String source = metaData.getSource(); + + if (source == null || source.length() == 0) { throw new ScriptFrameworkErrorException( "Failed to read script", null, metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.UNKNOWN ); + ScriptFrameworkErrorType.NO_SUCH_SCRIPT); + } + + result = interpreter.eval(source); + + if (result == null) { + return new Any(new Type(), null); } + + return result; + } catch (bsh.ParseException pe) { + throw new InvocationTargetException("Beanshell failed to parse " + + metaData.getLanguageName(), null, processBshException(pe, + metaData.getLanguageName())); + } catch (bsh.TargetError te) { + throw new InvocationTargetException("Beanshell uncaught exception for " + + metaData.getLanguageName(), null, processBshException(te, + metaData.getLanguageName())); + } catch (bsh.EvalError ex) { + throw new InvocationTargetException("Beanshell error for " + + metaData.getLanguageName(), null, processBshException(ex, + metaData.getLanguageName())); + } catch (Exception e) { + throw new ScriptFrameworkErrorException( + "Failed to read script", null, + metaData.getLanguageName(), metaData.getLanguage(), + ScriptFrameworkErrorType.UNKNOWN); } - private void raiseEditor( int lineNum ) - { - try - { - URL sourceUrl = metaData.getSourceURL(); - ScriptEditorForBeanShell editor = ScriptEditorForBeanShell.getEditor( sourceUrl ); - if ( editor == null ) - { - editor = ScriptEditorForBeanShell.getEditor(); - editor.edit( - ScriptContext.createContext(m_xModel, m_xInvocContext, - m_xContext, m_xMultiComponentFactory), metaData ); - editor = ScriptEditorForBeanShell.getEditor( sourceUrl ); - } - if ( editor != null ) - { - editor.indicateErrorLine( lineNum ); - } + } + private void raiseEditor(int lineNum) { + try { + URL sourceUrl = metaData.getSourceURL(); + ScriptEditorForBeanShell editor = ScriptEditorForBeanShell.getEditor(sourceUrl); + + if (editor == null) { + editor = ScriptEditorForBeanShell.getEditor(); + editor.edit( + ScriptContext.createContext(m_xModel, m_xInvocContext, + m_xContext, m_xMultiComponentFactory), metaData); + editor = ScriptEditorForBeanShell.getEditor(sourceUrl); } - catch( Exception ignore ) - { + + if (editor != null) { + editor.indicateErrorLine(lineNum); } + } catch (Exception ignore) { } + } - private ScriptErrorRaisedException processBshException( bsh.EvalError e, String script ) - { - LogUtils.DEBUG("Beanshell error RAW message " + e.getMessage()); - String message = e.getMessage(); - int usefulInfoIndex = message.lastIndexOf("\' :" ); - int lineNum = e.getErrorLineNumber(); + private ScriptErrorRaisedException processBshException(bsh.EvalError e, + String script) { + LogUtils.DEBUG("Beanshell error RAW message " + e.getMessage()); + String message = e.getMessage(); + int usefulInfoIndex = message.lastIndexOf("\' :"); + int lineNum = e.getErrorLineNumber(); + + raiseEditor(lineNum); + + if (usefulInfoIndex > -1) { + message = message.substring(usefulInfoIndex + 2); + } - raiseEditor( lineNum ); + if (e instanceof bsh.TargetError) { + LogUtils.DEBUG("got instance of TargetError"); - if ( usefulInfoIndex > -1 ) - { - message = message.substring( usefulInfoIndex + 2 ); + if (usefulInfoIndex == -1) { + message = ((bsh.TargetError)e).getTarget().getMessage(); } - if ( e instanceof bsh.TargetError ) - { - LogUtils.DEBUG("got instance of TargetError"); - if ( usefulInfoIndex == -1 ) - { - message = ( ( bsh.TargetError)e ).getTarget().getMessage(); - } - String wrappedException = ""; - String full = e.toString(); - int index = full.indexOf( "Target exception:" ); - if ( index > -1 ) - { - String toParse = full.substring( index ); - LogUtils.DEBUG("About to parse " + toParse ); - StringTokenizer tokenizer = new StringTokenizer( full.substring( index ),":" ); - if ( tokenizer.countTokens() > 2 ) - { - LogUtils.DEBUG("First token = " + (String)tokenizer.nextElement()); - wrappedException = (String)tokenizer.nextElement(); - LogUtils.DEBUG("wrapped exception = = " + wrappedException ); - } + + String wrappedException = ""; + String full = e.toString(); + int index = full.indexOf("Target exception:"); + + if (index > -1) { + String toParse = full.substring(index); + LogUtils.DEBUG("About to parse " + toParse); + StringTokenizer tokenizer = new StringTokenizer(full.substring(index), ":"); + + if (tokenizer.countTokens() > 2) { + LogUtils.DEBUG("First token = " + (String)tokenizer.nextElement()); + wrappedException = (String)tokenizer.nextElement(); + LogUtils.DEBUG("wrapped exception = = " + wrappedException); } - ScriptExceptionRaisedException se = new ScriptExceptionRaisedException( message); - se.lineNum = lineNum; - se.scriptName = script; - se.exceptionType = wrappedException; - se.language = "BeanShell"; - LogUtils.DEBUG("UnCaught Exception error: " ); - LogUtils.DEBUG("\tscript: " + script ); - LogUtils.DEBUG("\tline: " + lineNum ); - LogUtils.DEBUG("\twrapped exception: " + wrappedException ); - LogUtils.DEBUG("\tmessage: " + message ); - return se; - } - else - { - LogUtils.DEBUG("Error or ParseError Exception error: " ); - LogUtils.DEBUG("\tscript: " + script ); - LogUtils.DEBUG("\tline: " + lineNum ); - LogUtils.DEBUG("\tmessage: " + message ); - return new ScriptErrorRaisedException( message, null, script, "BeanShell", lineNum ); } + + ScriptExceptionRaisedException se = new ScriptExceptionRaisedException(message); + se.lineNum = lineNum; + se.scriptName = script; + se.exceptionType = wrappedException; + se.language = "BeanShell"; + LogUtils.DEBUG("UnCaught Exception error: "); + LogUtils.DEBUG("\tscript: " + script); + LogUtils.DEBUG("\tline: " + lineNum); + LogUtils.DEBUG("\twrapped exception: " + wrappedException); + LogUtils.DEBUG("\tmessage: " + message); + return se; + } else { + LogUtils.DEBUG("Error or ParseError Exception error: "); + LogUtils.DEBUG("\tscript: " + script); + LogUtils.DEBUG("\tline: " + lineNum); + LogUtils.DEBUG("\tmessage: " + message); + return new ScriptErrorRaisedException(message, null, script, "BeanShell", + lineNum); } + } } diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java index ef4719ef1a7d..9954c6b550c9 100644 --- a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java +++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java @@ -30,7 +30,7 @@ public class ScriptSourceModel { private URL file = null; private ScriptSourceView view = null; - public ScriptSourceModel(URL file ) { + public ScriptSourceModel(URL file) { this.file = file; } @@ -40,14 +40,14 @@ public class ScriptSourceModel { byte[] contents = new byte[1024]; int len; + while ((len = in.read(contents, 0, 1024)) != -1) { buf.append(new String(contents, 0, len)); } try { in.close(); - } - catch (IOException ignore) { + } catch (IOException ignore) { } return buf.toString(); @@ -58,8 +58,7 @@ public class ScriptSourceModel { try { result = load(); - } - catch (IOException ioe) { + } catch (IOException ioe) { // do nothing, empty string will be returned } @@ -74,52 +73,51 @@ public class ScriptSourceModel { this.view = view; } - public Object execute(final XScriptContext context, ClassLoader cl ) - throws Exception - { - if ( cl != null ) - { - // sets this threads class loader - // hopefully any threads spawned by this - // will inherit this cl - // this enables any class files imported - // from the interpreter to be loaded - // note: setting the classloader on the - // interpreter has a slightly different - // meaning in that the classloader for - // the interpreter seems only to look for - // source files ( bla.java ) in the classpath - Thread.currentThread().setContextClassLoader(cl); - } - bsh.Interpreter interpreter = new bsh.Interpreter(); - if ( cl != null ) - { - // additionally set class loader on the interpreter - // to allow it to load java classes defined in source - // files e.g. bla.java - interpreter.getNameSpace().clear(); - } - - - // reset position - currentPosition = -1; - view.update(); - - interpreter.set("XSCRIPTCONTEXT", context); - interpreter.set("ARGUMENTS", new Object[0]); - - Object result; - if (view.isModified()) { - result = interpreter.eval(view.getText()); - } - else { - result = interpreter.eval(getText()); - } + public Object execute(final XScriptContext context, ClassLoader cl) + throws Exception { + if (cl != null) { + // sets this threads class loader + // hopefully any threads spawned by this + // will inherit this cl + // this enables any class files imported + // from the interpreter to be loaded + // note: setting the classloader on the + // interpreter has a slightly different + // meaning in that the classloader for + // the interpreter seems only to look for + // source files ( bla.java ) in the classpath + Thread.currentThread().setContextClassLoader(cl); + } + + bsh.Interpreter interpreter = new bsh.Interpreter(); + + if (cl != null) { + // additionally set class loader on the interpreter + // to allow it to load java classes defined in source + // files e.g. bla.java + interpreter.getNameSpace().clear(); + } + + + // reset position + currentPosition = -1; + view.update(); + + interpreter.set("XSCRIPTCONTEXT", context); + interpreter.set("ARGUMENTS", new Object[0]); + + Object result; + + if (view.isModified()) { + result = interpreter.eval(view.getText()); + } else { + result = interpreter.eval(getText()); + } + return result; } - public void indicateErrorLine( int lineNum ) - { - System.out.println("Beanshell indicateErrorLine " + lineNum ); + public void indicateErrorLine(int lineNum) { + System.out.println("Beanshell indicateErrorLine " + lineNum); currentPosition = lineNum - 1; view.update(); } diff --git a/scripting/java/com/sun/star/script/framework/provider/java/Resolver.java b/scripting/java/com/sun/star/script/framework/provider/java/Resolver.java index af35e3e4c233..ab5103070210 100644 --- a/scripting/java/com/sun/star/script/framework/provider/java/Resolver.java +++ b/scripting/java/com/sun/star/script/framework/provider/java/Resolver.java @@ -32,7 +32,7 @@ public interface Resolver { * @param c A Class * @return The ScriptProxy value */ - ScriptProxy getProxy( ScriptDescriptor sd, Class<?> c ) + ScriptProxy getProxy(ScriptDescriptor sd, Class<?> c) throws NoSuchMethodException; } diff --git a/scripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java b/scripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java index 66d25aa6ccdd..cd2e417695b6 100644 --- a/scripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java +++ b/scripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java @@ -26,13 +26,12 @@ import java.util.StringTokenizer; * The <code>ScriptDescriptor</code> object is used to store the search * criteria that should be used for finding a particular script */ -public class ScriptDescriptor -{ +public class ScriptDescriptor { private String m_name; private String m_methodName; private String m_className; private List<String> m_classpath; - private ArrayList<Class<?>> m_argumentTypes = new ArrayList<Class<?>>( 11 ); + private ArrayList<Class<?>> m_argumentTypes = new ArrayList<Class<?>>(11); /** * Constructs a ScriptDescriptor for the given name @@ -40,19 +39,17 @@ public class ScriptDescriptor * @param name Script Name * @exception IllegalArgumentException if the given name does not contain a "." */ - public ScriptDescriptor( String name ) - throws IllegalArgumentException - { - int idx = name.lastIndexOf( '.' ); - - if ( idx == -1 ) - { - throw new IllegalArgumentException( "Invalid method name" ); + public ScriptDescriptor(String name) + throws IllegalArgumentException { + int idx = name.lastIndexOf('.'); + + if (idx == -1) { + throw new IllegalArgumentException("Invalid method name"); } this.m_name = name; - this.m_methodName = name.substring( idx + 1 ); - this.m_className = name.substring( 0, idx ); + this.m_methodName = name.substring(idx + 1); + this.m_className = name.substring(0, idx); } /** @@ -60,8 +57,7 @@ public class ScriptDescriptor * * @return The Script Name value */ - public String getName() - { + public String getName() { return m_name; } @@ -70,8 +66,7 @@ public class ScriptDescriptor * * @return The Script Name value */ - public String getClassName() - { + public String getClassName() { return m_className; } @@ -81,8 +76,7 @@ public class ScriptDescriptor * * @return The methodName value */ - public String getMethodName() - { + public String getMethodName() { return m_methodName; } @@ -92,12 +86,11 @@ public class ScriptDescriptor * * @param classpath The new classpath value */ - public void setClasspath( String classpath ) - { - StringTokenizer stk = new StringTokenizer( classpath, ":" ); - while( stk.hasMoreElements() ) - { - this.m_classpath.add( (String) stk.nextElement() ); + public void setClasspath(String classpath) { + StringTokenizer stk = new StringTokenizer(classpath, ":"); + + while (stk.hasMoreElements()) { + this.m_classpath.add((String) stk.nextElement()); } } @@ -106,8 +99,7 @@ public class ScriptDescriptor * * @param classpath The new classpath value */ - public void setClasspath( List<String> classpath ) - { + public void setClasspath(List<String> classpath) { this.m_classpath = classpath; } @@ -117,8 +109,7 @@ public class ScriptDescriptor * * @return The classpath value */ - public List<String> getClasspath() - { + public List<String> getClasspath() { return m_classpath; } @@ -129,9 +120,9 @@ public class ScriptDescriptor * * @param clazz The feature to be added to the ArgumentType attribute */ - public synchronized void addArgumentType( Class<?> clazz ) - { - m_argumentTypes.add( clazz ); + + public synchronized void addArgumentType(Class<?> clazz) { + m_argumentTypes.add(clazz); } @@ -146,11 +137,11 @@ public class ScriptDescriptor * * @return The argumentTypes value */ + public synchronized Class<?>[] - getArgumentTypes() - { - if ( m_argumentTypes.size() > 0 ) - return m_argumentTypes.toArray( new Class[ m_argumentTypes.size() ] ); + getArgumentTypes() { + if (m_argumentTypes.size() > 0) + return m_argumentTypes.toArray(new Class[ m_argumentTypes.size() ]); else return null; } @@ -163,24 +154,22 @@ public class ScriptDescriptor * @return The scriptName including the parameters. */ @Override - public String toString() - { - StringBuilder description = new StringBuilder( m_name ); + public String toString() { + StringBuilder description = new StringBuilder(m_name); Class<?>[] types = getArgumentTypes(); - description.append( " (" ); + description.append(" ("); - if ( types != null ) - { - for ( int i = 0; i < types.length - 1; i++ ) - { - description.append( types[ i ].getName() ); - description.append( ", " ); + if (types != null) { + for (int i = 0; i < types.length - 1; i++) { + description.append(types[ i ].getName()); + description.append(", "); } - description.append( types[ types.length - 1 ].getName() ); + description.append(types[ types.length - 1 ].getName()); } - description.append( ")" ); + + description.append(")"); return description.toString(); } diff --git a/scripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java index 9bac3b7e0e40..b09c530b570d 100644 --- a/scripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java +++ b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java @@ -41,50 +41,43 @@ import com.sun.star.script.framework.container.ScriptMetaData; import com.sun.star.script.framework.provider.*; import com.sun.star.script.framework.log.LogUtils; -public class ScriptProviderForJava -{ - public static class _ScriptProviderForJava extends ScriptProvider - { +public class ScriptProviderForJava { + public static class _ScriptProviderForJava extends ScriptProvider { private Resolver m_resolutionPolicy = new StrictResolver(); - public _ScriptProviderForJava( XComponentContext ctx ) - { - super (ctx, "Java"); + public _ScriptProviderForJava(XComponentContext ctx) { + super(ctx, "Java"); } @Override - public XScript getScript( /*IN*/String scriptURI ) - throws com.sun.star.uno.RuntimeException, - ScriptFrameworkErrorException - { - ScriptMetaData scriptData = getScriptData( scriptURI ); - try - { - ScriptImpl script = new ScriptImpl( m_xContext, m_resolutionPolicy, scriptData, m_xModel, m_xInvocContext ); + public XScript getScript(/*IN*/String scriptURI) + throws com.sun.star.uno.RuntimeException, + ScriptFrameworkErrorException { + ScriptMetaData scriptData = getScriptData(scriptURI); + + try { + ScriptImpl script = new ScriptImpl(m_xContext, m_resolutionPolicy, scriptData, + m_xModel, m_xInvocContext); return script; - } - catch ( com.sun.star.uno.RuntimeException re ) - { + } catch (com.sun.star.uno.RuntimeException re) { ScriptFrameworkErrorException e2 = new ScriptFrameworkErrorException( - "Failed to create script object: " + re, - null, scriptData.getLanguageName(), language, - ScriptFrameworkErrorType.UNKNOWN ); - e2.initCause( re ); + "Failed to create script object: " + re, + null, scriptData.getLanguageName(), language, + ScriptFrameworkErrorType.UNKNOWN); + e2.initCause(re); throw e2; } } @Override - public boolean hasScriptEditor() - { + public boolean hasScriptEditor() { return false; } @Override - public ScriptEditor getScriptEditor() - { + public ScriptEditor getScriptEditor() { return null; } } @@ -101,245 +94,223 @@ public class ScriptProviderForJava * the component * @see com.sun.star.comp.loader.JavaLoader */ - public static XSingleServiceFactory __getServiceFactory( String implName, + public static XSingleServiceFactory __getServiceFactory(String implName, XMultiServiceFactory multiFactory, - XRegistryKey regKey ) - { + XRegistryKey regKey) { XSingleServiceFactory xSingleServiceFactory = null; - if ( implName.equals( ScriptProviderForJava._ScriptProviderForJava.class.getName() ) ) - { - xSingleServiceFactory = FactoryHelper.getServiceFactory( - ScriptProviderForJava._ScriptProviderForJava.class, - "com.sun.star.script.provider.ScriptProviderForJava", - multiFactory, - regKey ); + if (implName.equals( + ScriptProviderForJava._ScriptProviderForJava.class.getName())) { + xSingleServiceFactory = FactoryHelper.getServiceFactory( + ScriptProviderForJava._ScriptProviderForJava.class, + "com.sun.star.script.provider.ScriptProviderForJava", + multiFactory, + regKey); } return xSingleServiceFactory; } } -class ScriptImpl implements XScript -{ +class ScriptImpl implements XScript { private ScriptMetaData metaData; private XComponentContext m_xContext; private XModel m_xModel; private XScriptInvocationContext m_xInvocContext; private XMultiComponentFactory m_xMultiComponentFactory; private Resolver m_resolutionPolicy; - ScriptImpl( XComponentContext ctx, Resolver resolver, ScriptMetaData metaData, XModel xModel, XScriptInvocationContext xInvocContext ) throws com.sun.star.uno.RuntimeException - { + ScriptImpl(XComponentContext ctx, Resolver resolver, ScriptMetaData metaData, + XModel xModel, XScriptInvocationContext xInvocContext) throws + com.sun.star.uno.RuntimeException { this.metaData = metaData; this.m_xContext = ctx; this.m_xModel = xModel; this.m_xInvocContext = xInvocContext; this.m_resolutionPolicy = resolver; - try - { + + try { this.m_xMultiComponentFactory = m_xContext.getServiceManager(); - } - catch ( Exception e ) - { - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + } catch (Exception e) { + LogUtils.DEBUG(LogUtils.getTrace(e)); com.sun.star.uno.RuntimeException e2 = new com.sun.star.uno.RuntimeException( - "Error constructing ScriptProvider: " + e ); - e2.initCause( e ); + "Error constructing ScriptProvider: " + e); + e2.initCause(e); throw e2; } - LogUtils.DEBUG("ScriptImpl [java] script data = " + metaData ); + LogUtils.DEBUG("ScriptImpl [java] script data = " + metaData); } - /** - * Invoke - * - * - * @param params All parameters; pure, out params are undefined in - * sequence, i.e., the value has to be ignored by the callee - * @param aOutParamIndex Out indices - * @param aOutParam Out parameters - * @return The value returned from the function being invoked - * @throws IllegalArgumentException If there is no matching script name - * @throws com.sun.star.reflection.InvocationTargetException If the running script throws an exception - * this information is captured and rethrown as this exception type. - */ - - public Object invoke( - /*IN*/Object[] params, - /*OUT*/short[][] aOutParamIndex, - /*OUT*/Object[][] aOutParam ) - - throws ScriptFrameworkErrorException, com.sun.star.reflection.InvocationTargetException - { - LogUtils.DEBUG( "** ScriptProviderForJava::invoke: Starting..." ); - - // Initialise the out parameters - not used at the moment - aOutParamIndex[0] = new short[0]; - aOutParam[0] = new Object[0]; - - Map<String,String> languageProps = metaData.getLanguageProperties(); - - ScriptDescriptor scriptDesc = - new ScriptDescriptor( metaData.getLanguageName() ); - - ClassLoader scriptLoader = null; + /** + * Invoke + * + * + * @param params All parameters; pure, out params are undefined in + * sequence, i.e., the value has to be ignored by the callee + * @param aOutParamIndex Out indices + * @param aOutParam Out parameters + * @return The value returned from the function being invoked + * @throws IllegalArgumentException If there is no matching script name + * @throws com.sun.star.reflection.InvocationTargetException If the running script throws an exception + * this information is captured and rethrown as this exception type. + */ - try { - LogUtils.DEBUG( "Classloader starting..." ); - scriptLoader = ClassLoaderFactory.getURLClassLoader( - metaData ); - LogUtils.DEBUG( "Classloader finished..." ); - } - catch (ArrayStoreException e ) - { - // Framework error - ScriptFrameworkErrorException e2 = - new ScriptFrameworkErrorException( - e.toString(), null, - metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.UNKNOWN ); - e2.initCause( e ); - throw e2; - } + public Object invoke( + /*IN*/Object[] params, + /*OUT*/short[][] aOutParamIndex, + /*OUT*/Object[][] aOutParam) + + throws ScriptFrameworkErrorException, + com.sun.star.reflection.InvocationTargetException { + LogUtils.DEBUG("** ScriptProviderForJava::invoke: Starting..."); + + // Initialise the out parameters - not used at the moment + aOutParamIndex[0] = new short[0]; + aOutParam[0] = new Object[0]; + + Map<String, String> languageProps = metaData.getLanguageProperties(); + + ScriptDescriptor scriptDesc = + new ScriptDescriptor(metaData.getLanguageName()); + + ClassLoader scriptLoader = null; + + try { + LogUtils.DEBUG("Classloader starting..."); + scriptLoader = ClassLoaderFactory.getURLClassLoader( + metaData); + LogUtils.DEBUG("Classloader finished..."); + } catch (ArrayStoreException e) { + // Framework error + ScriptFrameworkErrorException e2 = + new ScriptFrameworkErrorException( + e.toString(), null, + metaData.getLanguageName(), metaData.getLanguage(), + ScriptFrameworkErrorType.UNKNOWN); + e2.initCause(e); + throw e2; + } - ArrayList<Object> invocationArgList = new ArrayList<Object>(); - Object[] invocationArgs = null; + ArrayList<Object> invocationArgList = new ArrayList<Object>(); + Object[] invocationArgs = null; - LogUtils.DEBUG( "Parameter Mapping..." ); + LogUtils.DEBUG("Parameter Mapping..."); - // Setup Context Object - XScriptContext xSc = ScriptContext.createContext(m_xModel, m_xInvocContext, - m_xContext, m_xMultiComponentFactory); - scriptDesc.addArgumentType( XScriptContext.class ); - invocationArgList.add( xSc ); + // Setup Context Object + XScriptContext xSc = ScriptContext.createContext(m_xModel, m_xInvocContext, + m_xContext, m_xMultiComponentFactory); + scriptDesc.addArgumentType(XScriptContext.class); + invocationArgList.add(xSc); - for ( int i = 0; i < params.length; i++ ) - { - scriptDesc.addArgumentType( params[ i ].getClass() ); - invocationArgList.add( params[ i ] ); - } + for (int i = 0; i < params.length; i++) { + scriptDesc.addArgumentType(params[ i ].getClass()); + invocationArgList.add(params[ i ]); + } - if ( !invocationArgList.isEmpty() ) - { - invocationArgs = invocationArgList.toArray(); - } + if (!invocationArgList.isEmpty()) { + invocationArgs = invocationArgList.toArray(); + } - LogUtils.DEBUG( "ScriptProxy starting... " ); - ScriptProxy script = null; - try - { - String className = metaData.getLanguageName().substring( 0, - metaData.getLanguageName().lastIndexOf( '.' ) ); - LogUtils.DEBUG( "About to load Class " + className + " starting... " ); - - long start = new java.util.Date().getTime(); - Class<?> c = scriptLoader.loadClass( className ); - long end = new java.util.Date().getTime(); - - LogUtils.DEBUG("loadClass took: " + String.valueOf(end - start) + - "milliseconds"); - - try - { - LogUtils.DEBUG( "class loaded ... " ); - script = m_resolutionPolicy.getProxy( scriptDesc, c ); - LogUtils.DEBUG( "script resolved ... " ); - } - catch( NoSuchMethodException e ) - { - // Framework error - ScriptFrameworkErrorException e2 = - new ScriptFrameworkErrorException( - e.toString(), null, - metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.NO_SUCH_SCRIPT ); - e2.initCause( e ); - throw e2; - } - } - catch ( ClassNotFoundException e ) - { - // Framework error - ScriptFrameworkErrorException e2 = - new ScriptFrameworkErrorException( - e.toString(), null, - metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.NO_SUCH_SCRIPT ); - e2.initCause( e ); - throw e2; - } + LogUtils.DEBUG("ScriptProxy starting... "); + ScriptProxy script = null; - LogUtils.DEBUG( "Starting Invoke on Proxy ..." ); - Object result = null; + try { + String className = metaData.getLanguageName().substring(0, + metaData.getLanguageName().lastIndexOf('.')); + LogUtils.DEBUG("About to load Class " + className + " starting... "); - try - { - long start = new java.util.Date().getTime(); - result = script.invoke( invocationArgs ); - long end = new java.util.Date().getTime(); + long start = new java.util.Date().getTime(); + Class<?> c = scriptLoader.loadClass(className); + long end = new java.util.Date().getTime(); - LogUtils.DEBUG("invoke took: " + - String.valueOf(end - start) + "milliseconds"); - } - catch ( java.lang.IllegalArgumentException iae ) - { - ScriptFrameworkErrorException e2 = - new ScriptFrameworkErrorException( - iae.getMessage(), null, - metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.UNKNOWN ); - e2.initCause( iae ); - throw e2; - } - catch ( java.lang.IllegalAccessException ia ) - { + LogUtils.DEBUG("loadClass took: " + String.valueOf(end - start) + + "milliseconds"); + + try { + LogUtils.DEBUG("class loaded ... "); + script = m_resolutionPolicy.getProxy(scriptDesc, c); + LogUtils.DEBUG("script resolved ... "); + } catch (NoSuchMethodException e) { + // Framework error ScriptFrameworkErrorException e2 = new ScriptFrameworkErrorException( - ia.toString(), null, - metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.UNKNOWN ); - e2.initCause( ia ); + e.toString(), null, + metaData.getLanguageName(), metaData.getLanguage(), + ScriptFrameworkErrorType.NO_SUCH_SCRIPT); + e2.initCause(e); throw e2; } - catch ( java.lang.reflect.InvocationTargetException ite ) - { - Throwable targetException = ite.getTargetException(); - ScriptExceptionRaisedException se = - new ScriptExceptionRaisedException( - targetException.toString() ); - se.lineNum = -1; - se.scriptName = metaData.getLanguageName(); - se.language = "Java"; - se.exceptionType = targetException.getClass().getName(); - throw new com.sun.star.reflection.InvocationTargetException( - "Scripting Framework error executing script ", null, se ); - } - catch ( Exception unknown ) - { - ScriptExceptionRaisedException se = - new ScriptExceptionRaisedException( - unknown.toString() ); - se.lineNum = -1; - se.scriptName = metaData.getLanguageName(); - se.language = "Java"; - se.exceptionType = unknown.getClass().getName(); - throw new com.sun.star.reflection.InvocationTargetException( - "Scripting Framework error executing script ", null, se ); - } - if ( result == null ) - { - LogUtils.DEBUG( "Got Nothing Back" ); - // in the case where there is no return type - Any voidAny = new Any(new Type(), null); - result = voidAny; - } - else - { - LogUtils.DEBUG( "Got object " + result ); - } - return result; + } catch (ClassNotFoundException e) { + // Framework error + ScriptFrameworkErrorException e2 = + new ScriptFrameworkErrorException( + e.toString(), null, + metaData.getLanguageName(), metaData.getLanguage(), + ScriptFrameworkErrorType.NO_SUCH_SCRIPT); + e2.initCause(e); + throw e2; + } + + LogUtils.DEBUG("Starting Invoke on Proxy ..."); + Object result = null; + + try { + long start = new java.util.Date().getTime(); + result = script.invoke(invocationArgs); + long end = new java.util.Date().getTime(); + + LogUtils.DEBUG("invoke took: " + + String.valueOf(end - start) + "milliseconds"); + } catch (java.lang.IllegalArgumentException iae) { + ScriptFrameworkErrorException e2 = + new ScriptFrameworkErrorException( + iae.getMessage(), null, + metaData.getLanguageName(), metaData.getLanguage(), + ScriptFrameworkErrorType.UNKNOWN); + e2.initCause(iae); + throw e2; + } catch (java.lang.IllegalAccessException ia) { + ScriptFrameworkErrorException e2 = + new ScriptFrameworkErrorException( + ia.toString(), null, + metaData.getLanguageName(), metaData.getLanguage(), + ScriptFrameworkErrorType.UNKNOWN); + e2.initCause(ia); + throw e2; + } catch (java.lang.reflect.InvocationTargetException ite) { + Throwable targetException = ite.getTargetException(); + ScriptExceptionRaisedException se = + new ScriptExceptionRaisedException( + targetException.toString()); + se.lineNum = -1; + se.scriptName = metaData.getLanguageName(); + se.language = "Java"; + se.exceptionType = targetException.getClass().getName(); + throw new com.sun.star.reflection.InvocationTargetException( + "Scripting Framework error executing script ", null, se); + } catch (Exception unknown) { + ScriptExceptionRaisedException se = + new ScriptExceptionRaisedException( + unknown.toString()); + se.lineNum = -1; + se.scriptName = metaData.getLanguageName(); + se.language = "Java"; + se.exceptionType = unknown.getClass().getName(); + throw new com.sun.star.reflection.InvocationTargetException( + "Scripting Framework error executing script ", null, se); + } + + if (result == null) { + LogUtils.DEBUG("Got Nothing Back"); + // in the case where there is no return type + Any voidAny = new Any(new Type(), null); + result = voidAny; + } else { + LogUtils.DEBUG("Got object " + result); } + + return result; + } } diff --git a/scripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java index 010f160ade94..a9bd27293f54 100644 --- a/scripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java +++ b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java @@ -26,8 +26,7 @@ import java.lang.reflect.InvocationTargetException; * * @see java.lang.reflect.Method */ -public class ScriptProxy -{ +public class ScriptProxy { private Object m_targetObject; private Method m_method; @@ -38,8 +37,7 @@ public class ScriptProxy * * @param method Description of the Parameter */ - public ScriptProxy( Method method ) - { + public ScriptProxy(Method method) { this.m_method = method; } @@ -50,8 +48,7 @@ public class ScriptProxy * * @param obj The new targetObject value */ - public void setTargetObject( Object obj ) - { + public void setTargetObject(Object obj) { m_targetObject = obj; } @@ -67,11 +64,10 @@ public class ScriptProxy * @see java.lang.reflect.Method for the exceptions * that may be thrown */ - public Object invoke( Object[] args ) + public Object invoke(Object[] args) throws IllegalAccessException, InvocationTargetException, - IllegalArgumentException - { - return m_method.invoke( m_targetObject, args ); + IllegalArgumentException { + return m_method.invoke(m_targetObject, args); } } diff --git a/scripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java b/scripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java index 6f1898b43387..4ad0f4d52fa7 100644 --- a/scripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java +++ b/scripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java @@ -28,14 +28,12 @@ import com.sun.star.script.framework.log.LogUtils; * method accepting all of the arguments specified in the ScriptDescriptor * can be found in the Class. */ -public class StrictResolver implements Resolver -{ +public class StrictResolver implements Resolver { /** *Constructor for the StrictResolver object */ - public StrictResolver() - { - LogUtils.DEBUG( this.getClass().getName() + " created" ); + public StrictResolver() { + LogUtils.DEBUG(this.getClass().getName() + " created"); } /** @@ -47,49 +45,40 @@ public class StrictResolver implements Resolver * @param c the Class file in which to search for the method * @return the ScriptProxy matching the criteria, or null if no match is found */ - public ScriptProxy getProxy( ScriptDescriptor sd, Class<?> c ) - throws NoSuchMethodException - { + public ScriptProxy getProxy(ScriptDescriptor sd, Class<?> c) + throws NoSuchMethodException { Method m = null; - LogUtils.DEBUG( "StrictResolver.getProxy() for: " + sd.toString() ); + LogUtils.DEBUG("StrictResolver.getProxy() for: " + sd.toString()); - try - { - m = resolveArguments( sd, c ); - } - catch ( ClassNotFoundException e ) - { - throw new NoSuchMethodException( "StrictResolver.getProxy: Can't find method: " - + sd.getMethodName() + ":" + e.getMessage() ); - } - catch ( NoSuchMethodException e ) - { - throw new NoSuchMethodException( "StrictResolver.getProxy: Can't find method: " - + sd.getMethodName() + ":" + e.getMessage() ); + try { + m = resolveArguments(sd, c); + } catch (ClassNotFoundException e) { + throw new NoSuchMethodException("StrictResolver.getProxy: Can't find method: " + + sd.getMethodName() + ":" + e.getMessage()); + } catch (NoSuchMethodException e) { + throw new NoSuchMethodException("StrictResolver.getProxy: Can't find method: " + + sd.getMethodName() + ":" + e.getMessage()); } - ScriptProxy sp = new ScriptProxy( m ); + ScriptProxy sp = new ScriptProxy(m); int modifiers = m.getModifiers(); - if ( !Modifier.isStatic( modifiers ) ) - { + + if (!Modifier.isStatic(modifiers)) { Object o; - try - { + + try { o = c.newInstance(); + } catch (InstantiationException ie) { + throw new NoSuchMethodException("getScriptProxy: Can't instantiate: " + + c.getName()); + } catch (IllegalAccessException iae) { + throw new NoSuchMethodException("getScriptProxy: Can't access: " + + c.getName()); } - catch ( InstantiationException ie ) - { - throw new NoSuchMethodException( "getScriptProxy: Can't instantiate: " + - c.getName() ); - } - catch ( IllegalAccessException iae ) - { - throw new NoSuchMethodException( "getScriptProxy: Can't access: " - + c.getName() ); - } - sp.setTargetObject( o ); + + sp.setTargetObject(o); } return sp; @@ -105,10 +94,9 @@ public class StrictResolver implements Resolver * @exception ClassNotFoundException * @exception NoSuchMethodException */ - private Method resolveArguments( ScriptDescriptor sd, Class<?> c ) - throws ClassNotFoundException, NoSuchMethodException - { - return c.getMethod( sd.getMethodName(), sd.getArgumentTypes() ); + private Method resolveArguments(ScriptDescriptor sd, Class<?> c) + throws ClassNotFoundException, NoSuchMethodException { + return c.getMethod(sd.getMethodName(), sd.getArgumentTypes()); } } diff --git a/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java index cc4c7b3c787f..89ebabd62b82 100644 --- a/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java +++ b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java @@ -40,8 +40,7 @@ import java.util.HashMap; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; -public class ScriptEditorForJavaScript implements ScriptEditor -{ +public class ScriptEditorForJavaScript implements ScriptEditor { // global ScriptEditorForJavaScript instance private static ScriptEditorForJavaScript theScriptEditorForJavaScript; @@ -51,7 +50,8 @@ public class ScriptEditorForJavaScript implements ScriptEditor private Main rhinoWindow; private URL scriptURL; // global list of ScriptEditors, key is URL of file being edited - private static Map<URL,ScriptEditorForJavaScript> BEING_EDITED = new HashMap<URL,ScriptEditorForJavaScript>(); + private static Map<URL, ScriptEditorForJavaScript> BEING_EDITED = new + HashMap<URL, ScriptEditorForJavaScript>(); static { try { @@ -62,6 +62,7 @@ public class ScriptEditorForJavaScript implements ScriptEditor StringBuilder buf = new StringBuilder(); byte[] b = new byte[1024]; int len; + while ((len = in.read(b)) != -1) { buf.append(new String(b, 0, len)); } @@ -69,11 +70,9 @@ public class ScriptEditorForJavaScript implements ScriptEditor in.close(); JSTEMPLATE = buf.toString(); - } - catch (IOException ioe) { + } catch (IOException ioe) { JSTEMPLATE = "// JavaScript script"; - } - catch (Exception e) { + } catch (Exception e) { JSTEMPLATE = "// JavaScript script"; } } @@ -81,13 +80,13 @@ public class ScriptEditorForJavaScript implements ScriptEditor /** * Returns the global ScriptEditorForJavaScript instance. */ - public static synchronized ScriptEditorForJavaScript getEditor() - { - if (theScriptEditorForJavaScript == null) - { + + public static synchronized ScriptEditorForJavaScript getEditor() { + if (theScriptEditorForJavaScript == null) { theScriptEditorForJavaScript = new ScriptEditorForJavaScript(); } + return theScriptEditorForJavaScript; } @@ -99,8 +98,7 @@ public class ScriptEditorForJavaScript implements ScriptEditor * @return The ScriptEditorForJavaScript associated with * the given URL if one exists, otherwise null. */ - public static ScriptEditorForJavaScript getEditor(URL url) - { + public static ScriptEditorForJavaScript getEditor(URL url) { synchronized (BEING_EDITED) { return BEING_EDITED.get(url); } @@ -110,9 +108,8 @@ public class ScriptEditorForJavaScript implements ScriptEditor * Returns whether or not the script source being edited in this * ScriptEditorForJavaScript has been modified */ - public boolean isModified() - { - return rhinoWindow.isModified( scriptURL ); + public boolean isModified() { + return rhinoWindow.isModified(scriptURL); } /** @@ -120,9 +117,8 @@ public class ScriptEditorForJavaScript implements ScriptEditor * * @return The text displayed in this ScriptEditorForJavaScript */ - public String getText() - { - return rhinoWindow.getText( scriptURL ); + public String getText() { + return rhinoWindow.getText(scriptURL); } /** @@ -130,8 +126,7 @@ public class ScriptEditorForJavaScript implements ScriptEditor * * @return The url of this ScriptEditorForJavaScript */ - public String getURL() - { + public String getURL() { return scriptURL.toString(); } @@ -140,8 +135,7 @@ public class ScriptEditorForJavaScript implements ScriptEditor * * @return The template text for JavaScript scripts */ - public String getTemplate() - { + public String getTemplate() { return JSTEMPLATE; } @@ -150,8 +144,7 @@ public class ScriptEditorForJavaScript implements ScriptEditor * * @return The default extension for JavaScript scripts */ - public String getExtension() - { + public String getExtension() { return "js"; } @@ -163,36 +156,36 @@ public class ScriptEditorForJavaScript implements ScriptEditor * @param context The context in which to execute the script * @param entry The metadata describing the script */ - public void edit(final XScriptContext context, ScriptMetaData entry) - { + public void edit(final XScriptContext context, ScriptMetaData entry) { try { String sUrl = entry.getParcelLocation(); - if ( !sUrl.endsWith( "/" ) ) - { + + if (!sUrl.endsWith("/")) { sUrl += "/"; } + sUrl += entry.getLanguageName(); final URL url = entry.getSourceURL(); SwingInvocation.invoke( - new Runnable() { - public void run() { - synchronized (BEING_EDITED) { - ScriptEditorForJavaScript editor = - BEING_EDITED.get(url); - if (editor == null) { - editor = new ScriptEditorForJavaScript( - context, url); - BEING_EDITED.put(url, editor); - } + new Runnable() { + public void run() { + synchronized (BEING_EDITED) { + ScriptEditorForJavaScript editor = + BEING_EDITED.get(url); + + if (editor == null) { + editor = new ScriptEditorForJavaScript( + context, url); + BEING_EDITED.put(url, editor); } - assert rhinoWindow != null; - rhinoWindow.showScriptWindow(url); - rhinoWindow.toFront(); } - }); - } - catch ( IOException e ) - { + + assert rhinoWindow != null; + rhinoWindow.showScriptWindow(url); + rhinoWindow.toFront(); + } + }); + } catch (IOException e) { LogUtils.DEBUG("Caught exception: " + e); LogUtils.DEBUG(LogUtils.getTrace(e)); } @@ -200,15 +193,13 @@ public class ScriptEditorForJavaScript implements ScriptEditor // Ensures that new instances of this class can only be created using // the factory methods - private ScriptEditorForJavaScript() - { + private ScriptEditorForJavaScript() { } - private ScriptEditorForJavaScript(XScriptContext context, URL url) - { + private ScriptEditorForJavaScript(XScriptContext context, URL url) { initUI(); - Scriptable scope = getScope( context ); - this.rhinoWindow.openFile(url, scope, new closeHandler( url ) ); + Scriptable scope = getScope(context); + this.rhinoWindow.openFile(url, scope, new closeHandler(url)); this.scriptURL = url; @@ -219,30 +210,26 @@ public class ScriptEditorForJavaScript implements ScriptEditor * */ - public Object execute() throws Exception - { + public Object execute() throws Exception { rhinoWindow.toFront(); - return this.rhinoWindow.runScriptWindow( scriptURL ); + return this.rhinoWindow.runScriptWindow(scriptURL); } /** * Indicates the line where error occurred * */ - public void indicateErrorLine( int lineNum ) - { + public void indicateErrorLine(int lineNum) { this.rhinoWindow.toFront(); - this.rhinoWindow.highlighLineInScriptWindow( scriptURL, lineNum ); + this.rhinoWindow.highlighLineInScriptWindow(scriptURL, lineNum); } // This code is based on the main method of the Rhino Debugger Main class // We pass in the XScriptContext in the global scope for script execution private void initUI() { try { - synchronized ( ScriptEditorForJavaScript.class ) - { - if ( this.rhinoWindow != null ) - { + synchronized (ScriptEditorForJavaScript.class) { + if (this.rhinoWindow != null) { return; } @@ -263,7 +250,7 @@ public class ScriptEditorForJavaScript implements ScriptEditor return org.mozilla.javascript.tools.shell.Main.getScope(); } }); - sdb.addWindowListener( new WindowAdapter() { + sdb.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { shutdown(); @@ -272,35 +259,34 @@ public class ScriptEditorForJavaScript implements ScriptEditor this.rhinoWindow = sdb; } } catch (Exception exc) { - LogUtils.DEBUG( LogUtils.getTrace( exc ) ); + LogUtils.DEBUG(LogUtils.getTrace(exc)); } } - private void shutdown() - { + private void shutdown() { // dereference Rhino Debugger window this.rhinoWindow = null; this.scriptURL = null; + // remove all scripts from BEING_EDITED - synchronized( BEING_EDITED ) - { + synchronized (BEING_EDITED) { java.util.Iterator<URL> iter = BEING_EDITED.keySet().iterator(); java.util.ArrayList<URL> keysToRemove = new java.util.ArrayList<URL>(); - while ( iter.hasNext() ) - { + + while (iter.hasNext()) { URL key = iter.next(); - keysToRemove.add( key ); + keysToRemove.add(key); } - for ( int i=0; i<keysToRemove.size(); i++ ) - { - BEING_EDITED.remove( keysToRemove.get( i ) ); + + for (int i = 0; i < keysToRemove.size(); i++) { + BEING_EDITED.remove(keysToRemove.get(i)); } + keysToRemove = null; } } - private Scriptable getScope(XScriptContext xsctxt ) - { + private Scriptable getScope(XScriptContext xsctxt) { Context ctxt = Context.enter(); ImporterTopLevel scope = new ImporterTopLevel(ctxt); @@ -308,25 +294,21 @@ public class ScriptEditorForJavaScript implements ScriptEditor scope.put("XSCRIPTCONTEXT", scope, jsCtxt); Scriptable jsArgs = Context.toObject( - new Object[0], scope); + new Object[0], scope); scope.put("ARGUMENTS", scope, jsArgs); Context.exit(); return scope; } - private class closeHandler implements Runnable - { + private class closeHandler implements Runnable { private URL url; - private closeHandler( URL url ) - { + private closeHandler(URL url) { this.url = url; } - public void run() - { - synchronized( BEING_EDITED ) - { - BEING_EDITED.remove( this.url ); + public void run() { + synchronized (BEING_EDITED) { + BEING_EDITED.remove(this.url); } } } diff --git a/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java index 1ef1ad7a0c81..e5b7a95cf46e 100644 --- a/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java +++ b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java @@ -48,43 +48,37 @@ import org.mozilla.javascript.ImporterTopLevel; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.JavaScriptException; -public class ScriptProviderForJavaScript -{ - public static class ScriptProviderForJavaScript_2 extends ScriptProvider - { - public ScriptProviderForJavaScript_2(XComponentContext ctx) - { +public class ScriptProviderForJavaScript { + public static class ScriptProviderForJavaScript_2 extends ScriptProvider { + public ScriptProviderForJavaScript_2(XComponentContext ctx) { super(ctx, "JavaScript"); } @Override - public XScript getScript( /*IN*/String scriptURI ) - throws com.sun.star.uno.RuntimeException, - ScriptFrameworkErrorException - { + public XScript getScript(/*IN*/String scriptURI) + throws com.sun.star.uno.RuntimeException, + ScriptFrameworkErrorException { ScriptMetaData scriptData = null; - try - { - scriptData = getScriptData( scriptURI ); - ScriptImpl script = new ScriptImpl( m_xContext, scriptData, m_xModel, m_xInvocContext ); + + try { + scriptData = getScriptData(scriptURI); + ScriptImpl script = new ScriptImpl(m_xContext, scriptData, m_xModel, + m_xInvocContext); return script; - } - catch ( com.sun.star.uno.RuntimeException re ) - { - throw new ScriptFrameworkErrorException( "Failed to create script object: " + re.getMessage(), - null, scriptData.getLanguageName(), language, ScriptFrameworkErrorType.UNKNOWN ); + } catch (com.sun.star.uno.RuntimeException re) { + throw new ScriptFrameworkErrorException("Failed to create script object: " + + re.getMessage(), + null, scriptData.getLanguageName(), language, ScriptFrameworkErrorType.UNKNOWN); } } @Override - public boolean hasScriptEditor() - { + public boolean hasScriptEditor() { return true; } @Override - public ScriptEditor getScriptEditor() - { + public ScriptEditor getScriptEditor() { return ScriptEditorForJavaScript.getEditor(); } } @@ -101,242 +95,231 @@ public class ScriptProviderForJavaScript * the component * @see com.sun.star.comp.loader.JavaLoader */ - public static XSingleServiceFactory __getServiceFactory( String implName, + public static XSingleServiceFactory __getServiceFactory(String implName, XMultiServiceFactory multiFactory, - XRegistryKey regKey ) - { + XRegistryKey regKey) { XSingleServiceFactory xSingleServiceFactory = null; - if ( implName.equals( ScriptProviderForJavaScript.ScriptProviderForJavaScript_2.class.getName() ) ) - { + if (implName.equals( + ScriptProviderForJavaScript.ScriptProviderForJavaScript_2.class.getName())) { xSingleServiceFactory = FactoryHelper.getServiceFactory( - ScriptProviderForJavaScript.ScriptProviderForJavaScript_2.class, - "com.sun.star.script.provider.ScriptProviderForJavaScript", - multiFactory, - regKey ); + ScriptProviderForJavaScript.ScriptProviderForJavaScript_2.class, + "com.sun.star.script.provider.ScriptProviderForJavaScript", + multiFactory, + regKey); } return xSingleServiceFactory; } } -class ScriptImpl implements XScript -{ +class ScriptImpl implements XScript { private ScriptMetaData metaData; private XComponentContext m_xContext; private XMultiComponentFactory m_xMultiComponentFactory; private XModel m_xModel; private XScriptInvocationContext m_xInvocContext; - ScriptImpl( XComponentContext ctx, ScriptMetaData metaData, XModel xModel, XScriptInvocationContext xInvocContext ) throws com.sun.star.uno.RuntimeException - { + ScriptImpl(XComponentContext ctx, ScriptMetaData metaData, XModel xModel, + XScriptInvocationContext xInvocContext) throws + com.sun.star.uno.RuntimeException { this.metaData = metaData; this.m_xContext = ctx; this.m_xModel = xModel; this.m_xInvocContext = xInvocContext; - try - { + + try { this.m_xMultiComponentFactory = m_xContext.getServiceManager(); - } - catch ( Exception e ) - { - LogUtils.DEBUG( LogUtils.getTrace( e ) ); + } catch (Exception e) { + LogUtils.DEBUG(LogUtils.getTrace(e)); throw new com.sun.star.uno.RuntimeException( "Error constructing ScriptImpl: [javascript]"); } - LogUtils.DEBUG("ScriptImpl [javascript] script data = " + metaData ); + + LogUtils.DEBUG("ScriptImpl [javascript] script data = " + metaData); } - /** - * The invoke method of the ScriptProviderForJavaScript runs the - * JavaScript script specified in the URI - * - * - * - * @param params All parameters; pure, out params are - * undefined in sequence, i.e., the value - * has to be ignored by the callee - * - * @param aOutParamIndex Out indices - * - * @param aOutParam Out parameters - * - * @return The value returned from the function - * being invoked - * - * @throws ScriptFrameworkErrorException If there is no matching script name - * - * - * @throws InvocationTargetException If the running script throws - * an exception this information - * is captured and rethrown as - * ScriptErrorRaisedException or - * ScriptExceptionRaisedException - */ - - public Object invoke( - /*IN*/Object[] params, - /*OUT*/short[][] aOutParamIndex, - /*OUT*/Object[][] aOutParam ) - - throws ScriptFrameworkErrorException, InvocationTargetException - { - // Initialise the out parameters - not used at the moment - aOutParamIndex[0] = new short[0]; - aOutParam[0] = new Object[0]; - - - - ClassLoader cl = null; - URL sourceUrl = null; - try { - cl = ClassLoaderFactory.getURLClassLoader( metaData ); - sourceUrl = metaData.getSourceURL(); - } - catch ( java.net.MalformedURLException mfu ) - { - throw new ScriptFrameworkErrorException( - mfu.getMessage(), null, - metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.MALFORMED_URL ); - } - Context ctxt = null; - - try - { - String editorURL = sourceUrl.toString(); - Object result = null; - ScriptEditorForJavaScript editor = - ScriptEditorForJavaScript.getEditor( - metaData.getSourceURL() ); - - if (editor != null) - { - editorURL = editor.getURL(); - result = editor.execute(); - if ( result != null && - result.getClass().getName().equals( "org.mozilla.javascript.Undefined" ) ) - { - // Always return a string - // TODO revisit - return Context.toString( result ); - } + /** + * The invoke method of the ScriptProviderForJavaScript runs the + * JavaScript script specified in the URI + * + * + * + * @param params All parameters; pure, out params are + * undefined in sequence, i.e., the value + * has to be ignored by the callee + * + * @param aOutParamIndex Out indices + * + * @param aOutParam Out parameters + * + * @return The value returned from the function + * being invoked + * + * @throws ScriptFrameworkErrorException If there is no matching script name + * + * + * @throws InvocationTargetException If the running script throws + * an exception this information + * is captured and rethrown as + * ScriptErrorRaisedException or + * ScriptExceptionRaisedException + */ - } + public Object invoke( + /*IN*/Object[] params, + /*OUT*/short[][] aOutParamIndex, + /*OUT*/Object[][] aOutParam) - String source; - if (editor != null && editor.isModified()) - { - LogUtils.DEBUG("GOT A MODIFIED SOURCE"); - source = editor.getText(); - } - else - { - metaData.loadSource(); - source = metaData.getSource(); + throws ScriptFrameworkErrorException, InvocationTargetException { + // Initialise the out parameters - not used at the moment + aOutParamIndex[0] = new short[0]; + aOutParam[0] = new Object[0]; - } - if ( source == null || source.length() == 0 ) { - throw new ScriptFrameworkErrorException( - "Failed to read source data for script", null, - metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.UNKNOWN ); - } - /* Set the context ClassLoader on the current thread to - be our custom ClassLoader. This is the suggested method - for setting up a ClassLoader to be used by the Rhino - interpreter - */ - if (cl != null) { - Thread.currentThread().setContextClassLoader(cl); + ClassLoader cl = null; + URL sourceUrl = null; + + try { + cl = ClassLoaderFactory.getURLClassLoader(metaData); + sourceUrl = metaData.getSourceURL(); + } catch (java.net.MalformedURLException mfu) { + throw new ScriptFrameworkErrorException( + mfu.getMessage(), null, + metaData.getLanguageName(), metaData.getLanguage(), + ScriptFrameworkErrorType.MALFORMED_URL); + } + + Context ctxt = null; + + try { + String editorURL = sourceUrl.toString(); + Object result = null; + ScriptEditorForJavaScript editor = + ScriptEditorForJavaScript.getEditor( + metaData.getSourceURL()); + + if (editor != null) { + editorURL = editor.getURL(); + result = editor.execute(); + + if (result != null && + result.getClass().getName().equals("org.mozilla.javascript.Undefined")) { + // Always return a string + // TODO revisit + return Context.toString(result); } - // Initialize a Rhino Context object - ctxt = Context.enter(); - - /* The ImporterTopLevel ensures that importClass and - importPackage statements work in Javascript scripts - Make the XScriptContext available as a global variable - to the script - */ - ImporterTopLevel scope = new ImporterTopLevel(ctxt); - - Scriptable jsCtxt = Context.toObject( - ScriptContext.createContext( - m_xModel, m_xInvocContext, m_xContext, - m_xMultiComponentFactory), scope); - scope.put("XSCRIPTCONTEXT", scope, jsCtxt); - - Scriptable jsArgs = Context.toObject(params, scope); - scope.put("ARGUMENTS", scope, jsArgs); - - result = ctxt.evaluateString(scope, - source, "<stdin>", 1, null); - result = Context.toString(result); - return result; } - catch (JavaScriptException jse) { - LogUtils.DEBUG( "Caught JavaScriptException exception for JavaScript type = " + jse.getClass() ); - String message = jse.getMessage(); - Object wrap = jse.getValue(); - LogUtils.DEBUG( "\t message " + message ); - LogUtils.DEBUG( "\t wrapped type " + wrap.getClass() ); - LogUtils.DEBUG( "\t wrapped toString " + wrap.toString() ); - ScriptExceptionRaisedException se = new - ScriptExceptionRaisedException( message ); - se.lineNum = -1; - se.language = "JavaScript"; - se.scriptName = metaData.getLanguageName(); - se.exceptionType = wrap.getClass().getName(); - se.language = metaData.getLanguage(); - LogUtils.DEBUG( "ExceptionRaised exception " ); - LogUtils.DEBUG( "\t message " + se.getMessage() ); - LogUtils.DEBUG( "\t lineNum " + se.lineNum ); - LogUtils.DEBUG( "\t language " + se.language ); - LogUtils.DEBUG( "\t scriptName " + se.scriptName ); - raiseEditor( se.lineNum ); - throw new InvocationTargetException( "JavaScript uncaught exception" + metaData.getLanguageName(), null, se ); + + String source; + + if (editor != null && editor.isModified()) { + LogUtils.DEBUG("GOT A MODIFIED SOURCE"); + source = editor.getText(); + } else { + metaData.loadSource(); + source = metaData.getSource(); + } - catch (Exception ex) { - LogUtils.DEBUG("Caught Exception " + ex ); - LogUtils.DEBUG("rethrowing as ScriptFramework error" ); + + if (source == null || source.length() == 0) { throw new ScriptFrameworkErrorException( - ex.getMessage(), null, + "Failed to read source data for script", null, metaData.getLanguageName(), metaData.getLanguage(), - ScriptFrameworkErrorType.UNKNOWN ); + ScriptFrameworkErrorType.UNKNOWN); } - finally { - if ( ctxt != null ) - { - Context.exit(); - } + + /* Set the context ClassLoader on the current thread to + be our custom ClassLoader. This is the suggested method + for setting up a ClassLoader to be used by the Rhino + interpreter + */ + if (cl != null) { + Thread.currentThread().setContextClassLoader(cl); + } + + // Initialize a Rhino Context object + ctxt = Context.enter(); + + /* The ImporterTopLevel ensures that importClass and + importPackage statements work in Javascript scripts + Make the XScriptContext available as a global variable + to the script + */ + ImporterTopLevel scope = new ImporterTopLevel(ctxt); + + Scriptable jsCtxt = Context.toObject( + ScriptContext.createContext( + m_xModel, m_xInvocContext, m_xContext, + m_xMultiComponentFactory), scope); + scope.put("XSCRIPTCONTEXT", scope, jsCtxt); + + Scriptable jsArgs = Context.toObject(params, scope); + scope.put("ARGUMENTS", scope, jsArgs); + + result = ctxt.evaluateString(scope, + source, "<stdin>", 1, null); + result = Context.toString(result); + return result; + } catch (JavaScriptException jse) { + LogUtils.DEBUG("Caught JavaScriptException exception for JavaScript type = " + + jse.getClass()); + String message = jse.getMessage(); + Object wrap = jse.getValue(); + LogUtils.DEBUG("\t message " + message); + LogUtils.DEBUG("\t wrapped type " + wrap.getClass()); + LogUtils.DEBUG("\t wrapped toString " + wrap.toString()); + ScriptExceptionRaisedException se = new + ScriptExceptionRaisedException(message); + se.lineNum = -1; + se.language = "JavaScript"; + se.scriptName = metaData.getLanguageName(); + se.exceptionType = wrap.getClass().getName(); + se.language = metaData.getLanguage(); + LogUtils.DEBUG("ExceptionRaised exception "); + LogUtils.DEBUG("\t message " + se.getMessage()); + LogUtils.DEBUG("\t lineNum " + se.lineNum); + LogUtils.DEBUG("\t language " + se.language); + LogUtils.DEBUG("\t scriptName " + se.scriptName); + raiseEditor(se.lineNum); + throw new InvocationTargetException("JavaScript uncaught exception" + + metaData.getLanguageName(), null, se); + } catch (Exception ex) { + LogUtils.DEBUG("Caught Exception " + ex); + LogUtils.DEBUG("rethrowing as ScriptFramework error"); + throw new ScriptFrameworkErrorException( + ex.getMessage(), null, + metaData.getLanguageName(), metaData.getLanguage(), + ScriptFrameworkErrorType.UNKNOWN); + } finally { + if (ctxt != null) { + Context.exit(); } } + } - private void raiseEditor( int lineNum ) - { - try - { - URL sourceUrl = metaData.getSourceURL(); - ScriptEditorForJavaScript editor = ScriptEditorForJavaScript.getEditor( sourceUrl ); - if ( editor == null ) - { - editor = ScriptEditorForJavaScript.getEditor(); - editor.edit( - ScriptContext.createContext(m_xModel, m_xInvocContext, - m_xContext, m_xMultiComponentFactory), metaData ); - editor = ScriptEditorForJavaScript.getEditor( sourceUrl ); - } - if ( editor != null ) - { - System.out.println("** Have raised IDE for JavaScript, calling indicateErrorLine for line " + lineNum ); - editor.indicateErrorLine( lineNum ); - } + private void raiseEditor(int lineNum) { + try { + URL sourceUrl = metaData.getSourceURL(); + ScriptEditorForJavaScript editor = ScriptEditorForJavaScript.getEditor( + sourceUrl); + + if (editor == null) { + editor = ScriptEditorForJavaScript.getEditor(); + editor.edit( + ScriptContext.createContext(m_xModel, m_xInvocContext, + m_xContext, m_xMultiComponentFactory), metaData); + editor = ScriptEditorForJavaScript.getEditor(sourceUrl); } - catch( Exception ignore ) - { + + if (editor != null) { + System.out.println("** Have raised IDE for JavaScript, calling indicateErrorLine for line " + + lineNum); + editor.indicateErrorLine(lineNum); } + } catch (Exception ignore) { } + } } diff --git a/scripting/java/org/openoffice/idesupport/CommandLineTools.java b/scripting/java/org/openoffice/idesupport/CommandLineTools.java index c47e2457c121..8fa9269ca361 100644 --- a/scripting/java/org/openoffice/idesupport/CommandLineTools.java +++ b/scripting/java/org/openoffice/idesupport/CommandLineTools.java @@ -43,28 +43,25 @@ public class CommandLineTools { // Get the URL for the Office DTD directory and pass it to the // XMLParserFactory so that Office xml files can be parsed - if (officePath == null) - { + if (officePath == null) { try { SVersionRCFile sv = SVersionRCFile.createInstance(); - if (sv.getDefaultVersion() != null) - { + + if (sv.getDefaultVersion() != null) { officePath = sv.getDefaultVersion().getPath(); } - } - catch (IOException ioe) { + } catch (IOException ioe) { System.err.println("Error getting Office directory"); } } - if (officePath == null) - { + if (officePath == null) { driver.fatalUsage("Error: Office Installation path not set"); } File officeDir = new File(officePath); - if (!officeDir.exists() || !officeDir.isDirectory()) - { + + if (!officeDir.exists() || !officeDir.isDirectory()) { driver.fatalUsage( "Error: Office Installation path not valid: " + officePath); } @@ -78,8 +75,7 @@ public class CommandLineTools { else { try { command.execute(); - } - catch (Exception e) { + } catch (Exception e) { driver.fatal("Error: " + e.getMessage()); } } @@ -91,17 +87,17 @@ public class CommandLineTools { private void printUsage() { System.out.println("java " + getClass().getName() + " -h " + - "prints this message"); + "prints this message"); System.out.println("java " + getClass().getName() + - " [-o Path to Office Installation] " + - "-d <script parcel zip file> " + - "<destination document or directory>"); + " [-o Path to Office Installation] " + + "-d <script parcel zip file> " + + "<destination document or directory>"); System.out.println("java " + getClass().getName() + - " [-o Path to Office Installation] " + - "-g [parcel root directory] [options] [script names]"); + " [-o Path to Office Installation] " + + "-g [parcel root directory] [options] [script names]"); System.out.println("options:"); System.out.println("\t[-l language[=supported extension 1[" + - File.pathSeparator + "supported extension 2]]]"); + File.pathSeparator + "supported extension 2]]]"); System.out.println("\t[-p name=value]"); System.out.println("\t[-v]"); } @@ -121,8 +117,7 @@ public class CommandLineTools { if (args.length < 1) { return null; - } - else if (args[0].equals("-h")) { + } else if (args[0].equals("-h")) { return new Command() { public void execute() { printUsage(); @@ -132,24 +127,24 @@ public class CommandLineTools { int i = 0; - if(args[0].equals("-o")) { - officePath = args[i+1]; + if (args[0].equals("-o")) { + officePath = args[i + 1]; i += 2; } - if(args[i].equals("-d")) { + if (args[i].equals("-d")) { if ((args.length - i) != 3) return null; else - return new DeployCommand(args[i+1], args[i+2]); - } - else if(args[i].equals("-g")) { + return new DeployCommand(args[i + 1], args[i + 2]); + } else if (args[i].equals("-g")) { if ((args.length - i) == 1) return new GenerateCommand(System.getProperty("user.dir")); GenerateCommand command; i++; + if (!args[i].startsWith("-")) command = new GenerateCommand(args[i++]); else @@ -158,19 +153,18 @@ public class CommandLineTools { for (; i < args.length; i++) { if (args[i].equals("-l")) { command.setLanguage(args[++i]); - } - else if (args[i].equals("-p")) { + } else if (args[i].equals("-p")) { command.addProperty(args[++i]); - } - else if (args[i].equals("-v")) { + } else if (args[i].equals("-v")) { command.setVerbose(); - } - else { + } else { command.addScript(args[i]); } } + return command; } + return null; } @@ -207,13 +201,13 @@ public class CommandLineTools { extensions = new String[tokenizer.countTokens()]; int i = 0; - while(tokenizer.hasMoreTokens()) + while (tokenizer.hasMoreTokens()) extensions[i++] = (String)tokenizer.nextToken(); - } - else { + } else { extensions = new String[1]; extensions[0] = ext; } + this.finder = new ExtensionFinder(this.language, extensions); } } @@ -244,6 +238,7 @@ public class CommandLineTools { public void addScript(ScriptEntry entry) { if (scripts == null) scripts = new ArrayList(3); + scripts.add(entry); } @@ -251,15 +246,14 @@ public class CommandLineTools { if (!basedir.isDirectory()) { throw new Exception(basedir.getName() + " is not a directory"); - } - else if (!contents.exists()) { + } else if (!contents.exists()) { throw new Exception(basedir.getName() + - " does not contain a Contents directory"); + " does not contain a Contents directory"); } if (language == null && !parcelxml.exists()) { throw new Exception(parcelxml.getName() + " not found and language " + - "not specified"); + "not specified"); } if (language != null && parcelxml.exists()) { @@ -271,8 +265,8 @@ public class CommandLineTools { if (!desclang.equals(language.toLowerCase())) throw new Exception(parcelxml.getName() + " already exists, " + - "and has a different language attribute: " + - desc.getLanguage()); + "and has a different language attribute: " + + desc.getLanguage()); } if (language != null && scripts == null) { @@ -282,6 +276,7 @@ public class CommandLineTools { log("Searching for " + language + " scripts"); ScriptEntry[] entries = finder.findMethods(contents); + for (int i = 0; i < entries.length; i++) { addScript(entries[i]); log("Found: " + entries[i].getLogicalName()); @@ -293,7 +288,9 @@ public class CommandLineTools { throw new Exception("No valid scripts found"); ParcelDescriptor desc = new ParcelDescriptor(parcelxml, language); - desc.setScriptEntries((ScriptEntry[])scripts.toArray(new ScriptEntry[scripts.size()])); + desc.setScriptEntries((ScriptEntry[])scripts.toArray(new + ScriptEntry[scripts.size()])); + if (properties.size() != 0) { Enumeration enumer = properties.keys(); @@ -305,15 +302,16 @@ public class CommandLineTools { desc.setLanguageProperty(name, value); } } + desc.write(); - } - else { + } else { if (!parcelxml.exists()) throw new Exception("No valid scripts found"); } contents = new File(contents.getAbsolutePath()); - String name = ParcelZipper.getParcelZipper().zipParcel(contents, AllFilesFilter.getInstance()); + String name = ParcelZipper.getParcelZipper().zipParcel(contents, + AllFilesFilter.getInstance()); System.out.println(name + " generated"); } @@ -335,7 +333,7 @@ public class CommandLineTools { public void execute() throws Exception { ParcelZipper.getParcelZipper().deployParcel(source, target); System.out.println(source.getName() + - " successfully deployed to " + target.getAbsolutePath()); + " successfully deployed to " + target.getAbsolutePath()); } } } diff --git a/scripting/java/org/openoffice/idesupport/ExtensionFinder.java b/scripting/java/org/openoffice/idesupport/ExtensionFinder.java index 0fa051c5af67..48b80fd77eec 100644 --- a/scripting/java/org/openoffice/idesupport/ExtensionFinder.java +++ b/scripting/java/org/openoffice/idesupport/ExtensionFinder.java @@ -44,6 +44,7 @@ public class ExtensionFinder implements MethodFinder { return empty; parcelName = basedir.getName(); + if (parcelName.equals(ParcelZipper.CONTENTS_DIRNAME)) parcelName = basedir.getParentFile().getName(); @@ -51,10 +52,12 @@ public class ExtensionFinder implements MethodFinder { if (files.size() != 0) return files.toArray(empty); + return empty; } - private void findFiles(ArrayList<ScriptEntry> list, File basedir, String parcelName) { + private void findFiles(ArrayList<ScriptEntry> list, File basedir, + String parcelName) { File[] children = basedir.listFiles(); File f; @@ -67,7 +70,7 @@ public class ExtensionFinder implements MethodFinder { for (int j = 0; j < extensions.length; j++) { if (f.getName().endsWith(extensions[j])) { ScriptEntry entry = new ScriptEntry(language, - f.getName(), parcelName); + f.getName(), parcelName); list.add(entry); break; } diff --git a/scripting/java/org/openoffice/idesupport/JavaFinder.java b/scripting/java/org/openoffice/idesupport/JavaFinder.java index 98043d2198e8..e9385fd3c57e 100644 --- a/scripting/java/org/openoffice/idesupport/JavaFinder.java +++ b/scripting/java/org/openoffice/idesupport/JavaFinder.java @@ -65,10 +65,12 @@ public class JavaFinder implements MethodFinder { return empty; parcelName = basedir.getName(); + if (parcelName.equals(ParcelZipper.CONTENTS_DIRNAME)) parcelName = basedir.getParentFile().getName(); String[] classNames = findClassNames(basedir); + if (classNames != null && classNames.length != 0) { ClassLoader classloader; @@ -78,40 +80,32 @@ public class JavaFinder implements MethodFinder { else classloader = getClassLoader(); - for (int i = 0; i < classNames.length; i++) - { - try - { + for (int i = 0; i < classNames.length; i++) { + try { Class clazz = classloader.loadClass(classNames[i]); Method[] methods = clazz.getDeclaredMethods(); - for (int k = 0; k < methods.length; k++) - { - if (Modifier.isPublic(methods[k].getModifiers())) - { + + for (int k = 0; k < methods.length; k++) { + if (Modifier.isPublic(methods[k].getModifiers())) { Class[] params = methods[k].getParameterTypes(); - if(params.length > 0) - { - if(params[0].getName().equals(FIRST_PARAM)) - { + + if (params.length > 0) { + if (params[0].getName().equals(FIRST_PARAM)) { ScriptEntry entry = new ScriptEntry(classNames[i] + "." + - methods[k].getName(), parcelName); + methods[k].getName(), parcelName); result.add(entry); } } } } - } - catch (ClassNotFoundException e) - { + } catch (ClassNotFoundException e) { System.err.println("Caught ClassNotFoundException loading: " - + classNames[i]); + + classNames[i]); continue; - } - catch (NoClassDefFoundError nc) - { + } catch (NoClassDefFoundError nc) { System.err.println("Caught NoClassDefFoundErr loading: " + - classNames[i]); + classNames[i]); continue; } } @@ -119,6 +113,7 @@ public class JavaFinder implements MethodFinder { if (result.size() != 0) return result.toArray(empty); + return empty; } @@ -133,8 +128,7 @@ public class JavaFinder implements MethodFinder { if (s != null) urls.add(new URL(s)); - } - catch (MalformedURLException mue) { + } catch (MalformedURLException mue) { } } @@ -146,7 +140,8 @@ public class JavaFinder implements MethodFinder { files.add(basedir); try { - Iterator<OfficeInstallation> offices = SVersionRCFile.createInstance().getVersions(); + Iterator<OfficeInstallation> offices = + SVersionRCFile.createInstance().getVersions(); while (offices.hasNext()) { OfficeInstallation oi = offices.next(); @@ -157,14 +152,14 @@ public class JavaFinder implements MethodFinder { break; } } - } - catch (IOException ioe) { + } catch (IOException ioe) { return null; } URL[] urls = new URL[files.size()]; String urlpath; File f; + for (int i = 0; i < urls.length; i++) { try { f = files.get(i); @@ -172,8 +167,7 @@ public class JavaFinder implements MethodFinder { if (urlpath != null) urls[i] = new URL(urlpath); - } - catch (MalformedURLException mue) { + } catch (MalformedURLException mue) { // do nothing, go on to next file } } @@ -191,36 +185,36 @@ public class JavaFinder implements MethodFinder { else if (children[i].getName().endsWith(suffix)) result.add(children[i]); } + return result; } - private String[] findClassNames(File basedir) - { + private String[] findClassNames(File basedir) { ArrayList<File> classFiles = findFiles(basedir, CLASS_SUFFIX); - if(classFiles == null || classFiles.size() == 0) + + if (classFiles == null || classFiles.size() == 0) return null; ArrayList<File> javaFiles = findFiles(basedir, JAVA_SUFFIX); - if(javaFiles == null || javaFiles.size() == 0) + + if (javaFiles == null || javaFiles.size() == 0) return null; ArrayList<String> result = new ArrayList<String>(); - for (int i = 0; i < classFiles.size(); i++) - { + + for (int i = 0; i < classFiles.size(); i++) { File classFile = classFiles.get(i); String className = classFile.getName(); className = className.substring(0, className.lastIndexOf(CLASS_SUFFIX)); boolean finished = false; - for (int j = 0; j < javaFiles.size() && !finished; j++) - { + for (int j = 0; j < javaFiles.size() && !finished; j++) { File javaFile = javaFiles.get(j); String javaName = javaFile.getName(); javaName = javaName.substring(0, javaName.lastIndexOf(JAVA_SUFFIX)); - if (javaName.equals(className)) - { + if (javaName.equals(className)) { String path = classFile.getAbsolutePath(); path = path.substring(basedir.getAbsolutePath().length() + 1); path = path.replace(File.separatorChar, '.'); @@ -232,6 +226,7 @@ public class JavaFinder implements MethodFinder { } } } + return result.toArray(new String[result.size()]); } } diff --git a/scripting/java/org/openoffice/idesupport/LocalOffice.java b/scripting/java/org/openoffice/idesupport/LocalOffice.java index ad6e4ad8302b..f6d0814e0199 100644 --- a/scripting/java/org/openoffice/idesupport/LocalOffice.java +++ b/scripting/java/org/openoffice/idesupport/LocalOffice.java @@ -28,8 +28,7 @@ import java.net.ConnectException; * office has to be started with options appropriate for establishing * local connection. */ -public class LocalOffice -{ +public class LocalOffice { /** @@ -40,15 +39,13 @@ public class LocalOffice * @param port is a communication port. */ protected void connect(String officePath, int port) - throws ConnectException - { + throws ConnectException { } /** * Closes the connection to the running office. */ - public void disconnect() - { + public void disconnect() { } /** @@ -56,7 +53,6 @@ public class LocalOffice * * @param uri is an identifier of storage has to be refreshed. */ - public void refreshStorage(String uri) - { + public void refreshStorage(String uri) { } } diff --git a/scripting/java/org/openoffice/idesupport/OfficeDocument.java b/scripting/java/org/openoffice/idesupport/OfficeDocument.java index 764501f01695..abad0ebbdd77 100644 --- a/scripting/java/org/openoffice/idesupport/OfficeDocument.java +++ b/scripting/java/org/openoffice/idesupport/OfficeDocument.java @@ -29,23 +29,22 @@ import java.util.zip.ZipFile; import org.openoffice.idesupport.zip.ParcelZipper; -public class OfficeDocument -{ +public class OfficeDocument { public static final String PARCEL_PREFIX_DIR = ParcelZipper.PARCEL_PREFIX_DIR; public static final String[] OFFICE_EXTENSIONS = - {".sxc" , ".sxw", ".sxi", ".sxd"}; + {".sxc" , ".sxw", ".sxi", ".sxd"}; public static final String OFFICE_PRODUCT_NAME = "OpenOffice.org"; private File file = null; - public OfficeDocument(File file) throws IllegalArgumentException - { + public OfficeDocument(File file) throws IllegalArgumentException { if (!file.exists() || file.isDirectory() || !isOfficeFile(file)) { throw new IllegalArgumentException("This is not a valid " + - OFFICE_PRODUCT_NAME + " document."); + OFFICE_PRODUCT_NAME + " document."); } + this.file = file; } @@ -53,6 +52,7 @@ public class OfficeDocument for (int i = 0; i < OFFICE_EXTENSIONS.length; i++) if (file.getName().endsWith(OFFICE_EXTENSIONS[i])) return true; + return false; } @@ -61,15 +61,13 @@ public class OfficeDocument ArrayList<String> parcels = new ArrayList<String>(); ZipFile zp = null; - try - { + try { zp = new ZipFile(this.file); - for (Enumeration enumer = zp.entries(); enumer.hasMoreElements(); ) - { + for (Enumeration enumer = zp.entries(); enumer.hasMoreElements();) { ZipEntry ze = (ZipEntry)enumer.nextElement(); - if (ze.getName().endsWith(ParcelZipper.PARCEL_DESCRIPTOR_XML)) - { + + if (ze.getName().endsWith(ParcelZipper.PARCEL_DESCRIPTOR_XML)) { String tmp = ze.getName(); int end = tmp.lastIndexOf('/'); tmp = tmp.substring(0, end); @@ -78,19 +76,15 @@ public class OfficeDocument parcels.add(parcelName); } } - } - catch(ZipException ze) { + } catch (ZipException ze) { ze.printStackTrace(); - } - catch(IOException ioe) { + } catch (IOException ioe) { ioe.printStackTrace(); - } - finally { + } finally { if (zp != null) { try { zp.close(); - } - catch (IOException asdf) { + } catch (IOException asdf) { } } } @@ -102,11 +96,11 @@ public class OfficeDocument try { ParcelZipper.getParcelZipper().removeParcel(file, parcelName); - } - catch (IOException ioe) { + } catch (IOException ioe) { ioe.printStackTrace(); return false; } + return true; } } diff --git a/scripting/java/org/openoffice/idesupport/OfficeInstallation.java b/scripting/java/org/openoffice/idesupport/OfficeInstallation.java index 586d3a2d47ef..fdc89c9d12a1 100644 --- a/scripting/java/org/openoffice/idesupport/OfficeInstallation.java +++ b/scripting/java/org/openoffice/idesupport/OfficeInstallation.java @@ -46,8 +46,7 @@ public class OfficeInstallation implements java.io.Serializable { path = path.replace('/', File.separatorChar); this.path = path; - } - else { + } else { this.path = path; if (System.getProperty("os.name").startsWith("Windows")) diff --git a/scripting/java/org/openoffice/idesupport/SVersionRCFile.java b/scripting/java/org/openoffice/idesupport/SVersionRCFile.java index a258983da7dd..4e754e347c75 100644 --- a/scripting/java/org/openoffice/idesupport/SVersionRCFile.java +++ b/scripting/java/org/openoffice/idesupport/SVersionRCFile.java @@ -32,14 +32,14 @@ public class SVersionRCFile { private static final String DEFAULT_NAME = System.getProperty("os.name").startsWith("Windows") ? - System.getProperty("user.home") + File.separator + - "Application Data" + File.separator + "sversion.ini" : - System.getProperty("user.home") + File.separator + - ".sversionrc"; + System.getProperty("user.home") + File.separator + + "Application Data" + File.separator + "sversion.ini" : + System.getProperty("user.home") + File.separator + + ".sversionrc"; public static final String FILE_URL_PREFIX = System.getProperty("os.name").startsWith("Windows") ? - "file:///" : "file://"; + "file:///" : "file://"; @@ -55,7 +55,8 @@ public class SVersionRCFile { /* Make sure this is in LowerCase !!!!! */ private static final String SCRIPTF = "scriptf"; - private static final HashMap<String, SVersionRCFile> files = new HashMap<String, SVersionRCFile>(3); + private static final HashMap<String, SVersionRCFile> files = new + HashMap<String, SVersionRCFile>(3); private File sversionrc = null; private OfficeInstallation defaultversion = null; @@ -72,13 +73,13 @@ public class SVersionRCFile { } public static SVersionRCFile createInstance() { - return(createInstance(DEFAULT_NAME)); + return (createInstance(DEFAULT_NAME)); } private static SVersionRCFile createInstance(String name) { SVersionRCFile result = null; - synchronized(SVersionRCFile.class) { + synchronized (SVersionRCFile.class) { result = files.get(name); if (result == null) { @@ -86,6 +87,7 @@ public class SVersionRCFile { files.put(name, result); } } + return result; } @@ -108,15 +110,14 @@ public class SVersionRCFile { br = new BufferedReader(new FileReader(sversionrc)); load(br); lastModified = l; - } - catch (FileNotFoundException fnfe) { + } catch (FileNotFoundException fnfe) { throw new IOException(fnfe.getMessage()); - } - finally { + } finally { if (br != null) br.close(); } } + return versions.iterator(); } @@ -124,10 +125,10 @@ public class SVersionRCFile { String s; while ((s = br.readLine()) != null && - !(s.equals(VERSIONS_LINE))) {} + !(s.equals(VERSIONS_LINE))) {} while ((s = br.readLine()) != null && - s.length() != 0) { + s.length() != 0) { StringTokenizer tokens = new StringTokenizer(s, "="); int count = tokens.countTokens(); @@ -137,6 +138,7 @@ public class SVersionRCFile { String name = tokens.nextToken(); String path = tokens.nextToken(); OfficeInstallation oi = new OfficeInstallation(name, path); + if (oi.supportsFramework()) { versions.add(oi); defaultversion = oi; @@ -152,8 +154,7 @@ public class SVersionRCFile { try { path = f.getCanonicalPath(); - } - catch (IOException ioe) { + } catch (IOException ioe) { return null; } @@ -169,33 +170,33 @@ public class SVersionRCFile { return buf.toString(); } - public static String getPathForUnoil(String officeInstall) - { + public static String getPathForUnoil(String officeInstall) { File unopkgdir = new File(officeInstall, UNOPACKAGEDIR); - if(!unopkgdir.exists()) - { + + if (!unopkgdir.exists()) { return null; } + File scriptf = null; String[] listunopkg = unopkgdir.list(); int size = listunopkg.length; - for(int i=0; i<size; i++) - { - if (listunopkg[i].toLowerCase().indexOf(SCRIPTF)>-1) - { + + for (int i = 0; i < size; i++) { + if (listunopkg[i].toLowerCase().indexOf(SCRIPTF) > -1) { scriptf = new File(unopkgdir, listunopkg[i]); } } - if(scriptf != null) - { + + if (scriptf != null) { File unoil = new File(scriptf, UNOILJAR); - if(unoil.exists()) - { + + if (unoil.exists()) { String path = unoil.getParent(); path = path.substring(path.indexOf(UNOPACKAGEDIR)); return officeInstall + path; } } + return null; } @@ -208,10 +209,10 @@ public class SVersionRCFile { ov = new SVersionRCFile(args[0]); Iterator<OfficeInstallation> enumer; + try { enumer = ov.getVersions(); - } - catch (IOException ioe) { + } catch (IOException ioe) { System.err.println("Error getting versions: " + ioe.getMessage()); return; } @@ -219,7 +220,7 @@ public class SVersionRCFile { while (enumer.hasNext()) { OfficeInstallation oi = enumer.next(); System.out.println("Name: " + oi.getName() + ", Path: " + oi.getPath() + - ", URL: " + oi.getURL()); + ", URL: " + oi.getURL()); } } } diff --git a/scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java b/scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java index a78ef0e11191..95436158bc6f 100644 --- a/scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java +++ b/scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java @@ -33,6 +33,7 @@ public class BinaryOnlyFilter implements FileFilter { for (int i = 0; i < EXTENSIONS.length; i++) if (name.endsWith(EXTENSIONS[i])) return true; + return false; } diff --git a/scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java b/scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java index 792c9d42a26d..178d449fd8ee 100644 --- a/scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java +++ b/scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java @@ -26,8 +26,7 @@ public class ExceptParcelFilter implements FileFilter { private ExceptParcelFilter() { } - public void setParcelToRemove(String parcelName) - { + public void setParcelToRemove(String parcelName) { ExceptParcelFilter.parcelName = parcelName; } @@ -37,6 +36,7 @@ public class ExceptParcelFilter implements FileFilter { public boolean validate(String name) { if (name.startsWith(ExceptParcelFilter.parcelName)) return true; + return false; } diff --git a/scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java b/scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java index 35a995819b83..3051b72bbfdd 100644 --- a/scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java +++ b/scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java @@ -40,8 +40,7 @@ import org.openoffice.idesupport.LocalOffice; * with options appropriate for establishing local connection. */ public final class LocalOfficeImpl - extends LocalOffice -{ + extends LocalOffice { private final static String STORAGE_MRG_SINGLETON = "/singletons/drafts.com.sun.star.script.framework.storage.theScriptStorageManager"; @@ -57,8 +56,7 @@ public final class LocalOfficeImpl */ @Override protected void connect(String officePath, int port) - throws ConnectException - { + throws ConnectException { try { bootstrap(port); } catch (java.lang.Exception ex) { @@ -72,35 +70,36 @@ public final class LocalOfficeImpl * @param uri is an identifier of storage has to be refreshed. */ @Override - public void refreshStorage(String uri) - { + public void refreshStorage(String uri) { try { Object object = null; object = mComponentContext.getValueByName(STORAGE_MRG_SINGLETON); XScriptStorageManager storageMgr; storageMgr = UnoRuntime.queryInterface( - XScriptStorageManager.class, object); + XScriptStorageManager.class, object); storageMgr.refreshScriptStorage(uri); } catch (java.lang.Exception ex) { -System.out.println("*** LocalOfficeImpl.refreshStorage: FAILED " + ex.getMessage()); -System.out.println("*** LocalOfficeImpl.refreshStorage: FAILED " + ex.getClass().getName()); + System.out.println("*** LocalOfficeImpl.refreshStorage: FAILED " + + ex.getMessage()); + System.out.println("*** LocalOfficeImpl.refreshStorage: FAILED " + + ex.getClass().getName()); } -System.out.println("*** LocalOfficeImpl.refreshStorage: DONE"); + + System.out.println("*** LocalOfficeImpl.refreshStorage: DONE"); } /** * Closes the connection to the running office. */ @Override - public void disconnect() - { -/* - if(mComponentFactory != null) { - XComponent comp = (XComponent)UnoRuntime.queryInterface( - XComponent.class, mComponentFactory); - comp.dispose(); - } -*/ + public void disconnect() { + /* + if(mComponentFactory != null) { + XComponent comp = (XComponent)UnoRuntime.queryInterface( + XComponent.class, mComponentFactory); + comp.dispose(); + } + */ } /** @@ -112,22 +111,21 @@ System.out.println("*** LocalOfficeImpl.refreshStorage: DONE"); * @param port is a communication port. */ private void bootstrap(int port) - throws java.lang.Exception - { + throws java.lang.Exception { Object object; mComponentContext = Bootstrap.createInitialComponentContext(null); XUnoUrlResolver urlresolver = UnoUrlResolver.create(mComponentContext); object = urlresolver.resolve( - "uno:socket,host=localhost,port=" + - port + - ";urp;StarOffice.ServiceManager"); + "uno:socket,host=localhost,port=" + + port + + ";urp;StarOffice.ServiceManager"); mComponentFactory = UnoRuntime.queryInterface( - XMultiComponentFactory.class, object); + XMultiComponentFactory.class, object); XPropertySet factoryProps; factoryProps = UnoRuntime.queryInterface( - XPropertySet.class, mComponentFactory); + XPropertySet.class, mComponentFactory); object = factoryProps.getPropertyValue("DefaultContext"); mComponentContext = UnoRuntime.queryInterface( - XComponentContext.class, object); + XComponentContext.class, object); } } diff --git a/scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java b/scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java index 72d98823864b..4098dca61f0e 100644 --- a/scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java +++ b/scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java @@ -53,7 +53,7 @@ public class ConfigurePanel extends JPanel { "Choose What to Export as Scripts"; public ConfigurePanel(String basedir, ArrayList<String> classpath, - ParcelDescriptor descriptor) { + ParcelDescriptor descriptor) { this.basedir = new File(basedir); this.classpath = classpath; @@ -62,17 +62,17 @@ public class ConfigurePanel extends JPanel { } public ConfigurePanel(String basedir, ArrayList<String> classpath) - throws IOException { + throws IOException { this.basedir = new File(basedir); this.classpath = classpath; this.descriptor = new ParcelDescriptor(new File(this.basedir, - ParcelZipper.PARCEL_DESCRIPTOR_XML)); + ParcelZipper.PARCEL_DESCRIPTOR_XML)); initUI(); } public void reload(String basedir, ArrayList<String> classpath, - ParcelDescriptor descriptor) { + ParcelDescriptor descriptor) { if (basedir != null) this.basedir = new File(basedir); @@ -85,12 +85,12 @@ public class ConfigurePanel extends JPanel { } methodPanel.reload(this.basedir, this.classpath, - descriptor.getLanguage()); + descriptor.getLanguage()); scriptPanel.reload(descriptor.getScriptEntries()); } public void reload(String basedir, ArrayList<String> classpath) - throws IOException { + throws IOException { if (basedir != null) this.basedir = new File(basedir); @@ -99,10 +99,10 @@ public class ConfigurePanel extends JPanel { this.classpath = classpath; this.descriptor = new ParcelDescriptor(new File(this.basedir, - ParcelZipper.PARCEL_DESCRIPTOR_XML)); + ParcelZipper.PARCEL_DESCRIPTOR_XML)); methodPanel.reload(this.basedir, this.classpath, - descriptor.getLanguage()); + descriptor.getLanguage()); scriptPanel.reload(descriptor.getScriptEntries()); } @@ -163,16 +163,17 @@ public class ConfigurePanel extends JPanel { private JPanel initMethodButtons() { JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); - ImageIcon icon = new ImageIcon(getClass().getResource("/org/openoffice/idesupport/ui/add.gif")); + ImageIcon icon = new ImageIcon( + getClass().getResource("/org/openoffice/idesupport/ui/add.gif")); JButton addButton = new JButton("Add", icon); addButton.setHorizontalTextPosition(AbstractButton.LEFT); addButton.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent e) { - scriptPanel.addScriptEntries(methodPanel.getSelectedEntries()); - } + new ActionListener() { + public void actionPerformed(ActionEvent e) { + scriptPanel.addScriptEntries(methodPanel.getSelectedEntries()); } + } ); GridBagConstraints gbc = new java.awt.GridBagConstraints(); @@ -199,19 +200,19 @@ public class ConfigurePanel extends JPanel { JButton removeAllButton = new JButton("Remove All"); removeButton.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent e) { - scriptPanel.removeSelectedRows(); - } + new ActionListener() { + public void actionPerformed(ActionEvent e) { + scriptPanel.removeSelectedRows(); } + } ); removeAllButton.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent e) { - scriptPanel.removeAllRows(); - } + new ActionListener() { + public void actionPerformed(ActionEvent e) { + scriptPanel.removeAllRows(); } + } ); panel.add(removeButton); diff --git a/scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java b/scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java index a6969cdd89ef..c25b5fb04660 100644 --- a/scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java +++ b/scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java @@ -56,8 +56,7 @@ public class ScriptPanel extends JPanel { try { entry = (ScriptEntry) entries[i].clone(); - } - catch (CloneNotSupportedException cnse) { + } catch (CloneNotSupportedException cnse) { entry = new ScriptEntry(entries[i].getLanguage(), entries[i].getLanguageName(), entries[i].getLocation()); @@ -108,8 +107,10 @@ public class ScriptPanel extends JPanel { private void tableFocusLost() { TableCellEditor editor = table.getCellEditor(); + if (editor != null) { Object value = editor.getCellEditorValue(); + if (value != null) model.setValueAt(value, table.getEditingRow(), table.getEditingColumn()); @@ -118,16 +119,19 @@ public class ScriptPanel extends JPanel { private class ScriptTableModel extends AbstractTableModel { final String[] columnNames = {"Exported Method", - "Script Name"}; + "Script Name" + }; private ArrayList<ScriptEntry> scripts; private int nextRow; public ScriptTableModel(ScriptEntry[] entries) { scripts = new ArrayList<ScriptEntry>(entries.length + 11); + for (int i = 0; i < entries.length; i++) { scripts.add(entries[i]); } + nextRow = entries.length; } diff --git a/scripting/java/org/openoffice/idesupport/xml/Manifest.java b/scripting/java/org/openoffice/idesupport/xml/Manifest.java index 263de3d97b29..492df63b75ea 100644 --- a/scripting/java/org/openoffice/idesupport/xml/Manifest.java +++ b/scripting/java/org/openoffice/idesupport/xml/Manifest.java @@ -53,14 +53,13 @@ public class Manifest { try { root = (Element) - document.getElementsByTagName("manifest:manifest").item(0); + document.getElementsByTagName("manifest:manifest").item(0); el = document.createElement("manifest:file-entry"); el.setAttribute("manifest:media-type", type); el.setAttribute("manifest:full-path", entry); root.appendChild(el); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Error adding entry: " + e.getMessage()); } } @@ -78,25 +77,28 @@ public class Manifest { try { root = (Element) - document.getElementsByTagName("manifest:manifest").item(0); + document.getElementsByTagName("manifest:manifest").item(0); NodeList nl = root.getElementsByTagName("manifest:file-entry"); + if (nl == null || (len = nl.getLength()) == 0) return; ArrayList<Element> list = new ArrayList<Element>(); + for (int i = 0; i < len; i++) { el = (Element)nl.item(i); + if (el.getAttribute("manifest:full-path").startsWith(entry)) { list.add(el); } } Iterator iter = list.iterator(); + while (iter.hasNext()) root.removeChild((Element)iter.next()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Error removing entry: " + e.getMessage()); } } @@ -109,8 +111,7 @@ public class Manifest { out = new ByteArrayOutputStream(); write(out); result = new ByteArrayInputStream(out.toByteArray()); - } - finally { + } finally { if (out != null) out.close(); } diff --git a/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java b/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java index 9fd7f5da00fd..3c8d797f220c 100644 --- a/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java +++ b/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java @@ -24,8 +24,7 @@ import org.openoffice.idesupport.filter.FileFilter; import org.openoffice.idesupport.filter.BinaryOnlyFilter; import org.openoffice.idesupport.xml.Manifest; -public class ParcelZipper -{ +public class ParcelZipper { public static final String PARCEL_PREFIX_DIR = "Scripts/"; private static final String PARCEL_EXTENSION = "sxp"; public static final String CONTENTS_DIRNAME = "Contents"; @@ -42,6 +41,7 @@ public class ParcelZipper public static synchronized ParcelZipper getParcelZipper() { if (zipper == null) zipper = new ParcelZipper(); + return zipper; } @@ -52,7 +52,7 @@ public class ParcelZipper public String removeParcel(File document, String parcelName) - throws IOException { + throws IOException { ZipInputStream documentStream = null; ZipOutputStream outStream = null; @@ -60,6 +60,7 @@ public class ParcelZipper if (!parcelName.startsWith(PARCEL_PREFIX_DIR)) parcelName = PARCEL_PREFIX_DIR + parcelName; + manifest = removeParcelFromManifest(document, parcelName); // first write contents of document to tmpfile @@ -76,38 +77,36 @@ public class ParcelZipper while ((inEntry = documentStream.getNextEntry()) != null) { - if(inEntry.getName().startsWith(parcelName)) + if (inEntry.getName().startsWith(parcelName)) continue; outEntry = new ZipEntry(inEntry); outStream.putNextEntry(outEntry); - if(inEntry.getName().equals("META-INF/manifest.xml") && - manifest != null) { + if (inEntry.getName().equals("META-INF/manifest.xml") && + manifest != null) { InputStream manifestStream = null; + try { manifestStream = manifest.getInputStream(); + while ((len = manifestStream.read(bytes)) != -1) outStream.write(bytes, 0, len); - } - finally { + } finally { if (manifestStream != null) manifestStream.close(); } - } - else if (!inEntry.isDirectory()) { + } else if (!inEntry.isDirectory()) { while ((len = documentStream.read(bytes)) != -1) outStream.write(bytes, 0, len); } outStream.closeEntry(); } - } - catch (IOException ioe) { + } catch (IOException ioe) { tmpfile.delete(); throw ioe; - } - finally { + } finally { if (documentStream != null) documentStream.close(); @@ -118,8 +117,7 @@ public class ParcelZipper if (!document.delete()) { tmpfile.delete(); throw new IOException("Could not overwrite " + document); - } - else + } else tmpfile.renameTo(document); return document.getAbsolutePath(); @@ -132,18 +130,16 @@ public class ParcelZipper try { documentZip = new ZipFile(document); ZipEntry original = documentZip.getEntry("META-INF/manifest.xml"); + if (original != null) { result = new Manifest(documentZip.getInputStream(original)); } - } - catch (IOException ioe) { - } - finally { + } catch (IOException ioe) { + } finally { try { if (documentZip != null) documentZip.close(); - } - catch (IOException ioe) {} + } catch (IOException ioe) {} } return result; @@ -153,6 +149,7 @@ public class ParcelZipper Manifest result = null; result = getManifestFromDocument(document); + if (result == null) return null; diff --git a/scripting/java/org/openoffice/netbeans/editor/JavaKit.java b/scripting/java/org/openoffice/netbeans/editor/JavaKit.java index 3f622927ed83..1a3b6abddd17 100644 --- a/scripting/java/org/openoffice/netbeans/editor/JavaKit.java +++ b/scripting/java/org/openoffice/netbeans/editor/JavaKit.java @@ -57,10 +57,10 @@ public class JavaKit extends ExtKit { public static final String JAVA_MIME_TYPE = "text/x-java"; // NOI18N - static final long serialVersionUID =-5445829962533684922L; + static final long serialVersionUID = -5445829962533684922L; static { - Settings.addInitializer( new JavaSettingsInitializer( JavaKit.class ) ); + Settings.addInitializer(new JavaSettingsInitializer(JavaKit.class)); Settings.reset(); URL skeleton = null, body = null; @@ -73,8 +73,8 @@ public class JavaKit extends ExtKit { new URLAccessor(body)); JCBaseFinder finder = new JCBaseFinder(); - finder.append( provider ); - JavaCompletion.setFinder( finder ); + finder.append(provider); + JavaCompletion.setFinder(finder); } } @@ -110,7 +110,7 @@ public class JavaKit extends ExtKit { protected void initDocument(BaseDocument doc) { doc.addLayer(new JavaDrawLayerFactory.JavaLayer(), - JavaDrawLayerFactory.JAVA_LAYER_VISIBILITY); + JavaDrawLayerFactory.JAVA_LAYER_VISIBILITY); doc.addDocumentListener(new JavaDrawLayerFactory.LParenWatcher()); } @@ -131,8 +131,7 @@ public class JavaKit extends ExtKit { /** Not implemented */ public void append(byte[] buffer, int off, int len) - throws IOException - { + throws IOException { throw new IllegalArgumentException("read only!"); } @@ -150,6 +149,7 @@ public class JavaKit extends ExtKit { */ public void read(byte[] buffer, int off, int len) throws IOException { InputStream str = getStream(actOff); + while (len > 0) { int count = str.read(buffer, off, len); streamOff += count; @@ -162,7 +162,7 @@ public class JavaKit extends ExtKit { * @param requestWrite if true, file is opened for read/write */ public void open(boolean requestWrite) throws IOException { - if(requestWrite) + if (requestWrite) throw new IllegalArgumentException("read only!"); } @@ -181,7 +181,7 @@ public class JavaKit extends ExtKit { * at which the next read or write occurs. */ public long getFilePointer() throws IOException { - return actOff; + return actOff; } /** Clears the file and sets the offset to 0 */ @@ -206,7 +206,7 @@ public class JavaKit extends ExtKit { stream = null; } - if(stream == null) { + if (stream == null) { stream = url.openStream(); streamOff = 0; } @@ -214,6 +214,7 @@ public class JavaKit extends ExtKit { while (streamOff < off) { long len = stream.skip(off - streamOff); streamOff += (int)len; + if (len == 0) throw new IOException("EOF"); } diff --git a/scripting/java/org/openoffice/netbeans/editor/NetBeansSourceView.java b/scripting/java/org/openoffice/netbeans/editor/NetBeansSourceView.java index b4b2bd8d4fa3..19388fd8f82f 100644 --- a/scripting/java/org/openoffice/netbeans/editor/NetBeansSourceView.java +++ b/scripting/java/org/openoffice/netbeans/editor/NetBeansSourceView.java @@ -49,25 +49,24 @@ public class NetBeansSourceView extends JPanel try { Class kitClass = Class.forName( - NetBeansSourceView.class.getPackage().getName() + ".JavaKit"); + NetBeansSourceView.class.getPackage().getName() + ".JavaKit"); JEditorPane.registerEditorKitForContentType( "text/x-java", kitClass.getName(), kitClass.getClassLoader()); - } - catch( ClassNotFoundException exc ) { + } catch (ClassNotFoundException exc) { } } private class MyLocalizer implements LocaleSupport.Localizer { private ResourceBundle bundle; - public MyLocalizer( String bundleName ) { - bundle = ResourceBundle.getBundle( bundleName ); + public MyLocalizer(String bundleName) { + bundle = ResourceBundle.getBundle(bundleName); } // Localizer - public String getString( String key ) { - return bundle.getString( key ); + public String getString(String key) { + return bundle.getString(key); } } @@ -102,10 +101,10 @@ public class NetBeansSourceView extends JPanel } java.net.URL url = null; + try { url = f.toURL(); - } - catch (java.net.MalformedURLException mue) { + } catch (java.net.MalformedURLException mue) { System.err.println("Invalid file"); System.exit(-1); } @@ -120,11 +119,11 @@ public class NetBeansSourceView extends JPanel } // Code grabbed from NetBeans editor module - public void scrollToLine(int line) - { + public void scrollToLine(int line) { BaseDocument doc = Utilities.getDocument(pane); int pos = -1; + if (doc != null) { // Obtain the offset where to jump pos = Utilities.getRowStartFromLineOffset(doc, line); @@ -132,11 +131,11 @@ public class NetBeansSourceView extends JPanel if (pos != -1) { Caret caret = pane.getCaret(); + if (caret instanceof BaseCaret) { // support extended scroll mode BaseCaret bCaret = (BaseCaret)caret; bCaret.setDot(pos, bCaret, EditorUI.SCROLL_FIND); - } - else { + } else { caret.setDot(pos); } } @@ -151,16 +150,14 @@ public class NetBeansSourceView extends JPanel so we don't get a storm of DocumentEvents during loading */ pane.getDocument().removeDocumentListener(this); - if (!isModified) - { + if (!isModified) { pane.setText(model.getText()); } // scroll to current position of the model try { scrollToLine(model.getCurrentPosition()); - } - catch (Exception e) { + } catch (Exception e) { // couldn't scroll to line, do nothing } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/BuildParcelAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/BuildParcelAction.java index db68ba7f874a..9aa998cfe77a 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/BuildParcelAction.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/BuildParcelAction.java @@ -50,7 +50,7 @@ public class BuildParcelAction extends BuildAllAction { if (task.isSuccessful()) { ParcelFolderCookie cookie = (ParcelFolderCookie) - activatedNodes[i].getCookie(ParcelFolderCookie.class); + activatedNodes[i].getCookie(ParcelFolderCookie.class); if (cookie != null) cookie.generate(); diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ConfigureParcelAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ConfigureParcelAction.java index 0e4005828c9c..fa64996ced70 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/ConfigureParcelAction.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ConfigureParcelAction.java @@ -43,15 +43,15 @@ public class ConfigureParcelAction extends CookieAction { return HelpCtx.DEFAULT_HELP; } - protected void performAction(final Node[] activatedNodes) - { + protected void performAction(final Node[] activatedNodes) { FrameworkJarChecker.mountDependencies(); RequestProcessor.getDefault().post(new Runnable() { public void run() { for (int i = 0; i < activatedNodes.length; i++) { ParcelFolderCookie pfc = (ParcelFolderCookie) - activatedNodes[i].getCookie(ParcelFolderCookie.class); + activatedNodes[i].getCookie(ParcelFolderCookie.class); + if (pfc != null) pfc.configure(); } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/DeployParcelAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/DeployParcelAction.java index 015c15cfb54b..6f9f48b02489 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/DeployParcelAction.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/DeployParcelAction.java @@ -51,16 +51,17 @@ import org.openoffice.idesupport.LocalOffice; import org.openoffice.netbeans.modules.office.utils.NagDialog; import org.openoffice.netbeans.modules.office.options.OfficeSettings; -public class DeployParcelAction extends CookieAction implements Presenter.Popup { +public class DeployParcelAction extends CookieAction implements + Presenter.Popup { private static final String BROWSE_LABEL = "Office Document..."; private static final String DEPLOY_LABEL = "Deploy To"; - public String getName () { + public String getName() { return DEPLOY_LABEL; } - public HelpCtx getHelpCtx () { + public HelpCtx getHelpCtx() { return HelpCtx.DEFAULT_HELP; } @@ -79,12 +80,13 @@ public class DeployParcelAction extends CookieAction implements Presenter.Popup (ParcelCookie)nodes[0].getCookie(ParcelCookie.class); File target = new File(oi.getPath(File.separator + label + - File.separator + "Scripts")); + File.separator + "Scripts")); File langdir = new File(target, parcelCookie.getLanguage()); if (!langdir.exists()) { boolean response = askIfCreateDirectory(langdir); + if (!response) { return; } @@ -110,8 +112,10 @@ public class DeployParcelAction extends CookieAction implements Presenter.Popup item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File target = getTargetFile(); + if (target == null) return; + deploy(target); } }); @@ -120,15 +124,15 @@ public class DeployParcelAction extends CookieAction implements Presenter.Popup return menu; } - protected int mode () { + protected int mode() { return MODE_ONE; } - protected Class[] cookieClasses () { + protected Class[] cookieClasses() { return new Class[] { ParcelCookie.class }; } - protected void performAction (Node[] activatedNodes) { + protected void performAction(Node[] activatedNodes) { // do nothing, should not happen } @@ -150,7 +154,7 @@ public class DeployParcelAction extends CookieAction implements Presenter.Popup private boolean askIfCreateDirectory(File directory) { String message = directory.getAbsolutePath() + " does not exist. " + - "Do you want to create it now?"; + "Do you want to create it now?"; NotifyDescriptor d = new NotifyDescriptor.Confirmation( message, NotifyDescriptor.OK_CANCEL_OPTION); @@ -160,10 +164,10 @@ public class DeployParcelAction extends CookieAction implements Presenter.Popup return false; boolean result; + try { result = directory.mkdirs(); - } - catch (SecurityException se) { + } catch (SecurityException se) { result = false; } @@ -173,6 +177,7 @@ public class DeployParcelAction extends CookieAction implements Presenter.Popup tmp, NotifyDescriptor.ERROR_MESSAGE); TopManager.getDefault().notify(d2); } + return result; } @@ -185,14 +190,14 @@ public class DeployParcelAction extends CookieAction implements Presenter.Popup private void showNagDialog() { String message = "If you currently have Office running you will " + - "need to click on the Tools/Scripting Add-on's/Refresh All Scripts " + - " menu item in Office so that the scripts in this parcel can be detected."; + "need to click on the Tools/Scripting Add-on's/Refresh All Scripts " + + " menu item in Office so that the scripts in this parcel can be detected."; OfficeSettings settings = OfficeSettings.getDefault(); if (settings.getWarnAfterDirDeploy()) { NagDialog warning = NagDialog.createInformationDialog( - message, "Show this message in future", true); + message, "Show this message in future", true); warning.show(); @@ -216,6 +221,7 @@ public class DeployParcelAction extends CookieAction implements Presenter.Popup file.getName().endsWith(".sxd") || file.getName().endsWith(".sxi")) return true; + return false; } @@ -229,6 +235,7 @@ public class DeployParcelAction extends CookieAction implements Presenter.Popup if (result == JFileChooser.APPROVE_OPTION) { target = chooser.getSelectedFile(); } + return target; } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/MountDocumentAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/MountDocumentAction.java index 7fa5fa7e0292..8b22e93ef9c4 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/MountDocumentAction.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/MountDocumentAction.java @@ -26,41 +26,33 @@ import org.openide.util.actions.CookieAction; /** * @version 1.0 */ -public class MountDocumentAction extends CookieAction -{ - public String getName() - { +public class MountDocumentAction extends CookieAction { + public String getName() { return "Mount Document"; //NOI18N } - public HelpCtx getHelpCtx() - { + public HelpCtx getHelpCtx() { return HelpCtx.DEFAULT_HELP; } - protected int mode() - { + protected int mode() { // enable duplication for as many qualifying nodes as are selected: return CookieAction.MODE_ALL; } - protected java.lang.Class[] cookieClasses() - { + protected java.lang.Class[] cookieClasses() { // just the DuplicateCookie: return new Class[] {OfficeDocumentCookie.class}; } - protected void performAction(final Node[] activatedNodes) - { - RequestProcessor.getDefault().post(new Runnable() - { - public void run() - { - for (int i=0; i<activatedNodes.length; i++) - { - OfficeDocumentCookie cookie = (OfficeDocumentCookie)activatedNodes[i].getCookie(OfficeDocumentCookie.class); - if (cookie != null) - { + protected void performAction(final Node[] activatedNodes) { + RequestProcessor.getDefault().post(new Runnable() { + public void run() { + for (int i = 0; i < activatedNodes.length; i++) { + OfficeDocumentCookie cookie = (OfficeDocumentCookie)activatedNodes[i].getCookie( + OfficeDocumentCookie.class); + + if (cookie != null) { cookie.mount(); } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/MountParcelAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/MountParcelAction.java index c579dacc2e53..01395dc3fb7d 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/MountParcelAction.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/MountParcelAction.java @@ -26,40 +26,32 @@ import org.openide.util.actions.CookieAction; /** * @version 1.0 */ -public class MountParcelAction extends CookieAction -{ - public String getName() - { +public class MountParcelAction extends CookieAction { + public String getName() { return "Mount Parcel"; //NOI18N } - public HelpCtx getHelpCtx() - { + public HelpCtx getHelpCtx() { return HelpCtx.DEFAULT_HELP; } - protected int mode() - { + protected int mode() { // enable duplication for as many qualifying nodes as are selected: return CookieAction.MODE_ALL; } - protected java.lang.Class[] cookieClasses() - { + protected java.lang.Class[] cookieClasses() { return new Class[] {ParcelCookie.class}; } - protected void performAction(final Node[] activatedNodes) - { - RequestProcessor.getDefault().post(new Runnable() - { - public void run() - { - for (int i=0; i<activatedNodes.length; i++) - { - ParcelCookie mpc = (ParcelCookie)activatedNodes[i].getCookie(ParcelCookie.class); - if (mpc != null) - { + protected void performAction(final Node[] activatedNodes) { + RequestProcessor.getDefault().post(new Runnable() { + public void run() { + for (int i = 0; i < activatedNodes.length; i++) { + ParcelCookie mpc = (ParcelCookie)activatedNodes[i].getCookie( + ParcelCookie.class); + + if (mpc != null) { mpc.mount(); } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentCookie.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentCookie.java index 04ac91f3e741..df57575020f4 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentCookie.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentCookie.java @@ -22,8 +22,7 @@ import java.util.Enumeration; import javax.swing.event.ChangeListener; import org.openide.nodes.Node; -public interface OfficeDocumentCookie extends Node.Cookie -{ +public interface OfficeDocumentCookie extends Node.Cookie { void mount(); Enumeration getParcels(); void removeParcel(String name); diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentSupport.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentSupport.java index 0237872185bf..c77fc63a7cbc 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentSupport.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentSupport.java @@ -44,8 +44,8 @@ import org.openoffice.netbeans.modules.office.loader.OfficeDocumentDataObject; import org.openoffice.netbeans.modules.office.utils.ZipMounter; import org.openoffice.netbeans.modules.office.utils.ManifestParser; -public class OfficeDocumentSupport implements OfficeDocumentCookie, OpenCookie, FileChangeListener -{ +public class OfficeDocumentSupport implements OfficeDocumentCookie, OpenCookie, + FileChangeListener { protected OfficeDocumentDataObject dataObj; private boolean isMounted = false; private OfficeDocument document; @@ -54,12 +54,13 @@ public class OfficeDocumentSupport implements OfficeDocumentCookie, OpenCookie, public OfficeDocumentSupport(OfficeDocumentDataObject dataObj) { this.dataObj = dataObj; FileObject fo = dataObj.getPrimaryFile(); + try { this.document = new OfficeDocument(FileUtil.toFile(fo)); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } + fo.addFileChangeListener(this); } @@ -69,26 +70,24 @@ public class OfficeDocumentSupport implements OfficeDocumentCookie, OpenCookie, try { ZipMounter.getZipMounter().mountZipFile(file); isMounted = true; - } - catch (IOException ioe) { + } catch (IOException ioe) { ErrorManager.getDefault().notify(ioe); - } - catch (PropertyVetoException pve) { + } catch (PropertyVetoException pve) { ErrorManager.getDefault().notify(pve); } } - public void open () { + public void open() { File file = FileUtil.toFile(dataObj.getPrimaryFile()); OfficeSettings settings = OfficeSettings.getDefault(); File soffice = new File(settings.getOfficeDirectory().getPath( - File.separator + "soffice")); + File.separator + "soffice")); try { - Process p = Runtime.getRuntime ().exec (new String[] { - soffice.getAbsolutePath(), file.getAbsolutePath () - }); + Process p = Runtime.getRuntime().exec(new String[] { + soffice.getAbsolutePath(), file.getAbsolutePath() + }); } catch (IOException ioe) { ErrorManager.getDefault().notify(ioe); } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelCookie.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelCookie.java index 1e4f701234bd..1c782ae6bf22 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelCookie.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelCookie.java @@ -21,8 +21,7 @@ package org.openoffice.netbeans.modules.office.actions; import java.io.File; import org.openide.nodes.Node; -public interface ParcelCookie extends Node.Cookie -{ +public interface ParcelCookie extends Node.Cookie { File getFile(); String getLanguage(); diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorEditorSupport.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorEditorSupport.java index 00402b93409d..c4378ceff24d 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorEditorSupport.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorEditorSupport.java @@ -32,7 +32,8 @@ import org.openoffice.netbeans.modules.office.loader.ParcelDescriptorDataObject; /** Support for editing a data object as text. */ // Replace OpenCookie with EditCookie or maybe ViewCookie as desired: -public class ParcelDescriptorEditorSupport extends DataEditorSupport implements EditorCookie, OpenCookie, CloseCookie, PrintCookie { +public class ParcelDescriptorEditorSupport extends DataEditorSupport implements + EditorCookie, OpenCookie, CloseCookie, PrintCookie { /** Create a new editor support. * @param obj the data object whose primary file will be edited as text @@ -51,12 +52,15 @@ public class ParcelDescriptorEditorSupport extends DataEditorSupport implements if (!super.notifyModified()) { return false; } + ParcelDescriptorDataObject obj = (ParcelDescriptorDataObject)getDataObject(); + if (obj.getCookie(SaveCookie.class) == null) { obj.setModified(true); // You must implement this method on the object: obj.addSaveCookie(new Save()); } + return true; } @@ -66,11 +70,13 @@ public class ParcelDescriptorEditorSupport extends DataEditorSupport implements protected void notifyUnmodified() { ParcelDescriptorDataObject obj = (ParcelDescriptorDataObject)getDataObject(); SaveCookie save = (SaveCookie)obj.getCookie(SaveCookie.class); + if (save != null) { // You must implement this method on the object: obj.removeSaveCookie(save); obj.setModified(false); } + super.notifyUnmodified(); } @@ -111,7 +117,8 @@ public class ParcelDescriptorEditorSupport extends DataEditorSupport implements * @throws IOException if the lock could not be taken */ protected FileLock takeLock() throws IOException { - return ((ParcelDescriptorDataObject)getDataObject()).getPrimaryEntry().takeLock(); + return ((ParcelDescriptorDataObject) + getDataObject()).getPrimaryEntry().takeLock(); } /** Find the editor support this environment represents. @@ -120,7 +127,8 @@ public class ParcelDescriptorEditorSupport extends DataEditorSupport implements * @return the editor support */ public CloneableOpenSupport findCloneableOpenSupport() { - return (ParcelDescriptorEditorSupport)getDataObject().getCookie(ParcelDescriptorEditorSupport.class); + return (ParcelDescriptorEditorSupport)getDataObject().getCookie( + ParcelDescriptorEditorSupport.class); } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserCookie.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserCookie.java index 21091196b0e8..0e7e4226d657 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserCookie.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserCookie.java @@ -22,8 +22,7 @@ import org.w3c.dom.NodeList; import javax.swing.event.ChangeListener; import org.openide.nodes.Node; -public interface ParcelDescriptorParserCookie extends Node.Cookie -{ +public interface ParcelDescriptorParserCookie extends Node.Cookie { // should return a NodeList of org.w3c.dom.Element NodeList getScriptElements(); diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserSupport.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserSupport.java index 7d71560bce59..f3f105679677 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserSupport.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserSupport.java @@ -32,50 +32,45 @@ import org.openide.filesystems.*; import org.openide.xml.XMLUtil; public class ParcelDescriptorParserSupport - implements ParcelDescriptorParserCookie, FileChangeListener -{ + implements ParcelDescriptorParserCookie, FileChangeListener { private FileObject fo; private Document document; private Set listeners; - public ParcelDescriptorParserSupport(FileObject fo) - { + public ParcelDescriptorParserSupport(FileObject fo) { this.fo = fo; fo.addFileChangeListener(this); } - private synchronized void parseFile() - { + private synchronized void parseFile() { File file = FileUtil.toFile(fo); InputSource is; try { is = new InputSource(new FileInputStream(file)); - } - catch (FileNotFoundException fnfe) { + } catch (FileNotFoundException fnfe) { System.out.println("Couldn't find file: " + file.getName()); return; } document = null; + try { document = XMLUtil.parse(is, false, false, null, null); - } - catch (IOException ioe) { + } catch (IOException ioe) { System.out.println("IO Error parsing file: " + file.getName()); - } - catch (SAXException se) { + } catch (SAXException se) { System.out.println("Sax Error parsing file: " + file.getName()); } } - public synchronized NodeList getScriptElements() - { + public synchronized NodeList getScriptElements() { if (document == null) parseFile(); if (document != null) return document.getElementsByTagName("script"); + return null; } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderCookie.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderCookie.java index 778bd208b570..6a17ee13ab31 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderCookie.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderCookie.java @@ -20,8 +20,7 @@ package org.openoffice.netbeans.modules.office.actions; import org.openide.nodes.Node; -public interface ParcelFolderCookie extends Node.Cookie -{ +public interface ParcelFolderCookie extends Node.Cookie { void generate(); boolean configure(); diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderSupport.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderSupport.java index bf310bc8b2c0..ce0ac563b0a5 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderSupport.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderSupport.java @@ -58,8 +58,7 @@ import org.openoffice.idesupport.zip.ParcelZipper; import org.openoffice.idesupport.filter.FileFilter; import org.openoffice.idesupport.ui.ConfigurePanel; -public class ParcelFolderSupport implements ParcelFolderCookie -{ +public class ParcelFolderSupport implements ParcelFolderCookie { protected ParcelFolder parcelFolder; private ConfigurePanel configuror = null; @@ -72,8 +71,7 @@ public class ParcelFolderSupport implements ParcelFolderCookie if (descriptor == null) { return ""; - } - else { + } else { return descriptor.getLanguage(); } } @@ -83,8 +81,7 @@ public class ParcelFolderSupport implements ParcelFolderCookie if (descriptor == null) { return ""; - } - else { + } else { return descriptor.getLanguageProperty("classpath"); } } @@ -97,8 +94,7 @@ public class ParcelFolderSupport implements ParcelFolderCookie try { descriptor.write(); - } - catch (IOException ioe) { + } catch (IOException ioe) { ErrorManager.getDefault().notify(ioe); } } @@ -108,7 +104,7 @@ public class ParcelFolderSupport implements ParcelFolderCookie FileObject primary = parcelFolder.getPrimaryFile(); File contents = FileUtil.toFile( - primary.getFileObject(ParcelZipper.CONTENTS_DIRNAME)); + primary.getFileObject(ParcelZipper.CONTENTS_DIRNAME)); return ParcelDescriptor.getParcelDescriptor(contents); } @@ -128,32 +124,32 @@ public class ParcelFolderSupport implements ParcelFolderCookie // use the Parcel Recipe directory as the target directory File targetDir = FileUtil.toFile(parcelFolder.getPrimaryFile()); File targetfile = new File(targetDir, File.separator + - parcelBase.getName() + "." + ParcelZipper.PARCEL_EXTENSION); + parcelBase.getName() + "." + ParcelZipper.PARCEL_EXTENSION); boolean proceed = configure(); + if (!proceed) { return; } final OutputWriter out = ParcelSupport.getOutputWindowWriter(parcelDir.getName() + " (generating)"); + try { out.println("Generating: " + parcelDir.getName(), null); - ParcelZipper.getParcelZipper().zipParcel(contentsDir, targetfile, node.getFileFilter()); + ParcelZipper.getParcelZipper().zipParcel(contentsDir, targetfile, + node.getFileFilter()); out.println("\nGENERATION SUCCESSFUL."); out.println("\nRight click on the generated parcel to deploy it"); if (targetDir.equals(parcelDir)) { parcelBase.refresh(true); } - } - catch (IOException ioe) { - out.println("GENERATION FAILED: reason: " + ioe.getClass().getName() + ": "+ ioe.getMessage()); - } - finally - { - if( out != null) - { + } catch (IOException ioe) { + out.println("GENERATION FAILED: reason: " + ioe.getClass().getName() + ": " + + ioe.getMessage()); + } finally { + if (out != null) { out.close(); } } @@ -164,33 +160,32 @@ public class ParcelFolderSupport implements ParcelFolderCookie FileObject primary = parcelFolder.getPrimaryFile(); File contents = FileUtil.toFile( - primary.getFileObject(ParcelZipper.CONTENTS_DIRNAME)); + primary.getFileObject(ParcelZipper.CONTENTS_DIRNAME)); ArrayList<String> classpath = getConfigureClasspath(); classpath.add(contents.getAbsolutePath()); try { ParcelDescriptor descriptor = getParcelDescriptor(); + if (descriptor == null) { descriptor = ParcelDescriptor.createParcelDescriptor(contents); } if (configuror == null) { configuror = new ConfigurePanel(contents.getAbsolutePath(), - classpath, descriptor); - } - else { + classpath, descriptor); + } else { configuror.reload(contents.getAbsolutePath(), classpath, - descriptor); + descriptor); } - } - catch (IOException ioe) { + } catch (IOException ioe) { ErrorManager.getDefault().notify(ioe); return false; } DialogDescriptor dd = new DialogDescriptor(configuror, - ConfigurePanel.DIALOG_TITLE); + ConfigurePanel.DIALOG_TITLE); Dialog dialog = TopManager.getDefault().createDialog(dd); dialog.show(); @@ -199,14 +194,13 @@ public class ParcelFolderSupport implements ParcelFolderCookie try { ParcelDescriptor descriptor = configuror.getConfiguration(); descriptor.write(); - } - catch (Exception e) { + } catch (Exception e) { ErrorManager.getDefault().notify(e); } - } - else { + } else { return false; } + return true; } @@ -214,30 +208,30 @@ public class ParcelFolderSupport implements ParcelFolderCookie ArrayList<String> result = new ArrayList<String>(); String classpath = NbClassPath.createRepositoryPath().getClassPath(); - if ( System.getProperty( "os.name" ).startsWith( "Windows" ) ) - { + + if (System.getProperty("os.name").startsWith("Windows")) { // under windows path is enclosed by quotes // e.g. C:\path1;d:\path2 would appear as // "C:\path1;d:\path2" therefore for us // we need to remove 1 character at either end of the // classpath returned from "createRepositoryPath().getClassPath()" - if ( classpath.startsWith("\"") && classpath.endsWith("\"") ) - { - StringBuffer buff = new StringBuffer(classpath); - buff.delete(0,1); - buff.delete( buff.length() - 1, buff.length() ); - classpath = buff.toString(); + if (classpath.startsWith("\"") && classpath.endsWith("\"")) { + StringBuffer buff = new StringBuffer(classpath); + buff.delete(0, 1); + buff.delete(buff.length() - 1, buff.length()); + classpath = buff.toString(); } } + StringTokenizer tokens = new StringTokenizer(classpath, File.pathSeparator); - while(tokens.hasMoreTokens()) + while (tokens.hasMoreTokens()) result.addElement(tokens.nextToken()); OfficeSettings settings = OfficeSettings.getDefault(); File classesDir = new File(settings.getOfficeDirectory().getPath( - File.separator + "program" + File.separator + "classes")); + File.separator + "program" + File.separator + "classes")); File[] jarfiles = classesDir.listFiles(); for (int i = 0; i < jarfiles.length; i++) diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelSupport.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelSupport.java index ab05d89d687d..381be44ccadb 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelSupport.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelSupport.java @@ -44,8 +44,7 @@ import org.openoffice.netbeans.modules.office.utils.NagDialog; import org.openoffice.netbeans.modules.office.utils.ZipMounter; import org.openoffice.netbeans.modules.office.utils.ManifestParser; -public class ParcelSupport implements ParcelCookie -{ +public class ParcelSupport implements ParcelCookie { private FileObject fo; private ParcelZipper zipper = ParcelZipper.getParcelZipper(); private String language = null; @@ -62,26 +61,23 @@ public class ParcelSupport implements ParcelCookie if (language == null) { try { language = zipper.getParcelLanguage(getFile()); - } - catch (IOException ioe) { + } catch (IOException ioe) { return null; } } + return language; } - public void mount() - { + public void mount() { File parcel = FileUtil.toFile(fo); if (parcel != null) { try { ZipMounter.getZipMounter().mountZipFile(parcel); - } - catch (IOException ioe) { + } catch (IOException ioe) { ErrorManager.getDefault().notify(ioe); - } - catch (PropertyVetoException pve) { + } catch (PropertyVetoException pve) { ErrorManager.getDefault().notify(pve); } } @@ -93,12 +89,12 @@ public class ParcelSupport implements ParcelCookie if (!target.isDirectory()) { OfficeSettings settings = OfficeSettings.getDefault(); String message = "If you already have this document open in " + - "Office, please close it before continuing. Click OK to " + - "continue deployment."; + "Office, please close it before continuing. Click OK to " + + "continue deployment."; if (settings.getWarnBeforeDocDeploy()) { NagDialog warning = NagDialog.createConfirmationDialog( - message, "Show this message in future", true); + message, "Show this message in future", true); boolean result = warning.show(); @@ -117,36 +113,35 @@ public class ParcelSupport implements ParcelCookie if (!zipper.isOverwriteNeeded(source, target)) if (!promptForOverwrite(source, target)) return false; - } - catch (IOException ioe) { - out.println("DEPLOYMENT FAILED: reason: " + - ioe.getClass().getName() + ": "+ ioe.getMessage()); - return false; + } catch (IOException ioe) { + out.println("DEPLOYMENT FAILED: reason: " + + ioe.getClass().getName() + ": " + ioe.getMessage()); + return false; } try { out.println("Deploying: " + fo.getName() + - "\nTo: " + target.getAbsolutePath(), null); + "\nTo: " + target.getAbsolutePath(), null); zipper.deployParcel(source, target); out.println("\nDEPLOYMENT SUCCESSFUL."); FileObject[] fileobjs = FileUtil.fromFile(target); + if (fileobjs != null) { for (int i = 0; i < fileobjs.length; i++) fileobjs[i].refresh(true); } - } - catch (IOException ioe) { - out.println("DEPLOYMENT FAILED: reason: " + - ioe.getClass().getName() + ": "+ ioe.getMessage()); - return false; - } - finally { - if( out != null) + } catch (IOException ioe) { + out.println("DEPLOYMENT FAILED: reason: " + + ioe.getClass().getName() + ": " + ioe.getMessage()); + return false; + } finally { + if (out != null) out.close(); } + return true; } @@ -156,19 +151,20 @@ public class ParcelSupport implements ParcelCookie io.setOutputVisible(true); OutputWriter out = io.getOut(); + try { out.reset(); - } - catch( IOException e) { + } catch (IOException e) { e.printStackTrace(System.err); } + out.println(Calendar.getInstance().getTime() + ":\n"); return out; } private boolean promptForOverwrite(File source, File target) { String message = source.getName() + " has already been deployed " + - "to this target. Do you wish to overwrite it?"; + "to this target. Do you wish to overwrite it?"; NotifyDescriptor d = new NotifyDescriptor.Confirmation( message, NotifyDescriptor.OK_CANCEL_OPTION); diff --git a/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystem.java b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystem.java index e86f5e03ae3c..6081445d258a 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystem.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystem.java @@ -42,8 +42,7 @@ import org.openide.util.NbBundle; * OpenOffice.org Document filesystem. */ public class OpenOfficeDocFileSystem - extends AbstractFileSystem -{ + extends AbstractFileSystem { public static final String SCRIPTS_ROOT = "Scripts"; // must be a folder public static final String SEPARATOR = "/"; // zip file separator @@ -74,6 +73,7 @@ public class OpenOfficeDocFileSystem static { // Identify the type of OS String osname = System.getProperty("os.name"); + if (osname.startsWith("Mac OS")) osType = OS_MACOS; else if (osname.startsWith("Windows")) @@ -85,8 +85,7 @@ public class OpenOfficeDocFileSystem /** * Default constructor. Initializes new OpenOffice filesystem. */ - public OpenOfficeDocFileSystem() - { + public OpenOfficeDocFileSystem() { // Create the filesystem cache cache = new HashMap(); @@ -116,8 +115,7 @@ public class OpenOfficeDocFileSystem /** * Constructor. Initializes new OpenOffice filesystem with FS capability. */ - public OpenOfficeDocFileSystem(FileSystemCapability cap) - { + public OpenOfficeDocFileSystem(FileSystemCapability cap) { this(); setCapability(cap); } @@ -127,8 +125,7 @@ public class OpenOfficeDocFileSystem * NOTE: The scope is not a part of the signature so it is impossible * to mount the same archive more than once. */ - public static String computeSystemName(File file) - { + public static String computeSystemName(File file) { return OpenOfficeDocFileSystem.class.getName() + "[" + file + "]"; } @@ -137,21 +134,19 @@ public class OpenOfficeDocFileSystem /** * Provides the 'human readable' name of the instance of the filesystem. */ - public String getDisplayName() - { + public String getDisplayName() { if (!isValid()) return NbBundle.getMessage(OpenOfficeDocFileSystem.class, - "LAB_invalid_file_system", ((docFile != null)? docFile.toString(): "")); + "LAB_invalid_file_system", ((docFile != null) ? docFile.toString() : "")); else return NbBundle.getMessage(OpenOfficeDocFileSystem.class, - "LAB_valid_file_system", docFile.toString()); + "LAB_valid_file_system", docFile.toString()); } /** * Retrieves the 'document' property. */ - public File getDocument() - { + public File getDocument() { return docFile; } @@ -162,39 +157,45 @@ public class OpenOfficeDocFileSystem // of the root file object) should cause everything using this filesystem // to refresh. The system name must change and refreshRoot should be used // to ensure that everything is correctly updated. + public synchronized void setDocument(File file) - throws java.beans.PropertyVetoException, java.io.IOException - { -System.out.println("OpenOfficeDocFileSystem.setDocument: file=\"" + file.toString() + "\""); - if(!file.exists() || !file.isFile()) { + throws java.beans.PropertyVetoException, java.io.IOException { + System.out.println("OpenOfficeDocFileSystem.setDocument: file=\"" + + file.toString() + "\""); + + if (!file.exists() || !file.isFile()) { IOException ioe = new IOException( file.toString() + " does not exist"); ErrorManager.getDefault().annotate(ioe, NbBundle.getMessage( - OpenOfficeDocFileSystem.class, "EXC_root_dir_does_not_exist", - file.toString())); + OpenOfficeDocFileSystem.class, "EXC_root_dir_does_not_exist", + file.toString())); throw ioe; } + // update the document try { - updateDocument(); - } catch(IOException ioe) { + updateDocument(); + } catch (IOException ioe) { // cannot save all!!! -System.out.println("*** OpenOfficeDocFileSystem.setDocument:"); -System.out.println(" file: " + ((docFile != null)? docFile.toString(): "")); -System.out.println(" exception: " + ioe.getMessage()); + System.out.println("*** OpenOfficeDocFileSystem.setDocument:"); + System.out.println(" file: " + ((docFile != null) ? docFile.toString() : + "")); + System.out.println(" exception: " + ioe.getMessage()); } + // new document type verification!!! closeDocument(); + // open a new document try { openDocument(file); firePropertyChange(PROP_ROOT, null, refreshRoot()); setRefreshTime(REFRESH_TIME); - } catch(IOException ioe) { + } catch (IOException ioe) { // cannot open a new document!!! -System.out.println("*** OpenOfficeDocFileSystem.setDocument:"); -System.out.println(" file: " + ((file != null)? file.toString(): "")); -System.out.println(" exception: " + ioe.getMessage()); + System.out.println("*** OpenOfficeDocFileSystem.setDocument:"); + System.out.println(" file: " + ((file != null) ? file.toString() : "")); + System.out.println(" exception: " + ioe.getMessage()); } } @@ -203,8 +204,7 @@ System.out.println(" exception: " + ioe.getMessage()); * NOTE: The portion of the mounted document available to the user is * always editable. */ - public boolean isReadOnly() - { + public boolean isReadOnly() { return false; } @@ -213,8 +213,7 @@ System.out.println(" exception: " + ioe.getMessage()); * NOTE: The portion of the mounted document available to the user is * always editable. */ - public void setReadOnly(boolean flag) - { + public void setReadOnly(boolean flag) { // sorry! it is not supported. } @@ -224,8 +223,7 @@ System.out.println(" exception: " + ioe.getMessage()); * Participates in the environment configuration. * This is how you can affect the classpath for execution, compilation, etc. */ - public void prepareEnvironment(FileSystem.Environment environment) - { + public void prepareEnvironment(FileSystem.Environment environment) { // BUG: the compiller cannot access files within the OpenOffice document. //environment.addClassPath(docFile.toString()); } @@ -266,7 +264,7 @@ System.out.println(" exception: " + ioe.getMessage()); // The actions should typically be CookieActions looking for DataObject // cookies, where the object's primary file is on this type of filesystem. public SystemAction[] getActions() { -// ------>>>> UPDATE OPENOFFICE DOCUMENT <<<<------ + // ------>>>> UPDATE OPENOFFICE DOCUMENT <<<<------ return new SystemAction[] { SystemAction.get(SomeAction.class), null, // separator @@ -283,17 +281,18 @@ System.out.println(" exception: " + ioe.getMessage()); * to avoid retaining resources for too long etc. Filesystems should maintain correct * semantics regardless of whether and when this method is called. */ - public void removeNotify() - { + public void removeNotify() { setRefreshTime(REFRESH_OFF); // disable refresh + // update the document try { - updateDocument(); - } catch(IOException ioe) { + updateDocument(); + } catch (IOException ioe) { // cannot save all!!! -System.out.println("*** OpenOfficeDocFileSystem.removeNotify:"); -System.out.println(" exception: " + ioe.getMessage()); + System.out.println("*** OpenOfficeDocFileSystem.removeNotify:"); + System.out.println(" exception: " + ioe.getMessage()); } + closeDocument(); super.removeNotify(); } @@ -302,9 +301,8 @@ System.out.println(" exception: " + ioe.getMessage()); * Opens (mounts) an OpenOffice document. */ private void openDocument(File file) - throws IOException, PropertyVetoException - { - synchronized(cache) { + throws IOException, PropertyVetoException { + synchronized (cache) { setSystemName(computeSystemName(file)); docFile = file; zipFile = new ZipFile(docFile); @@ -316,19 +314,19 @@ System.out.println(" exception: " + ioe.getMessage()); /* * Closes the document and cleans up the cache. */ - private void closeDocument() - { - synchronized(cache) { + private void closeDocument() { + synchronized (cache) { // if a document mounted - close it - if(docFile != null) { + if (docFile != null) { // close the document archive - if(zipFile != null) { + if (zipFile != null) { try { zipFile.close(); - } catch(IOException ioe) { + } catch (IOException ioe) { // sorry! we can do nothing about it. } } + zipFile = null; // clean up cache scanDocument(new CleanStrategy()); @@ -341,21 +339,24 @@ System.out.println(" exception: " + ioe.getMessage()); /* * Creates a document cache. */ - private void cacheDocument(Enumeration entries, Strategy editables) - { + private void cacheDocument(Enumeration entries, Strategy editables) { Entry cacheEntry; ZipEntry archEntry; - synchronized(cache) { + + synchronized (cache) { cache.clear(); // root folder cacheEntry = new ReadWriteEntry(null); cache.put(cacheEntry.getName(), cacheEntry); + // the rest of items - while(entries.hasMoreElements()) { + while (entries.hasMoreElements()) { archEntry = (ZipEntry)entries.nextElement(); cacheEntry = new Entry(archEntry); - if(editables.evaluate(cacheEntry)) + + if (editables.evaluate(cacheEntry)) cacheEntry = new ReadWriteEntry(archEntry); + cache.put(cacheEntry.getName(), cacheEntry); } } // synchronized @@ -365,44 +366,51 @@ System.out.println(" exception: " + ioe.getMessage()); * Updates the document. */ private void updateDocument() - throws IOException - { - if(docFile == null) + throws IOException { + if (docFile == null) return; - synchronized(cache) { + + synchronized (cache) { ModifiedStrategy modifiedStrategy = new ModifiedStrategy(); scanDocument(modifiedStrategy); - if(isModified || modifiedStrategy.isModified()) - { + + if (isModified || modifiedStrategy.isModified()) { File tmpFile = null; + try { // create updated document tmpFile = File.createTempFile( - TMP_FILE_PREF, TMP_FILE_SUFX, docFile.getParentFile()); + TMP_FILE_PREF, TMP_FILE_SUFX, docFile.getParentFile()); saveDocument(tmpFile); - } catch(IOException ioe) { - if(tmpFile != null) + } catch (IOException ioe) { + if (tmpFile != null) tmpFile.delete(); + throw ioe; } + // close the document archive - if(zipFile != null) { + if (zipFile != null) { try { zipFile.close(); - } catch(IOException ioe) { + } catch (IOException ioe) { } } + zipFile = null; // create the document and backup File newFile = new File(docFile.getParentFile() + File.separator + - "~" + docFile.getName()); - if(newFile.exists()) + "~" + docFile.getName()); + + if (newFile.exists()) newFile.delete(); // delete old backup + docFile.renameTo(newFile); tmpFile.renameTo(docFile); // open the document archive zipFile = new ZipFile(docFile); } + isModified = false; } // synchronized } @@ -411,9 +419,8 @@ System.out.println(" exception: " + ioe.getMessage()); * Saves the document in a new archive. */ private void saveDocument(File file) - throws IOException - { - synchronized(cache) { + throws IOException { + synchronized (cache) { SaveStrategy saver = new SaveStrategy(file); scanDocument(saver); saver.close(); @@ -423,11 +430,11 @@ System.out.println(" exception: " + ioe.getMessage()); /* * Provides each individual entry in the cached document to an apraiser. */ - private void scanDocument(Strategy strategy) - { - synchronized(cache) { + private void scanDocument(Strategy strategy) { + synchronized (cache) { Iterator itr = cache.values().iterator(); - while(itr.hasNext()) { + + while (itr.hasNext()) { strategy.evaluate((Entry)itr.next()); } } // synchronized @@ -437,25 +444,29 @@ System.out.println(" exception: " + ioe.getMessage()); * Retrieves or creates a file. */ private Entry getFileEntry(String name) - throws IOException - { + throws IOException { Entry cEntry = null; - synchronized(cache) { + + synchronized (cache) { cEntry = (Entry)cache.get(name); - if(cEntry == null) { + + if (cEntry == null) { // create a new file ZipEntry zEntry = new ZipEntry(name); zEntry.setTime(new Date().getTime()); cEntry = new Entry(zEntry); - if(!editableStrategy.evaluate(cEntry)) { + + if (!editableStrategy.evaluate(cEntry)) { throw new IOException( "cannot create/edit readonly file"); // I18N } + cEntry = new ReadWriteEntry(zEntry); cache.put(cEntry.getName(), cEntry); isModified = true; } } // synchronized + return cEntry; } @@ -463,12 +474,13 @@ System.out.println(" exception: " + ioe.getMessage()); * Retrieves or creates a folder. */ private Entry getFolderEntry(String name) - throws IOException - { + throws IOException { Entry cEntry = null; - synchronized(cache) { + + synchronized (cache) { cEntry = (Entry)cache.get(name); - if(cEntry == null) { + + if (cEntry == null) { // create a new folder ZipEntry zEntry = new ZipEntry(name + SEPARATOR); zEntry.setMethod(ZipEntry.STORED); @@ -477,19 +489,22 @@ System.out.println(" exception: " + ioe.getMessage()); zEntry.setCrc(crc.getValue()); zEntry.setTime(new Date().getTime()); cEntry = new Entry(zEntry); - if(!editableStrategy.evaluate(cEntry)) { + + if (!editableStrategy.evaluate(cEntry)) { throw new IOException( "cannot create folder"); // I18N } + cEntry = new ReadWriteEntry(zEntry); cEntry.getOutputStream(); // sets up modified flag cache.put(cEntry.getName(), cEntry); isModified = true; } else { - if(!cEntry.isFolder()) + if (!cEntry.isFolder()) cEntry = null; } } // synchronized + return cEntry; } @@ -502,20 +517,23 @@ System.out.println(" exception: " + ioe.getMessage()); * the rest of the code. * WORKAROUND: we have to strip leading '/' if it is in the name. */ - private static String zipName(String name) - { - String zname = ((name.startsWith(File.separator))? - name.substring(File.separator.length()): name); - switch(osType) { + private static String zipName(String name) { + String zname = ((name.startsWith(File.separator)) ? + name.substring(File.separator.length()) : name); + + switch (osType) { case OS_MACOS: zname = zname.replace(':', '/'); // ':' by '/' break; + case OS_WINDOWS: zname = zname.replace((char)0x5c, '/'); // '\' by '/' break; + default: break; } + return zname; } @@ -526,14 +544,15 @@ System.out.println(" exception: " + ioe.getMessage()); * not affect the file's presence or name. */ private class InfoImpl - implements Info - { + implements Info { public boolean folder(String name) { - synchronized(cache) { + synchronized (cache) { String zname = zipName(name); Entry entry = (Entry)cache.get(zname); - if(entry != null) + + if (entry != null) return entry.isFolder(); + // logical zip file entry childrenStrategy.setParent(zname); scanDocument(childrenStrategy); @@ -542,14 +561,14 @@ System.out.println(" exception: " + ioe.getMessage()); } public Date lastModified(String name) { - synchronized(cache) { + synchronized (cache) { Entry entry = (Entry)cache.get(zipName(name)); - return new Date((entry != null)? entry.getTime(): 0L); + return new Date((entry != null) ? entry.getTime() : 0L); } } public boolean readOnly(String name) { - synchronized(cache) { + synchronized (cache) { Entry entry = (Entry)cache.get(zipName(name)); return entry && entry.isReadOnly(); } @@ -564,24 +583,22 @@ System.out.println(" exception: " + ioe.getMessage()); } public long size(String name) { - synchronized(cache) { + synchronized (cache) { Entry entry = (Entry)cache.get(zipName(name)); - return (entry != null)? entry.getSize(): 0; + return (entry != null) ? entry.getSize() : 0; } // synchronized } public InputStream inputStream(String name) - throws FileNotFoundException - { - synchronized(cache) { + throws FileNotFoundException { + synchronized (cache) { Entry entry = (Entry)cache.get(zipName(name)); - return (entry != null)? entry.getInputStream(): null; + return (entry != null) ? entry.getInputStream() : null; } // synchronized } public OutputStream outputStream(String name) - throws IOException - { + throws IOException { return getFileEntry(zipName(name)).getOutputStream(); } @@ -589,19 +606,18 @@ System.out.println(" exception: " + ioe.getMessage()); // This only means that you should define how the file should be locked // to the outside world--perhaps it does not need to be. public void lock(String name) - throws IOException - { -/* - File file = getFile(name); - if (file.exists() == true && file.canWrite() == false) { - IOException ioe = new IOException("file " + file + - " could not be locked"); - ErrorManager.getDefault().annotate(ioe, NbBundle.getMessage( - OpenOfficeDocFileSystem.class, "EXC_file_could_not_be_locked", - file.getName(), getDisplayName(), file.getPath())); - throw ioe; - } -*/ + throws IOException { + /* + File file = getFile(name); + if (file.exists() == true && file.canWrite() == false) { + IOException ioe = new IOException("file " + file + + " could not be locked"); + ErrorManager.getDefault().annotate(ioe, NbBundle.getMessage( + OpenOfficeDocFileSystem.class, "EXC_file_could_not_be_locked", + file.getName(), getDisplayName(), file.getPath())); + throw ioe; + } + */ } public void unlock(String name) { @@ -620,80 +636,90 @@ System.out.println(" exception: " + ioe.getMessage()); * Operations that change the available files. */ private class ChangeImpl - implements Change - { + implements Change { public void createFolder(String name) - throws IOException - { - synchronized(cache) { + throws IOException { + synchronized (cache) { String zname = zipName(name); - if(cache.get(zname) != null) { + + if (cache.get(zname) != null) { throw new IOException( "cannot create new folder: " + name); // I18N } + getFolderEntry(zname); } // synchronized } public void createData(String name) - throws IOException - { - synchronized(cache) { + throws IOException { + synchronized (cache) { String zname = zipName(name); - if(cache.get(zname) != null) { + + if (cache.get(zname) != null) { throw new IOException( "cannot create new data: " + name); // I18N } + OutputStream os = getFileEntry(zname).getOutputStream(); os.close(); } // synchronized } public void rename(String oldName, String newName) - throws IOException - { + throws IOException { String oname = zipName(oldName); String nname = zipName(newName); - if((oname.length() == 0) || (nname.length() == 0)) { + + if ((oname.length() == 0) || (nname.length() == 0)) { throw new IOException( "cannot move or rename the root folder"); // I18N } - synchronized(cache) { - if(cache.get(nname) != null) { + + synchronized (cache) { + if (cache.get(nname) != null) { throw new IOException( "target file/folder " + newName + " exists"); // I18N } + Entry entry = (Entry)cache.get(oname); - if(entry == null) { + + if (entry == null) { throw new IOException( "there is no such a file/folder " + oldName); // I18N } - if(entry.isReadOnly()) { + + if (entry.isReadOnly()) { throw new IOException( "file/folder " + oldName + " is readonly"); // I18N } + entry.rename(nname); - if(!editableStrategy.evaluate(entry)) { + + if (!editableStrategy.evaluate(entry)) { entry.rename(oname); throw new IOException( "cannot create file/folder"); // I18N } + cache.remove(oname); cache.put(entry.getName(), entry); } // synchronized } public void delete(String name) - throws IOException - { + throws IOException { String zname = zipName(name); - if(zname.length() == 0) { + + if (zname.length() == 0) { throw new IOException( "cannot delete the root folder"); // I18N } - synchronized(cache) { + + synchronized (cache) { Entry entry = (Entry)cache.remove(zname); - if(entry != null) { + + if (entry != null) { // BUG: this is the design bug. Cache has to // remember that the entry was removed. isModified = true; @@ -707,17 +733,17 @@ System.out.println(" exception: " + ioe.getMessage()); * Operation which provides the directory structure. */ private class ListImpl - implements List - { - public String[] children(String name) - { + implements List { + public String[] children(String name) { String[] children = null; - synchronized(cache) { + + synchronized (cache) { String zname = zipName(name); Entry entry = (Entry)cache.get(zname); - if(entry != null) { + + if (entry != null) { // real zip file entry - if(entry.isFolder()) { + if (entry.isFolder()) { childrenStrategy.setParent(entry.getName()); } } else { @@ -725,9 +751,11 @@ System.out.println(" exception: " + ioe.getMessage()); // (portion of the path of a real zip file entry) childrenStrategy.setParent(zname); } + scanDocument(childrenStrategy); children = childrenStrategy.getChildren(); } // synchronize + return children; } @@ -781,8 +809,7 @@ System.out.println(" exception: " + ioe.getMessage()); /* ----------------------------------------------------------- * This interface hides an action will be performed on an entry. */ - private interface Strategy - { + private interface Strategy { boolean evaluate(Entry entry); } @@ -790,17 +817,14 @@ System.out.println(" exception: " + ioe.getMessage()); * Recognizes editable (read-write) entires */ private class EditableStrategy - implements Strategy - { + implements Strategy { private String scope; - public EditableStrategy(String scope) - { + public EditableStrategy(String scope) { this.scope = scope; } - public boolean evaluate(Entry entry) - { + public boolean evaluate(Entry entry) { // recognizes all entries in a subtree of the // 'scope' as editable entries return entry && entry.getName().startsWith(scope); @@ -811,55 +835,58 @@ System.out.println(" exception: " + ioe.getMessage()); * Recognizes and accumulates immediate children of the parent. */ private class ChildrenStrategy - implements Strategy - { + implements Strategy { private String parent; private Collection children = new HashSet(); - public void setParent(String name) - { - parent = (name.length() > 0)? (name + SEPARATOR): ""; - if(children == null) + public void setParent(String name) { + parent = (name.length() > 0) ? (name + SEPARATOR) : ""; + + if (children == null) children = (java.util.List)new LinkedList(); + children.clear(); } - public boolean evaluate(Entry entry) - { + public boolean evaluate(Entry entry) { // do not accept "children" of a file // ignore "read only" part of the filesystem - if(!entry.isReadOnly()) { + if (!entry.isReadOnly()) { // identify a child - if( (entry.getName().length() > 0) && - (entry.getName().startsWith(parent))) - { + if ((entry.getName().length() > 0) && + (entry.getName().startsWith(parent))) { // identify an immediate child String child = entry.getName(); - if(parent.length() > 0) { + + if (parent.length() > 0) { child = entry.getName().substring(parent.length()); } + int idx = child.indexOf(SEPARATOR); - if(idx > 0) // more path elements ahead + + if (idx > 0) // more path elements ahead child = child.substring(0, idx); + return children.add(child); } } + return false; } - public int countChildren() - { + public int countChildren() { return children.size(); } - public String[] getChildren() - { + public String[] getChildren() { String[] chn = new String[children.size()]; Iterator itr = children.iterator(); int idx = 0; - while(itr.hasNext()) { + + while (itr.hasNext()) { chn[idx++] = (String)itr.next(); } + return chn; } } @@ -868,18 +895,15 @@ System.out.println(" exception: " + ioe.getMessage()); * Recognizes cache entries which have to be save into new archive. */ private class ModifiedStrategy - implements Strategy - { + implements Strategy { private boolean modified; - public boolean evaluate(Entry entry) - { + public boolean evaluate(Entry entry) { modified |= entry.isModified(); return entry.isModified(); } - public boolean isModified() - { + public boolean isModified() { return modified; } } @@ -888,35 +912,33 @@ System.out.println(" exception: " + ioe.getMessage()); * Saves each entry in the filesystem cache. */ private class SaveStrategy - implements Strategy - { + implements Strategy { ZipOutputStream docos; IOException ioexp; public SaveStrategy(File newdoc) - throws IOException - { + throws IOException { docos = new ZipOutputStream(new FileOutputStream(newdoc)); ioexp = null; // success by default } - public boolean evaluate(Entry entry) - { - if(entry.getName().length() == 0) + public boolean evaluate(Entry entry) { + if (entry.getName().length() == 0) return false; + try { entry.save(docos); - } catch(IOException ioe) { - if(ioexp == null) + } catch (IOException ioe) { + if (ioexp == null) ioexp = ioe; } + return true; } public void close() - throws IOException - { - if(docos != null) { + throws IOException { + if (docos != null) { try { docos.close(); } catch (IOException ioe) { @@ -924,7 +946,8 @@ System.out.println(" exception: " + ioe.getMessage()); } finally { docos = null; } - if(ioexp != null) { + + if (ioexp != null) { throw ioexp; } } @@ -935,15 +958,14 @@ System.out.println(" exception: " + ioe.getMessage()); * Cleans each entiry in the filesystem cache. */ private class CleanStrategy - implements Strategy - { - public boolean evaluate(Entry entry) - { + implements Strategy { + public boolean evaluate(Entry entry) { try { entry.clean(); - } catch(java.lang.Exception exp) { + } catch (java.lang.Exception exp) { // sorry! can do nothing about it. } + return true; } } @@ -951,25 +973,24 @@ System.out.println(" exception: " + ioe.getMessage()); /* ----------------------------------------------------------- * ReadOnly cache entry */ - private class Entry - { + private class Entry { private String name; private boolean folder; private long size; private long time; private File node; // data files only - public Entry(ZipEntry entry) - { - if(entry != null) { + public Entry(ZipEntry entry) { + if (entry != null) { name = entry.getName(); folder = entry.isDirectory(); size = entry.getSize(); time = entry.getTime(); + // removes tail file separator from a folder name - if(folder && name.endsWith(SEPARATOR)) { + if (folder && name.endsWith(SEPARATOR)) { name = name.substring( - 0, name.length() - SEPARATOR.length()); + 0, name.length() - SEPARATOR.length()); } } else { // 'null' is special cace of root folder @@ -980,65 +1001,56 @@ System.out.println(" exception: " + ioe.getMessage()); } } - public boolean isReadOnly() - { + public boolean isReadOnly() { return true; } - public boolean isFolder() - { + public boolean isFolder() { return folder; } - public boolean isModified() - { + public boolean isModified() { return false; } - public String getName() - { + public String getName() { return name; } - public long getSize() - { + public long getSize() { return size; } - public long getTime() - { + public long getTime() { // adjust last modified time to the java.io.File - return (time >= 0)? time: 0; + return (time >= 0) ? time : 0; } public InputStream getInputStream() - throws FileNotFoundException - { + throws FileNotFoundException { return !isFolder() ? new FileInputStream(getFile()) : null; } public OutputStream getOutputStream() - throws IOException - { + throws IOException { return null; } public void rename(String name) - throws IOException - { + throws IOException { // BUG: this is the design bug. Cache has to manage such kind // of operation in order to keep the data integrity. this.name = name; } public void save(ZipOutputStream arch) - throws IOException - { + throws IOException { InputStream is = null; ZipEntry entry = new ZipEntry( - getName() + ((isFolder())? SEPARATOR: "")); + getName() + ((isFolder()) ? SEPARATOR : "")); + try { - if(isFolder()) { + if (isFolder()) { // folder entry.setMethod(ZipEntry.STORED); entry.setSize(0); @@ -1048,55 +1060,56 @@ System.out.println(" exception: " + ioe.getMessage()); arch.putNextEntry(entry); } else { // file - if(!isModified()) + if (!isModified()) entry.setTime(getTime()); else entry.setTime(node.lastModified()); + arch.putNextEntry(entry); is = getInputStream(); FileUtil.copy(is, arch); } } finally { // close streams - if(is != null) { + if (is != null) { try { is.close(); - } catch(java.io.IOException ioe) { + } catch (java.io.IOException ioe) { // sorry! can do nothing about it. } } - if(arch != null) + + if (arch != null) arch.closeEntry(); } } public void clean() - throws IOException - { - if(node != null) + throws IOException { + if (node != null) node.delete(); } - public String toString() - { + public String toString() { return ( - ((isReadOnly())? "RO ": "RW ") + - ((isFolder())? "D": "F") + - " \"" + getName() + "\""); + ((isReadOnly()) ? "RO " : "RW ") + + ((isFolder()) ? "D" : "F") + + " \"" + getName() + "\""); } /* package */ File getFile() - throws FileNotFoundException - { - if(node == null) { + throws FileNotFoundException { + if (node == null) { try { node = File.createTempFile(TMP_FILE_PREF, TMP_FILE_SUFX); - // copy the file from archive to the cache - OutputStream nos = null; - InputStream zis = null; + // copy the file from archive to the cache + OutputStream nos = null; + InputStream zis = null; + try { ZipEntry entry = zipFile.getEntry(getName()); - if(entry != null) { + + if (entry != null) { // copy existing file to the cache zis = zipFile.getInputStream(entry); nos = new FileOutputStream(node); @@ -1104,28 +1117,31 @@ System.out.println(" exception: " + ioe.getMessage()); } } finally { // close streams - if(nos != null) { + if (nos != null) { try { nos.close(); - } catch(java.io.IOException ioe) { + } catch (java.io.IOException ioe) { } } - if(zis != null) { + + if (zis != null) { try { zis.close(); - } catch(java.io.IOException ioe) { + } catch (java.io.IOException ioe) { } } } - } catch(java.lang.Exception exp) { + } catch (java.lang.Exception exp) { // delete cache file - if(node != null) + if (node != null) node.delete(); + node = null; throw new FileNotFoundException( "cannot access file: " + getName()); // I18N } } + return node; } @@ -1135,36 +1151,30 @@ System.out.println(" exception: " + ioe.getMessage()); * ReadWrite cache entry */ private class ReadWriteEntry - extends Entry - { + extends Entry { private boolean modified; // 'null' is special cace of root folder - public ReadWriteEntry(ZipEntry entry) - { + public ReadWriteEntry(ZipEntry entry) { super(entry); } - public boolean isReadOnly() - { + public boolean isReadOnly() { return false; } - public boolean isModified() - { + public boolean isModified() { return modified; } public void rename(String name) - throws IOException - { + throws IOException { modified = true; super.rename(name); } public OutputStream getOutputStream() - throws IOException - { + throws IOException { modified = true; return !isFolder() ? new FileOutputStream(getFile()) : null; } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystemBeanInfo.java b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystemBeanInfo.java index 4e4b8fb54404..ad3d18e154db 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystemBeanInfo.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystemBeanInfo.java @@ -31,8 +31,7 @@ import org.openide.util.Utilities; * Description of the OpenOffice.org Document filesystem. */ public class OpenOfficeDocFileSystemBeanInfo - extends SimpleBeanInfo -{ + extends SimpleBeanInfo { private static String ICONLOCATION = "org/openoffice/netbeans/modules/office/resources"; private static String COLORICON16NAME = @@ -43,49 +42,47 @@ public class OpenOfficeDocFileSystemBeanInfo /** * Retrieves an additional bean information. */ - public BeanInfo[] getAdditionalBeanInfo() - { + public BeanInfo[] getAdditionalBeanInfo() { try { return new BeanInfo[] { - Introspector.getBeanInfo(FileSystem.class) - }; + Introspector.getBeanInfo(FileSystem.class) + }; } catch (IntrospectionException ie) { ErrorManager.getDefault().notify(ie); return null; } } -/* - // If you have a visual dialog to customize configuration of the - // filesystem: - public BeanDescriptor getBeanDescriptor() - { - return new BeanDescriptor(OpenOfficeDocFileSystem.class, - OpenOfficeDocFileSystemCustomizer.class); - } -*/ + /* + // If you have a visual dialog to customize configuration of the + // filesystem: + public BeanDescriptor getBeanDescriptor() + { + return new BeanDescriptor(OpenOfficeDocFileSystem.class, + OpenOfficeDocFileSystemCustomizer.class); + } + */ /** * Retrieves bean property descriptors. */ - public PropertyDescriptor[] getPropertyDescriptors() - { + public PropertyDescriptor[] getPropertyDescriptors() { try { // Included only to make it a writable property (it is read-only // in FileSystem): PropertyDescriptor readOnly = new PropertyDescriptor( "readOnly", OpenOfficeDocFileSystem.class); readOnly.setDisplayName(NbBundle.getMessage( - OpenOfficeDocFileSystemBeanInfo.class, "PROP_readOnly")); + OpenOfficeDocFileSystemBeanInfo.class, "PROP_readOnly")); readOnly.setShortDescription(NbBundle.getMessage( - OpenOfficeDocFileSystemBeanInfo.class, "HINT_readOnly")); + OpenOfficeDocFileSystemBeanInfo.class, "HINT_readOnly")); // This could be whatever properties you use to configure the // filesystem: PropertyDescriptor document = new PropertyDescriptor( "Document", OpenOfficeDocFileSystem.class); document.setDisplayName(NbBundle.getMessage( - OpenOfficeDocFileSystemBeanInfo.class, "PROP_document")); + OpenOfficeDocFileSystemBeanInfo.class, "PROP_document")); document.setShortDescription(NbBundle.getMessage( - OpenOfficeDocFileSystemBeanInfo.class, "HINT_document")); + OpenOfficeDocFileSystemBeanInfo.class, "HINT_document")); // Request to the property editor that it be permitted only to // choose directories: document.setValue("directories", Boolean.FALSE); // NOI18N @@ -101,9 +98,8 @@ public class OpenOfficeDocFileSystemBeanInfo /** * Retrieves an icon by the icon type. */ - public Image getIcon(int type) - { - if((type == BeanInfo.ICON_COLOR_16x16) || + public Image getIcon(int type) { + if ((type == BeanInfo.ICON_COLOR_16x16) || (type == BeanInfo.ICON_MONO_16x16)) { return Utilities.loadImage(COLORICON16NAME); } else { diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoader.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoader.java index d47481ec39d5..268c6054b2bb 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoader.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoader.java @@ -59,6 +59,7 @@ public class OfficeDocumentDataLoader extends UniFileLoader { protected FileObject findPrimaryFile(FileObject fo) { ExtensionList extensions = getExtensions(); + if (!extensions.isRegistered(fo)) return null; @@ -67,32 +68,32 @@ public class OfficeDocumentDataLoader extends UniFileLoader { try { jarFs.setJarFile(document); - } - catch (IOException e) { + } catch (IOException e) { return null; - } - catch (Exception e) { + } catch (Exception e) { return null; } + return fo; } protected SystemAction[] defaultActions() { return new SystemAction[] { - SystemAction.get(OpenAction.class), - null, - SystemAction.get(CutAction.class), - SystemAction.get(CopyAction.class), - SystemAction.get(PasteAction.class), - null, - SystemAction.get(DeleteAction.class), - SystemAction.get(RenameAction.class), - null, - SystemAction.get(PropertiesAction.class), - }; + SystemAction.get(OpenAction.class), + null, + SystemAction.get(CutAction.class), + SystemAction.get(CopyAction.class), + SystemAction.get(PasteAction.class), + null, + SystemAction.get(DeleteAction.class), + SystemAction.get(RenameAction.class), + null, + SystemAction.get(PropertiesAction.class), + }; } - protected MultiDataObject createMultiObject(FileObject primaryFile) throws DataObjectExistsException, IOException { + protected MultiDataObject createMultiObject(FileObject primaryFile) throws + DataObjectExistsException, IOException { return new OfficeDocumentDataObject(primaryFile, this); } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataNode.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataNode.java index 91f393e5d176..32d438f1f3c2 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataNode.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataNode.java @@ -36,7 +36,7 @@ public class OfficeDocumentDataNode extends DataNode { public OfficeDocumentDataNode(OfficeDocumentDataObject obj) { this(obj, new OfficeDocumentChildren((OfficeDocumentCookie) - obj.getCookie(OfficeDocumentCookie.class))); + obj.getCookie(OfficeDocumentCookie.class))); } public OfficeDocumentDataNode(OfficeDocumentDataObject obj, Children ch) { @@ -55,27 +55,32 @@ public class OfficeDocumentDataNode extends DataNode { if (copies != null) { for (int i = 0; i < copies.length; i++) { if (copies[i] instanceof ParcelDataNode) { - File source = FileUtil.toFile(((ParcelDataNode)copies[i]).getDataObject().getPrimaryFile()); + File source = FileUtil.toFile(((ParcelDataNode) + copies[i]).getDataObject().getPrimaryFile()); File target = FileUtil.toFile(getDataObject().getPrimaryFile()); if (source.exists() && source.canRead() && target.exists() && target.canWrite()) { - ls.add(new ParcelDataNode.ParcelPasteType((ParcelDataNode)copies[i], target, false)); + ls.add(new ParcelDataNode.ParcelPasteType((ParcelDataNode)copies[i], target, + false)); } } } } Node[] moves = NodeTransfer.nodes(t, NodeTransfer.MOVE); + if (moves != null) { for (int i = 0; i < moves.length; i++) { if (moves[i] instanceof ParcelDataNode) { - File source = FileUtil.toFile(((ParcelDataNode)moves[i]).getDataObject().getPrimaryFile()); + File source = FileUtil.toFile(((ParcelDataNode) + moves[i]).getDataObject().getPrimaryFile()); File target = FileUtil.toFile(getDataObject().getPrimaryFile()); if (source.exists() && source.canRead() && target.exists() && target.canWrite()) { - ls.add(new ParcelDataNode.ParcelPasteType((ParcelDataNode)moves[i], target, true)); + ls.add(new ParcelDataNode.ParcelPasteType((ParcelDataNode)moves[i], target, + true)); } } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataObject.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataObject.java index 23f5fd6e22ea..742b7d882968 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataObject.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataObject.java @@ -29,7 +29,8 @@ import org.openoffice.netbeans.modules.office.actions.*; public class OfficeDocumentDataObject extends MultiDataObject { - public OfficeDocumentDataObject(FileObject pf, OfficeDocumentDataLoader loader) throws DataObjectExistsException { + public OfficeDocumentDataObject(FileObject pf, + OfficeDocumentDataLoader loader) throws DataObjectExistsException { super(pf, loader); init(); } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolder.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolder.java index 53fa63199517..9243df8c7341 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolder.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolder.java @@ -41,8 +41,9 @@ import org.openoffice.netbeans.modules.office.actions.ParcelFolderCookie; import org.openoffice.netbeans.modules.office.utils.PackageRemover; public class ParcelContentsFolder extends DataFolder { - public ParcelContentsFolder(FileObject pf, ParcelContentsFolderDataLoader loader) - throws DataObjectExistsException { + public ParcelContentsFolder(FileObject pf, + ParcelContentsFolderDataLoader loader) + throws DataObjectExistsException { super(pf, loader); } @@ -59,11 +60,11 @@ public class ParcelContentsFolder extends DataFolder { DataFolder contents = (DataFolder)getDataObject(); ParcelFolderCookie cookie = (ParcelFolderCookie)contents.getFolder(). - getCookie(ParcelFolderCookie.class); + getCookie(ParcelFolderCookie.class); String language = cookie.getLanguage(); ParcelContentsFolder.createEmptyScript(contents, - language); + language); } }; return newtypes; @@ -76,11 +77,9 @@ public class ParcelContentsFolder extends DataFolder { if (language.toLowerCase().equals("java")) { sourceFile += ".java"; - } - else if (language.toLowerCase().equals("beanshell")) { + } else if (language.toLowerCase().equals("beanshell")) { sourceFile += ".bsh"; - } - else { + } else { NotifyDescriptor d = new NotifyDescriptor.Message( "Language not defined for this Parcel Folder"); TopManager.getDefault().notify(d); @@ -89,36 +88,37 @@ public class ParcelContentsFolder extends DataFolder { FileSystem fs = Repository.getDefault().getDefaultFileSystem(); DataObject result = null; + try { DataObject dObj = DataObject.find(fs.findResource(sourceFile)); result = dObj.createFromTemplate(parent); - } - catch (IOException ioe) { + } catch (IOException ioe) { ErrorManager.getDefault().notify(ioe); } FileObject fo = result.getPrimaryFile(); + if (fo.getExt().equals("java")) { FileLock lock = null; + try { PackageRemover.removeDeclaration(FileUtil.toFile(fo)); // IssueZilla 11986 - rename the FileObject // so the JavaNode is resynchronized lock = fo.lock(); + if (lock != null) { fo.rename(lock, fo.getName(), fo.getExt()); } - } - catch (IOException ioe) { + } catch (IOException ioe) { NotifyDescriptor d = new NotifyDescriptor.Message( - "Error removing package declaration from file: " + - fo.getNameExt() + - ". You should manually remove this declaration " + - "before building the Parcel Recipe"); + "Error removing package declaration from file: " + + fo.getNameExt() + + ". You should manually remove this declaration " + + "before building the Parcel Recipe"); TopManager.getDefault().notify(d); - } - finally { + } finally { if (lock != null) { lock.releaseLock(); } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoader.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoader.java index 4406f3f903c8..4943a4f5d75e 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoader.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoader.java @@ -55,19 +55,20 @@ public class ParcelContentsFolderDataLoader extends UniFileLoader { protected SystemAction[] defaultActions() { return new SystemAction[] { - SystemAction.get(PasteAction.class), - SystemAction.get(NewAction.class), - // null, - // SystemAction.get(PropertiesAction.class), - }; + SystemAction.get(PasteAction.class), + SystemAction.get(NewAction.class), + // null, + // SystemAction.get(PropertiesAction.class), + }; } protected MultiDataObject createMultiObject(FileObject primaryFile) - throws DataObjectExistsException { + throws DataObjectExistsException { return new ParcelContentsFolder(primaryFile, this); } - protected MultiDataObject.Entry createPrimaryEntry(MultiDataObject obj, FileObject primaryFile) { + protected MultiDataObject.Entry createPrimaryEntry(MultiDataObject obj, + FileObject primaryFile) { return new FileEntry.Folder(obj, primaryFile); } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoader.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoader.java index 14e968668f71..86e86742c43e 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoader.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoader.java @@ -57,19 +57,20 @@ public class ParcelDataLoader extends UniFileLoader { protected SystemAction[] defaultActions() { return new SystemAction[] { - SystemAction.get(DeployParcelAction.class), - null, - SystemAction.get(CutAction.class), - SystemAction.get(CopyAction.class), - null, - SystemAction.get(DeleteAction.class), - SystemAction.get(RenameAction.class), - null, - SystemAction.get(PropertiesAction.class), - }; + SystemAction.get(DeployParcelAction.class), + null, + SystemAction.get(CutAction.class), + SystemAction.get(CopyAction.class), + null, + SystemAction.get(DeleteAction.class), + SystemAction.get(RenameAction.class), + null, + SystemAction.get(PropertiesAction.class), + }; } - protected MultiDataObject createMultiObject(FileObject primaryFile) throws DataObjectExistsException, IOException { + protected MultiDataObject createMultiObject(FileObject primaryFile) throws + DataObjectExistsException, IOException { return new ParcelDataObject(primaryFile, this); } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataNode.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataNode.java index 5865f32c2803..cb51b982e7c4 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataNode.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataNode.java @@ -55,7 +55,7 @@ public class ParcelDataNode extends DataNode { boolean isCut = false; public ParcelPasteType(ParcelDataNode sourceParcel, - File targetDocument, boolean isCut) { + File targetDocument, boolean isCut) { this.sourceParcel = sourceParcel; this.targetDocument = targetDocument; this.isCut = isCut; @@ -68,13 +68,13 @@ public class ParcelDataNode extends DataNode { if (isCut) { FileObject fo = sourceParcel.getDataObject().getPrimaryFile(); + try { fo.delete(); - } - catch (IOException ioe) {} + } catch (IOException ioe) {} + return ExTransferable.EMPTY; - } - else { + } else { return null; } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataObject.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataObject.java index 83833d06b480..0c9cf1720ca3 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataObject.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataObject.java @@ -31,7 +31,8 @@ import org.openoffice.netbeans.modules.office.actions.*; */ public class ParcelDataObject extends MultiDataObject { - public ParcelDataObject(FileObject pf, ParcelDataLoader loader) throws DataObjectExistsException { + public ParcelDataObject(FileObject pf, + ParcelDataLoader loader) throws DataObjectExistsException { super(pf, loader); init(); } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoader.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoader.java index 8f6083ae00d8..58b94c91031c 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoader.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoader.java @@ -53,20 +53,21 @@ public class ParcelDescriptorDataLoader extends UniFileLoader { protected SystemAction[] defaultActions() { return new SystemAction[] { - SystemAction.get(OpenAction.class), - null, - SystemAction.get(CutAction.class), - SystemAction.get(CopyAction.class), - SystemAction.get(PasteAction.class), - null, - SystemAction.get(DeleteAction.class), - SystemAction.get(RenameAction.class), - null, - SystemAction.get(PropertiesAction.class), - }; + SystemAction.get(OpenAction.class), + null, + SystemAction.get(CutAction.class), + SystemAction.get(CopyAction.class), + SystemAction.get(PasteAction.class), + null, + SystemAction.get(DeleteAction.class), + SystemAction.get(RenameAction.class), + null, + SystemAction.get(PropertiesAction.class), + }; } - protected MultiDataObject createMultiObject(FileObject primaryFile) throws DataObjectExistsException, IOException { + protected MultiDataObject createMultiObject(FileObject primaryFile) throws + DataObjectExistsException, IOException { return new ParcelDescriptorDataObject(primaryFile, this); } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataObject.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataObject.java index c344830b1c27..f72735cfc2ad 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataObject.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataObject.java @@ -34,18 +34,21 @@ public class ParcelDescriptorDataObject extends MultiDataObject { private boolean canParse = false; - public ParcelDescriptorDataObject(FileObject pf, ParcelDescriptorDataLoader loader) throws DataObjectExistsException { + public ParcelDescriptorDataObject(FileObject pf, + ParcelDescriptorDataLoader loader) throws DataObjectExistsException { super(pf, loader); init(); } private void init() { FileObject fo = getPrimaryFile(); + if (FileUtil.toFile(fo) != null) canParse = true; CookieSet cookies = getCookieSet(); cookies.add(new ParcelDescriptorEditorSupport(this)); + if (canParse) cookies.add(new ParcelDescriptorParserSupport(getPrimaryFile())); } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolder.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolder.java index cb03c0c8f35d..a9f04564794f 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolder.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolder.java @@ -47,7 +47,7 @@ public class ParcelFolder extends DataFolder { public static final String LANGUAGE_ATTRIBUTE = "language"; public ParcelFolder(FileObject pf, ParcelFolderDataLoader loader) - throws DataObjectExistsException { + throws DataObjectExistsException { super(pf, loader); CookieSet cookies = getCookieSet(); cookies.add(new ParcelFolderSupport(this)); @@ -74,10 +74,12 @@ public class ParcelFolder extends DataFolder { super(pf.createNodeChildren(dataFilter)); location = (File)pf.getPrimaryFile().getAttribute(LOCATION); + if (location == null) location = FileUtil.toFile(pf.getPrimaryFile()); String name = (String)pf.getPrimaryFile().getAttribute(FILTER); + if (name == null) filter = DEFAULT_FILTER; else { @@ -91,10 +93,10 @@ public class ParcelFolder extends DataFolder { ParcelFolderCookie cookie = (ParcelFolderCookie)pf.getCookie(ParcelFolderCookie.class); String s = cookie.getClasspath(); + if (s != null) { classpath = s; - } - else { + } else { classpath = "."; cookie.setClasspath(classpath); } @@ -111,6 +113,7 @@ public class ParcelFolder extends DataFolder { public String getLanguage() { if (language == null) language = (String)getPrimaryFile().getAttribute(LANGUAGE); + return language; } @@ -121,6 +124,7 @@ public class ParcelFolder extends DataFolder { sheet = super.createSheet(); props = sheet.get(Sheet.PROPERTIES); + if (props == null) { props = Sheet.createPropertiesSet(); sheet.put(props); @@ -139,24 +143,24 @@ public class ParcelFolder extends DataFolder { } private Node.Property createLocationProperty() { - Node.Property prop = - new PropertySupport.ReadWrite(LOCATION, File.class, - "Location", "Output location of Parcel Zip File") { - public void setValue(Object obj) { - if (obj instanceof File) { - location = (File)obj; - try { - getPrimaryFile().setAttribute(LOCATION, location); - } - catch (IOException ioe) { - } + Node.Property prop = + new PropertySupport.ReadWrite(LOCATION, File.class, + "Location", "Output location of Parcel Zip File") { + public void setValue(Object obj) { + if (obj instanceof File) { + location = (File)obj; + + try { + getPrimaryFile().setAttribute(LOCATION, location); + } catch (IOException ioe) { } } + } - public Object getValue() { - return location; - } - }; + public Object getValue() { + return location; + } + }; prop.setValue("files", Boolean.FALSE); return prop; } @@ -165,114 +169,114 @@ public class ParcelFolder extends DataFolder { private Node.Property createLanguageProperty() { Node.Property prop = - new PropertySupport.ReadWrite(LANGUAGE, String.class, - "Parcel Language", "Language of scripts in this Parcel") { - public void setValue(Object obj) { - if (obj instanceof String) { - language = (String)obj; - - try { - getPrimaryFile().setAttribute(LANGUAGE, language); - } - catch (IOException ioe) { - } + new PropertySupport.ReadWrite(LANGUAGE, String.class, + "Parcel Language", "Language of scripts in this Parcel") { + public void setValue(Object obj) { + if (obj instanceof String) { + language = (String)obj; + + try { + getPrimaryFile().setAttribute(LANGUAGE, language); + } catch (IOException ioe) { } } + } - public Object getValue() { - if (language == null) - language = (String)getPrimaryFile().getAttribute(LANGUAGE); - return language; - } + public Object getValue() { + if (language == null) + language = (String)getPrimaryFile().getAttribute(LANGUAGE); - public PropertyEditor getPropertyEditor() { - return new PropertyEditorSupport() { - public String[] getTags() { - return languages; - } - - public void setAsText(String text) { - for (int i = 0; i < languages.length; i++) - if (text.equals(languages[i])) - this.setValue(languages[i]); - } - - public String getAsText() { - return (String)this.getValue(); - } - }; - } - }; + return language; + } + + public PropertyEditor getPropertyEditor() { + return new PropertyEditorSupport() { + public String[] getTags() { + return languages; + } + + public void setAsText(String text) { + for (int i = 0; i < languages.length; i++) + if (text.equals(languages[i])) + this.setValue(languages[i]); + } + + public String getAsText() { + return (String)this.getValue(); + } + }; + } + }; return prop; } private FileFilter[] availableFilters = new FileFilter[] { - BinaryOnlyFilter.getInstance(), AllFilesFilter.getInstance()}; + BinaryOnlyFilter.getInstance(), AllFilesFilter.getInstance() + }; private Node.Property createFilterProperty() { Node.Property prop = - new PropertySupport.ReadWrite(FILTER, String.class, - "File Filter", "Files to be included in Parcel") { - public void setValue(Object obj) { - if (obj instanceof FileFilter) { - filter = (FileFilter)obj; - - try { - getPrimaryFile().setAttribute(FILTER, filter.toString()); - } - catch (IOException ioe) { - } + new PropertySupport.ReadWrite(FILTER, String.class, + "File Filter", "Files to be included in Parcel") { + public void setValue(Object obj) { + if (obj instanceof FileFilter) { + filter = (FileFilter)obj; + + try { + getPrimaryFile().setAttribute(FILTER, filter.toString()); + } catch (IOException ioe) { } } + } - public Object getValue() { - return filter; - } + public Object getValue() { + return filter; + } - public PropertyEditor getPropertyEditor() { - return new PropertyEditorSupport() { - public String[] getTags() { - String[] tags = new String[availableFilters.length]; + public PropertyEditor getPropertyEditor() { + return new PropertyEditorSupport() { + public String[] getTags() { + String[] tags = new String[availableFilters.length]; - for (int i = 0; i < availableFilters.length; i++) - tags[i] = availableFilters[i].toString(); + for (int i = 0; i < availableFilters.length; i++) + tags[i] = availableFilters[i].toString(); - return tags; - } + return tags; + } - public void setAsText(String text) { - for (int i = 0; i < availableFilters.length; i++) - if (text.equals(availableFilters[i].toString())) - this.setValue(availableFilters[i]); - } + public void setAsText(String text) { + for (int i = 0; i < availableFilters.length; i++) + if (text.equals(availableFilters[i].toString())) + this.setValue(availableFilters[i]); + } - public String getAsText() { - return this.getValue().toString(); - } - }; - } - }; + public String getAsText() { + return this.getValue().toString(); + } + }; + } + }; return prop; } private Node.Property createClasspathProperty() { - Node.Property prop = - new PropertySupport.ReadWrite(CLASSPATH, String.class, - "Classpath", "Classpath property for scripts in this parcel") { - public void setValue(Object obj) { - if (obj instanceof String) { - classpath = (String)obj; - - ParcelFolderCookie cookie = (ParcelFolderCookie) - getDataObject().getCookie(ParcelFolderCookie.class); - cookie.setClasspath(classpath); - } + Node.Property prop = + new PropertySupport.ReadWrite(CLASSPATH, String.class, + "Classpath", "Classpath property for scripts in this parcel") { + public void setValue(Object obj) { + if (obj instanceof String) { + classpath = (String)obj; + + ParcelFolderCookie cookie = (ParcelFolderCookie) + getDataObject().getCookie(ParcelFolderCookie.class); + cookie.setClasspath(classpath); } + } - public Object getValue() { - return classpath; - } - }; + public Object getValue() { + return classpath; + } + }; return prop; } } @@ -280,8 +284,10 @@ public class ParcelFolder extends DataFolder { private class ParcelFolderFilter implements DataFilter { public boolean acceptDataObject(DataObject dobj) { String name = dobj.getPrimaryFile().getNameExt(); + if (name.equals(ParcelZipper.PARCEL_DESCRIPTOR_XML)) return false; + return true; } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoader.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoader.java index df60b27561c1..965d11b18ce7 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoader.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoader.java @@ -56,10 +56,13 @@ public class ParcelFolderDataLoader extends UniFileLoader { return null; FileObject contents = fo.getFileObject(ParcelZipper.CONTENTS_DIRNAME); + if (contents == null) return null; - FileObject descriptor = contents.getFileObject(ParcelZipper.PARCEL_DESCRIPTOR_XML); + FileObject descriptor = contents.getFileObject( + ParcelZipper.PARCEL_DESCRIPTOR_XML); + if (descriptor == null) return null; @@ -68,25 +71,27 @@ public class ParcelFolderDataLoader extends UniFileLoader { protected SystemAction[] defaultActions() { return new SystemAction[] { - SystemAction.get(CompileParcelAction.class), - SystemAction.get(BuildParcelAction.class), - SystemAction.get(ConfigureParcelAction.class), - null, - SystemAction.get(CutAction.class), - SystemAction.get(CopyAction.class), - null, - SystemAction.get(DeleteAction.class), - SystemAction.get(RenameAction.class), - null, - SystemAction.get(PropertiesAction.class), - }; + SystemAction.get(CompileParcelAction.class), + SystemAction.get(BuildParcelAction.class), + SystemAction.get(ConfigureParcelAction.class), + null, + SystemAction.get(CutAction.class), + SystemAction.get(CopyAction.class), + null, + SystemAction.get(DeleteAction.class), + SystemAction.get(RenameAction.class), + null, + SystemAction.get(PropertiesAction.class), + }; } - protected MultiDataObject createMultiObject(FileObject primaryFile) throws DataObjectExistsException, IOException { + protected MultiDataObject createMultiObject(FileObject primaryFile) throws + DataObjectExistsException, IOException { return new ParcelFolder(primaryFile, this); } - protected MultiDataObject.Entry createPrimaryEntry(MultiDataObject obj, FileObject primaryFile) { + protected MultiDataObject.Entry createPrimaryEntry(MultiDataObject obj, + FileObject primaryFile) { return new FileEntry.Folder(obj, primaryFile); } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/nodes/OfficeDocumentChildren.java b/scripting/java/org/openoffice/netbeans/modules/office/nodes/OfficeDocumentChildren.java index 01710f9bcaac..b5e939bc2811 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/nodes/OfficeDocumentChildren.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/nodes/OfficeDocumentChildren.java @@ -48,16 +48,19 @@ public class OfficeDocumentChildren extends Children.Keys } Enumeration parcels = document.getParcels(); + if (!parcels.hasMoreElements()) { setKeys(Collections.EMPTY_SET); return; } ArrayList keys = new ArrayList(); + while (parcels.hasMoreElements()) { String parcel = (String)parcels.nextElement(); keys.add(parcel); } + setKeys(keys); } @@ -101,8 +104,8 @@ public class OfficeDocumentChildren extends Children.Keys protected SystemAction[] createActions() { return new SystemAction[] { - SystemAction.get(DeleteAction.class), - }; + SystemAction.get(DeleteAction.class), + }; } public HelpCtx getHelpCtx() { @@ -116,12 +119,12 @@ public class OfficeDocumentChildren extends Children.Keys public void destroy() throws IOException { OfficeSettings settings = OfficeSettings.getDefault(); String message = "If you already have this document open in " + - "Office, please close it before continuing. Click OK to " + - "delete this parcel."; + "Office, please close it before continuing. Click OK to " + + "delete this parcel."; if (settings.getWarnBeforeParcelDelete()) { NagDialog warning = NagDialog.createConfirmationDialog( - message, "Show this message in future", true); + message, "Show this message in future", true); boolean result = warning.show(); @@ -131,6 +134,7 @@ public class OfficeDocumentChildren extends Children.Keys if (!result) return; } + super.destroy(); document.removeParcel(name); } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/nodes/ParcelDescriptorChildren.java b/scripting/java/org/openoffice/netbeans/modules/office/nodes/ParcelDescriptorChildren.java index e8f6ef9003a7..52312ea03574 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/nodes/ParcelDescriptorChildren.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/nodes/ParcelDescriptorChildren.java @@ -31,7 +31,8 @@ import org.openoffice.netbeans.modules.office.actions.ParcelDescriptorParserCook /** List of children of a containing node. * Remember to document what your permitted keys are! */ -public class ParcelDescriptorChildren extends Children.Keys implements ChangeListener { +public class ParcelDescriptorChildren extends Children.Keys implements + ChangeListener { private ParcelDescriptorParserCookie parserCookie = null; @@ -51,8 +52,10 @@ public class ParcelDescriptorChildren extends Children.Keys implements ChangeLis } ArrayList keys = new ArrayList(len); + for (int i = 0; i < len; i++) keys.add(nl.item(i)); + setKeys(keys); } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/nodes/ScriptNode.java b/scripting/java/org/openoffice/netbeans/modules/office/nodes/ScriptNode.java index 91b4d97cb68f..861a4a4f1909 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/nodes/ScriptNode.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/nodes/ScriptNode.java @@ -54,10 +54,10 @@ public class ScriptNode extends AbstractNode { protected SystemAction[] createActions() { return new SystemAction[] { - SystemAction.get(ToolsAction.class), - null, - SystemAction.get(PropertiesAction.class), - }; + SystemAction.get(ToolsAction.class), + null, + SystemAction.get(PropertiesAction.class), + }; } public HelpCtx getHelpCtx() { @@ -75,12 +75,14 @@ public class ScriptNode extends AbstractNode { protected Sheet createSheet() { Sheet sheet = super.createSheet(); Sheet.Set props = sheet.get(Sheet.PROPERTIES); + if (props == null) { props = Sheet.createPropertiesSet(); sheet.put(props); } org.openide.nodes.Node.Property prop = null; + if ((prop = getStringProperty(LOGICAL_NAME)) != null) props.put(prop); @@ -92,7 +94,8 @@ public class ScriptNode extends AbstractNode { private org.openide.nodes.Node.Property getStringProperty(String name) { NodeList nl = element.getElementsByTagName(name); - if(nl.getLength() != 1) + + if (nl.getLength() != 1) return null; Element nameElement = (Element)nl.item(0); @@ -107,7 +110,7 @@ public class ScriptNode extends AbstractNode { public StringProperty(ScriptNode sn, String name, String value) { super(value, String.class, name, - "The name of the java language method for this script"); + "The name of the java language method for this script"); this.sn = sn; this.name = name; this.value = value; diff --git a/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettings.java b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettings.java index a56cdfa97779..1caa8835b4f8 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettings.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettings.java @@ -60,8 +60,7 @@ public class OfficeSettings extends SystemOption { setOfficeDirectory(oi); return; } - } - catch (IOException ioe) { + } catch (IOException ioe) { } } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsBeanInfo.java b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsBeanInfo.java index 63a386986896..a811ab855fd5 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsBeanInfo.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsBeanInfo.java @@ -39,54 +39,53 @@ public class OfficeSettingsBeanInfo extends SimpleBeanInfo { try { PropertyDescriptor[] props = new PropertyDescriptor[] { new PropertyDescriptor(OfficeSettings.OFFICE_DIRECTORY, - OfficeSettings.class, - "get" + OfficeSettings.OFFICE_DIRECTORY, - "set" + OfficeSettings.OFFICE_DIRECTORY), + OfficeSettings.class, + "get" + OfficeSettings.OFFICE_DIRECTORY, + "set" + OfficeSettings.OFFICE_DIRECTORY), new PropertyDescriptor(OfficeSettings.WARN_BEFORE_DOC_DEPLOY, - OfficeSettings.class, - "get" + OfficeSettings.WARN_BEFORE_DOC_DEPLOY, - "set" + OfficeSettings.WARN_BEFORE_DOC_DEPLOY), + OfficeSettings.class, + "get" + OfficeSettings.WARN_BEFORE_DOC_DEPLOY, + "set" + OfficeSettings.WARN_BEFORE_DOC_DEPLOY), new PropertyDescriptor(OfficeSettings.WARN_BEFORE_PARCEL_DELETE, - OfficeSettings.class, - "get" + OfficeSettings.WARN_BEFORE_PARCEL_DELETE, - "set" + OfficeSettings.WARN_BEFORE_PARCEL_DELETE), + OfficeSettings.class, + "get" + OfficeSettings.WARN_BEFORE_PARCEL_DELETE, + "set" + OfficeSettings.WARN_BEFORE_PARCEL_DELETE), new PropertyDescriptor(OfficeSettings.WARN_AFTER_DIR_DEPLOY, - OfficeSettings.class, - "get" + OfficeSettings.WARN_AFTER_DIR_DEPLOY, - "set" + OfficeSettings.WARN_AFTER_DIR_DEPLOY), + OfficeSettings.class, + "get" + OfficeSettings.WARN_AFTER_DIR_DEPLOY, + "set" + OfficeSettings.WARN_AFTER_DIR_DEPLOY), new PropertyDescriptor(OfficeSettings.WARN_BEFORE_MOUNT, - OfficeSettings.class, - "get" + OfficeSettings.WARN_BEFORE_MOUNT, - "set" + OfficeSettings.WARN_BEFORE_MOUNT) + OfficeSettings.class, + "get" + OfficeSettings.WARN_BEFORE_MOUNT, + "set" + OfficeSettings.WARN_BEFORE_MOUNT) }; props[0].setDisplayName(NbBundle.getMessage( - OfficeSettingsBeanInfo.class, "PROP_OfficeDirectory")); + OfficeSettingsBeanInfo.class, "PROP_OfficeDirectory")); props[0].setShortDescription(NbBundle.getMessage( - OfficeSettingsBeanInfo.class, "HINT_OfficeDirectory")); + OfficeSettingsBeanInfo.class, "HINT_OfficeDirectory")); props[0].setPropertyEditorClass(OfficeDirectoryEditor.class); props[1].setDisplayName(NbBundle.getMessage( - OfficeSettingsBeanInfo.class, "PROP_WarnBeforeDocDeploy")); + OfficeSettingsBeanInfo.class, "PROP_WarnBeforeDocDeploy")); props[1].setShortDescription(NbBundle.getMessage( - OfficeSettingsBeanInfo.class, "HINT_WarnBeforeDocDeploy")); + OfficeSettingsBeanInfo.class, "HINT_WarnBeforeDocDeploy")); props[1].setHidden(true); props[2].setDisplayName(NbBundle.getMessage( - OfficeSettingsBeanInfo.class, "PROP_WarnAfterDirDeploy")); + OfficeSettingsBeanInfo.class, "PROP_WarnAfterDirDeploy")); props[2].setShortDescription(NbBundle.getMessage( - OfficeSettingsBeanInfo.class, "HINT_WarnAfterDirDeploy")); + OfficeSettingsBeanInfo.class, "HINT_WarnAfterDirDeploy")); props[2].setHidden(true); props[3].setDisplayName(NbBundle.getMessage( - OfficeSettingsBeanInfo.class, "PROP_WarnBeforeMount")); + OfficeSettingsBeanInfo.class, "PROP_WarnBeforeMount")); props[3].setShortDescription(NbBundle.getMessage( - OfficeSettingsBeanInfo.class, "HINT_WarnBeforeMount")); + OfficeSettingsBeanInfo.class, "HINT_WarnBeforeMount")); props[3].setHidden(true); return props; - } - catch (IntrospectionException ie) { + } catch (IntrospectionException ie) { ErrorManager.getDefault().notify(ie); return null; } @@ -105,18 +104,18 @@ public class OfficeSettingsBeanInfo extends SimpleBeanInfo { private SelectPathPanel panel; - public String getAsText () { + public String getAsText() { return ((OfficeInstallation)getValue()).getPath(); } - public void setAsText (String path) { + public void setAsText(String path) { OfficeInstallation oi = new OfficeInstallation(path); if (!oi.supportsFramework()) throw new IllegalArgumentException(path + - " is not a valid Office install"); + " is not a valid Office install"); else - setValue (oi); + setValue(oi); } public Component getCustomEditor() { diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/FrameworkJarChecker.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/FrameworkJarChecker.java index b26b729455bf..9c6c33900383 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/utils/FrameworkJarChecker.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/FrameworkJarChecker.java @@ -33,46 +33,44 @@ public class FrameworkJarChecker { public static void mountDependencies() { String unoilPath = SVersionRCFile.getPathForUnoil( - OfficeSettings.getDefault().getOfficeDirectory().getPath()); + OfficeSettings.getDefault().getOfficeDirectory().getPath()); if (unoilPath == null) return; File unoilFile = new File(unoilPath + File.separator + "unoil.jar"); JarFileSystem jfs = new JarFileSystem(); + try { jfs.setJarFile(unoilFile); - } - catch (IOException ioe) { + } catch (IOException ioe) { return; - } - catch (PropertyVetoException pve) { + } catch (PropertyVetoException pve) { return; } FileSystem result; + try { result = Repository.getDefault().findFileSystem(jfs.getSystemName()); - } - catch(Exception exp) { + } catch (Exception exp) { result = null; - } - finally { + } finally { jfs.removeNotify(); } - if(result == null) { + if (result == null) { JarFileSystem newjfs = new JarFileSystem(); + try { newjfs.setJarFile(unoilFile); - } - catch (IOException ioe) { + } catch (IOException ioe) { return; - } - catch (PropertyVetoException pve) { + } catch (PropertyVetoException pve) { return; } + Repository.getDefault().addFileSystem(newjfs); newjfs.setHidden(true); } @@ -80,31 +78,31 @@ public class FrameworkJarChecker { public static void unmountDependencies() { String unoilPath = SVersionRCFile.getPathForUnoil( - OfficeSettings.getDefault().getOfficeDirectory().getPath()); + OfficeSettings.getDefault().getOfficeDirectory().getPath()); if (unoilPath == null) return; File unoilFile = new File(unoilPath + File.separator + "unoil.jar"); JarFileSystem jfs = new JarFileSystem(); + try { jfs.setJarFile(unoilFile); - } - catch (IOException ioe) { + } catch (IOException ioe) { return; - } - catch (PropertyVetoException pve) { + } catch (PropertyVetoException pve) { return; } FileSystem result; + try { result = Repository.getDefault().findFileSystem(jfs.getSystemName()); - if(result != null) + + if (result != null) Repository.getDefault().removeFileSystem(result); - } - catch(Exception exp) { + } catch (Exception exp) { } } @@ -115,13 +113,13 @@ public class FrameworkJarChecker { return; String message = "The Office Scripting Framework support jar file " + - "is not mounted, so Office scripts will not compile. NetBeans " + - "is going to mount this jar file automatically."; + "is not mounted, so Office scripts will not compile. NetBeans " + + "is going to mount this jar file automatically."; String prompt = "Show this message in future."; NagDialog warning = NagDialog.createInformationDialog( - message, prompt, true); + message, prompt, true); if (!warning.getState()) { settings.setWarnBeforeMount(false); diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/ManifestParser.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/ManifestParser.java index 1859ec60865e..67e6202c7789 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/utils/ManifestParser.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/ManifestParser.java @@ -45,6 +45,7 @@ public class ManifestParser implements XMLParser { if (parser == null) { parser = new ManifestParser(); } + return parser; } @@ -60,18 +61,15 @@ public class ManifestParser implements XMLParser { is.setSystemId(id); result = XMLUtil.parse(is, false, false, null, null); - } - catch (IOException ioe) { + } catch (IOException ioe) { System.out.println("IO Error parsing stream."); return null; - } - catch (SAXParseException spe) { + } catch (SAXParseException spe) { System.out.println("Sax Error parsing stream: " + spe.getMessage()); System.out.println("\tPublicId: " + spe.getPublicId()); System.out.println("\tSystemId: " + spe.getSystemId()); return null; - } - catch (SAXException se) { + } catch (SAXException se) { System.out.println("Sax Error parsing stream: " + se.getMessage()); return null; } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/NagDialog.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/NagDialog.java index c54833ba02bb..f6f9ee148e0e 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/utils/NagDialog.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/NagDialog.java @@ -36,7 +36,7 @@ public class NagDialog { private JCheckBox checkbox; private NagDialog(String message, String prompt, boolean initialState, - int type) { + int type) { initUI(message, prompt, initialState, type); } @@ -46,7 +46,7 @@ public class NagDialog { message, prompt, initialState, JOptionPane.INFORMATION_MESSAGE); result.setDescriptor(new NotifyDescriptor.Message(result.getPanel(), - NotifyDescriptor.PLAIN_MESSAGE)); + NotifyDescriptor.PLAIN_MESSAGE)); return result; } @@ -57,8 +57,8 @@ public class NagDialog { message, prompt, initialState, JOptionPane.QUESTION_MESSAGE); result.setDescriptor(new NotifyDescriptor.Confirmation( - result.getPanel(), NotifyDescriptor.OK_CANCEL_OPTION, - NotifyDescriptor.PLAIN_MESSAGE)); + result.getPanel(), NotifyDescriptor.OK_CANCEL_OPTION, + NotifyDescriptor.PLAIN_MESSAGE)); return result; } @@ -82,21 +82,21 @@ public class NagDialog { } private void initUI(String message, String prompt, boolean initialState, - int type) { + int type) { this.panel = new JPanel(); JOptionPane optionPane = new JOptionPane(message, type, 0, null, - new Object[0], null) - { - public int getMaxCharactersPerLineCount() { - return 100; - } - }; + new Object[0], null) { + public int getMaxCharactersPerLineCount() { + return 100; + } + }; optionPane.setUI(new javax.swing.plaf.basic.BasicOptionPaneUI() { public Dimension getMinimumOptionPaneSize() { if (minimumSize == null) { return new Dimension(MinimumWidth, 50); } + return new Dimension(minimumSize.width, 50); } }); diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/OfficeModule.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/OfficeModule.java index 305735cd4b86..a4d917e2552b 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/utils/OfficeModule.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/OfficeModule.java @@ -32,27 +32,28 @@ public class OfficeModule extends ModuleInstall { private static final long serialVersionUID = -8499324854301243852L; - public void installed () { + public void installed() { WizardDescriptor wiz = new InstallationPathDescriptor(); TopManager.getDefault().createDialog(wiz).show(); - if(wiz.getValue() == NotifyDescriptor.OK_OPTION) { + if (wiz.getValue() == NotifyDescriptor.OK_OPTION) { OfficeInstallation oi = (OfficeInstallation) - wiz.getProperty(InstallationPathDescriptor.PROP_INSTALLPATH); + wiz.getProperty(InstallationPathDescriptor.PROP_INSTALLPATH); OfficeSettings settings = OfficeSettings.getDefault(); settings.setOfficeDirectory(oi); } + FrameworkJarChecker.mountDependencies(); XMLParserFactory.setParser(ManifestParser.getManifestParser()); } - public void restored () { + public void restored() { FrameworkJarChecker.mountDependencies(); XMLParserFactory.setParser(ManifestParser.getManifestParser()); } - public boolean closing () { + public boolean closing() { FrameworkJarChecker.unmountDependencies(); return true; } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/PackageRemover.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/PackageRemover.java index 270b30fde9d9..f79368f6f495 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/utils/PackageRemover.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/PackageRemover.java @@ -39,24 +39,25 @@ public class PackageRemover { try { String line; + while ((line = in.readLine()) != null) { if (line.startsWith("package")) { String newDeclaration = evaluate(line); + if (newDeclaration != null) { out.write(newDeclaration, 0, newDeclaration.length()); out.newLine(); } - } - else { + } else { out.write(line, 0, line.length()); out.newLine(); } } - } - finally { + } finally { if (in != null) { in.close(); } + if (out != null) { out.close(); } @@ -65,8 +66,7 @@ public class PackageRemover { if (!source.delete()) { tmp.delete(); throw new IOException("Could not overwrite " + source); - } - else { + } else { tmp.renameTo(source); } } @@ -74,10 +74,12 @@ public class PackageRemover { public static String evaluate(String line) { int idx = line.indexOf(ParcelZipper.CONTENTS_DIRNAME); + if (idx == -1) return line; idx = idx + ParcelZipper.CONTENTS_DIRNAME.length(); + if (line.charAt(idx) == '.') return "package " + line.substring(idx + 1);; @@ -89,8 +91,7 @@ public class PackageRemover { try { removeDeclaration(source); - } - catch (IOException ioe) { + } catch (IOException ioe) { ioe.printStackTrace(); } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/ZipMounter.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/ZipMounter.java index 7150ef81e541..4163ea1ea99f 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/utils/ZipMounter.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/ZipMounter.java @@ -27,8 +27,7 @@ import org.openide.filesystems.Repository; import org.openoffice.netbeans.modules.office.filesystem.OpenOfficeDocFileSystem; -public class ZipMounter -{ +public class ZipMounter { private static ZipMounter mounter = null; private ZipMounter() { @@ -37,25 +36,26 @@ public class ZipMounter public static synchronized ZipMounter getZipMounter() { if (mounter == null) mounter = new ZipMounter(); + return mounter; } public void mountZipFile(File zipfile) - throws IOException, PropertyVetoException - { + throws IOException, PropertyVetoException { if (zipfile != null) { addDocumentToRepository(zipfile, true); } } private FileSystem addDocumentToRepository(File rootFile, boolean writeable) - throws IOException, PropertyVetoException - { + throws IOException, PropertyVetoException { Repository repo = Repository.getDefault(); OpenOfficeDocFileSystem oofs; oofs = (OpenOfficeDocFileSystem)getMountedDocument(rootFile); - if(oofs != null) + + if (oofs != null) repo.removeFileSystem(oofs); + oofs = new OpenOfficeDocFileSystem(); oofs.setDocument(rootFile); repo.addFileSystem(oofs); @@ -64,16 +64,18 @@ public class ZipMounter /** @return FileSystem which has given jar file as its root or * null if no such file system could be found in repository */ - private FileSystem getMountedDocument(File rootFile) - { + private FileSystem getMountedDocument(File rootFile) { if (rootFile == null) return null; + FileSystem oofs = null; + try { oofs = Repository.getDefault().findFileSystem( - OpenOfficeDocFileSystem.computeSystemName(rootFile)); - } catch(Exception exp) { + OpenOfficeDocFileSystem.computeSystemName(rootFile)); + } catch (Exception exp) { } + return oofs; } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathDescriptor.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathDescriptor.java index 46147272eb83..f75873dade3f 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathDescriptor.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathDescriptor.java @@ -56,7 +56,8 @@ public class InstallationPathDescriptor extends WizardDescriptor { protected void updateState() { super.updateState(); putProperty("WizardPanel_contentData", iterator.getSteps()); // NOI18N - putProperty("WizardPanel_contentSelectedIndex", Integer.valueOf(iterator.getIndex())); // NOI18N + putProperty("WizardPanel_contentSelectedIndex", + Integer.valueOf(iterator.getIndex())); // NOI18N } } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathIterator.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathIterator.java index 918bcbdf0b49..fafd40165978 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathIterator.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathIterator.java @@ -40,16 +40,16 @@ public class InstallationPathIterator implements WizardDescriptor.Iterator { protected WizardDescriptor.Panel[] createPanels() { return new WizardDescriptor.Panel[] { - new SelectPathPanel() - }; + new SelectPathPanel() + }; } // And the list of step names: protected String[] createSteps() { return new String[] { - "Select OpenOffice.org Installation" - }; + "Select OpenOffice.org Installation" + }; } // --- The rest probably does not need to be touched. --- @@ -66,6 +66,7 @@ public class InstallationPathIterator implements WizardDescriptor.Iterator { if (panels == null) { panels = createPanels(); } + return panels; } @@ -77,6 +78,7 @@ public class InstallationPathIterator implements WizardDescriptor.Iterator { if (steps == null) { steps = createSteps(); } + return steps; } @@ -87,7 +89,7 @@ public class InstallationPathIterator implements WizardDescriptor.Iterator { public String name() { return NbBundle.getMessage(InstallationPathIterator.class, "TITLE_x_of_y", - Integer.valueOf(index + 1), Integer.valueOf(getPanels().length)); + Integer.valueOf(index + 1), Integer.valueOf(getPanels().length)); } public boolean hasNext() { @@ -98,10 +100,12 @@ public class InstallationPathIterator implements WizardDescriptor.Iterator { } public void nextPanel() { if (!hasNext()) throw new NoSuchElementException(); + index++; } public void previousPanel() { if (!hasPrevious()) throw new NoSuchElementException(); + index--; } public WizardDescriptor.Panel current() { diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/JavaScriptIterator.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/JavaScriptIterator.java index 8a326201301b..dd602ce1131d 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/wizard/JavaScriptIterator.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/JavaScriptIterator.java @@ -58,17 +58,17 @@ public class JavaScriptIterator implements TemplateWizard.Iterator { protected WizardDescriptor.Panel[] createPanels() { return new WizardDescriptor.Panel[] { - // keep the default 2nd panel: - wiz.targetChooser(), - }; + // keep the default 2nd panel: + wiz.targetChooser(), + }; } // And the list of step names: protected String[] createSteps() { return new String[] { - null, - }; + null, + }; } private DataFolder checkTarget(DataFolder folder) { @@ -80,21 +80,23 @@ public class JavaScriptIterator implements TemplateWizard.Iterator { if (fs instanceof OpenOfficeDocFileSystem && fo.isRoot()) { FileObject scripts = fo.getFileObject(OpenOfficeDocFileSystem.SCRIPTS_ROOT); + if (scripts == null) scripts = fo.createFolder(OpenOfficeDocFileSystem.SCRIPTS_ROOT); FileObject javafolder = scripts.getFileObject("java"); + if (javafolder == null) javafolder = scripts.createFolder("java"); DataFolder subfolder = new DataFolder(javafolder); return subfolder; } - } - catch (IOException ioe) { + } catch (IOException ioe) { /* do nothing, we will just return the folder we were passed in */ } + return folder; } @@ -105,6 +107,7 @@ public class JavaScriptIterator implements TemplateWizard.Iterator { DataObject template = wiz.getTemplate(); DataObject result; + if (name == null) { // Default name. result = template.createFromTemplate(targetFolder); @@ -113,6 +116,7 @@ public class JavaScriptIterator implements TemplateWizard.Iterator { } FileObject tmp = result.getPrimaryFile(); + if (tmp.getExt().equals("java")) { try { PackageRemover.removeDeclaration(FileUtil.toFile(tmp)); @@ -120,13 +124,12 @@ public class JavaScriptIterator implements TemplateWizard.Iterator { // IssueZilla 11986 - rename the FileObject // so the JavaNode is resynchronized tmp.rename(tmp.lock(), tmp.getName(), tmp.getExt()); - } - catch (IOException ioe) { + } catch (IOException ioe) { NotifyDescriptor d = new NotifyDescriptor.Message( - "Error removing package declaration from file: " + - tmp.getNameExt() + - ". You should manually remove this declaration " + - "before building the Parcel Recipe"); + "Error removing package declaration from file: " + + tmp.getNameExt() + + ". You should manually remove this declaration " + + "before building the Parcel Recipe"); TopManager.getDefault().notify(d); } } @@ -150,18 +153,22 @@ public class JavaScriptIterator implements TemplateWizard.Iterator { panels = createPanels(); // Make sure list of steps is accurate. String[] steps = createSteps(); + for (int i = 0; i < panels.length; i++) { Component c = panels[i].getComponent(); + if (steps[i] == null) { // Default step name to component name of panel. // Mainly useful for getting the name of the target // chooser to appear in the list of steps. steps[i] = c.getName(); } + if (c instanceof JComponent) { // assume Swing components JComponent jc = (JComponent)c; // Step #. - jc.putClientProperty("WizardPanel_contentSelectedIndex", Integer.valueOf(i)); // NOI18N + jc.putClientProperty("WizardPanel_contentSelectedIndex", + Integer.valueOf(i)); // NOI18N // Step name (actually the whole list for reference). jc.putClientProperty("WizardPanel_contentData", steps); // NOI18N } @@ -189,10 +196,12 @@ public class JavaScriptIterator implements TemplateWizard.Iterator { } public void nextPanel() { if (!hasNext()) throw new NoSuchElementException(); + index++; } public void previousPanel() { if (!hasPrevious()) throw new NoSuchElementException(); + index--; } public WizardDescriptor.Panel current() { diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelContentsIterator.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelContentsIterator.java index 510a9adb638c..4135724d2010 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelContentsIterator.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelContentsIterator.java @@ -62,17 +62,17 @@ public class ParcelContentsIterator implements TemplateWizard.Iterator { protected WizardDescriptor.Panel[] createPanels() { return new WizardDescriptor.Panel[] { - new ParcelPropertiesPanel(), - }; + new ParcelPropertiesPanel(), + }; } // And the list of step names: protected String[] createSteps() { return new String[] { - // null, - "Parcel Properties", - }; + // null, + "Parcel Properties", + }; } private DataFolder checkTarget(DataFolder folder) { @@ -84,21 +84,23 @@ public class ParcelContentsIterator implements TemplateWizard.Iterator { if (fs instanceof OpenOfficeDocFileSystem && fo.isRoot()) { FileObject scripts = fo.getFileObject(OpenOfficeDocFileSystem.SCRIPTS_ROOT); + if (scripts == null) scripts = fo.createFolder(OpenOfficeDocFileSystem.SCRIPTS_ROOT); FileObject javafolder = scripts.getFileObject("java"); + if (javafolder == null) javafolder = scripts.createFolder("java"); DataFolder subfolder = new DataFolder(javafolder); return subfolder; } - } - catch (IOException ioe) { + } catch (IOException ioe) { /* do nothing, we will just return the folder we were passed in */ } + return folder; } @@ -111,6 +113,7 @@ public class ParcelContentsIterator implements TemplateWizard.Iterator { DataObject template = wiz.getTemplate(); DataObject result; + if (name == null) { // Default name. result = template.createFromTemplate(targetFolder); @@ -152,18 +155,22 @@ public class ParcelContentsIterator implements TemplateWizard.Iterator { panels = createPanels(); // Make sure list of steps is accurate. String[] steps = createSteps(); + for (int i = 0; i < panels.length; i++) { Component c = panels[i].getComponent(); + if (steps[i] == null) { // Default step name to component name of panel. // Mainly useful for getting the name of the target // chooser to appear in the list of steps. steps[i] = c.getName(); } + if (c instanceof JComponent) { // assume Swing components JComponent jc = (JComponent)c; // Step #. - jc.putClientProperty("WizardPanel_contentSelectedIndex", Integer.valueOf(i)); // NOI18N + jc.putClientProperty("WizardPanel_contentSelectedIndex", + Integer.valueOf(i)); // NOI18N // Step name (actually the whole list for reference). jc.putClientProperty("WizardPanel_contentData", steps); // NOI18N } @@ -191,10 +198,12 @@ public class ParcelContentsIterator implements TemplateWizard.Iterator { } public void nextPanel() { if (!hasNext()) throw new NoSuchElementException(); + index++; } public void previousPanel() { if (!hasPrevious()) throw new NoSuchElementException(); + index--; } public WizardDescriptor.Panel current() { diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesPanel.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesPanel.java index e0355ed391c6..aaf3abd5a186 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesPanel.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesPanel.java @@ -51,6 +51,7 @@ public class ParcelPropertiesPanel implements WizardDescriptor.FinishPanel { if (component == null) { component = new ParcelPropertiesVisualPanel(this); } + return component; } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.java index bdb25bd02fb3..bf10d713e4c7 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.java @@ -39,7 +39,8 @@ public class ParcelPropertiesVisualPanel extends javax.swing.JPanel { languagesComboBox.addItem("BeanShell"); // Provide a name in the title bar. - setName(NbBundle.getMessage(ParcelPropertiesVisualPanel.class, "TITLE_ParcelPropertiesVisualPanel")); + setName(NbBundle.getMessage(ParcelPropertiesVisualPanel.class, + "TITLE_ParcelPropertiesVisualPanel")); } /** This method is called from within the constructor to @@ -121,27 +122,33 @@ public class ParcelPropertiesVisualPanel extends javax.swing.JPanel { }//GEN-END:initComponents - private void recipeNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_recipeNameFocusGained + private void recipeNameFocusGained(java.awt.event.FocusEvent + evt) {//GEN-FIRST:event_recipeNameFocusGained recipeName.selectAll(); }//GEN-LAST:event_recipeNameFocusGained - private void recipeNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_recipeNameFocusLost + private void recipeNameFocusLost(java.awt.event.FocusEvent + evt) {//GEN-FIRST:event_recipeNameFocusLost changeName(); }//GEN-LAST:event_recipeNameFocusLost - private void languagesComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_languagesComboBoxActionPerformed + private void languagesComboBoxActionPerformed(java.awt.event.ActionEvent + evt) {//GEN-FIRST:event_languagesComboBoxActionPerformed String language = (String)languagesComboBox.getSelectedItem(); panel.setLanguage(language); }//GEN-LAST:event_languagesComboBoxActionPerformed - private void recipeNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_recipeNameActionPerformed + private void recipeNameActionPerformed(java.awt.event.ActionEvent + evt) {//GEN-FIRST:event_recipeNameActionPerformed changeName(); }//GEN-LAST:event_recipeNameActionPerformed private void changeName() { String name = recipeName.getText().trim(); + if (name.length() == 0) name = null; + panel.setName(name); } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathPanel.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathPanel.java index 66fb0a29821a..dfa434d75a35 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathPanel.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathPanel.java @@ -36,7 +36,8 @@ import org.openoffice.idesupport.SVersionRCFile; /** A single panel descriptor for a wizard. * You probably want to make a wizard iterator to hold it. */ -public class SelectPathPanel implements WizardDescriptor.Panel /* .FinishPanel */ { +public class SelectPathPanel implements + WizardDescriptor.Panel { /* .FinishPanel */ /** The visual component that displays this panel. * If you need to access the component from this class, @@ -52,8 +53,7 @@ public class SelectPathPanel implements WizardDescriptor.Panel /* .FinishPanel * if (office == null) { try { office = SVersionRCFile.createInstance().getDefaultVersion(); - } - catch (java.io.IOException ioe) {} + } catch (java.io.IOException ioe) {} } } @@ -65,6 +65,7 @@ public class SelectPathPanel implements WizardDescriptor.Panel /* .FinishPanel * if (component == null) { component = new SelectPathVisualPanel(this); } + return component; } @@ -98,10 +99,13 @@ public class SelectPathPanel implements WizardDescriptor.Panel /* .FinishPanel * } protected final void fireChangeEvent() { Iterator it; + synchronized (listeners) { it = new HashSet(listeners).iterator(); } + ChangeEvent ev = new ChangeEvent(this); + while (it.hasNext()) { ((ChangeListener)it.next()).stateChanged(ev); } diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.java index 3853944e72fe..ca26a25bc150 100644 --- a/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.java +++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.java @@ -52,8 +52,7 @@ public class SelectPathVisualPanel extends javax.swing.JPanel { OfficeInstallation oi = (OfficeInstallation)enumer.nextElement(); installationsComboBox.addItem(oi); } - } - catch (IOException ioe) { + } catch (IOException ioe) { installationsComboBox.addItem("<empty>"); } @@ -63,15 +62,16 @@ public class SelectPathVisualPanel extends javax.swing.JPanel { } installationsComboBox.addActionListener( - new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - installationsComboBoxActionPerformed(evt); - } + new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + installationsComboBoxActionPerformed(evt); } + } ); // Provide a name in the title bar. - setName(NbBundle.getMessage(SelectPathVisualPanel.class, "TITLE_SelectPathVisualPanel")); + setName(NbBundle.getMessage(SelectPathVisualPanel.class, + "TITLE_SelectPathVisualPanel")); } private void installationsComboBoxActionPerformed( @@ -155,7 +155,8 @@ public class SelectPathVisualPanel extends javax.swing.JPanel { }//GEN-END:initComponents - private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed + private void browseButtonActionPerformed(java.awt.event.ActionEvent + evt) {//GEN-FIRST:event_browseButtonActionPerformed // Add your handling code here: File target = null; @@ -167,10 +168,10 @@ public class SelectPathVisualPanel extends javax.swing.JPanel { target = chooser.getSelectedFile(); String path; + try { path = target.getCanonicalPath(); - } - catch (IOException ioe) { + } catch (IOException ioe) { path = target.getAbsolutePath(); } |