From 6f42a714399f4d0c46dad95c7c11bcd513c27eaa Mon Sep 17 00:00:00 2001 From: Robert Antoni Buj i Gelonch Date: Thu, 25 Sep 2014 19:41:12 +0200 Subject: scripting: Format_java_code.sh initial run Conflicts: scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java Change-Id: I09b94d8c96dfbaf498bd93a0088feb80a9e4afb6 --- scripting/examples/java/HelloWorld/HelloWorld.java | 16 +- .../examples/java/Highlight/HighlightText.java | 89 ++-- .../examples/java/MemoryUsage/MemoryUsage.java | 55 +- .../examples/java/Newsgroup/MimeConfiguration.java | 170 +++---- scripting/examples/java/Newsgroup/NewsGroup.java | 12 +- .../examples/java/Newsgroup/OfficeAttachment.java | 228 ++++----- .../examples/java/Newsgroup/PostNewsgroup.java | 560 ++++++++++----------- scripting/examples/java/Newsgroup/Sender.java | 96 ++-- .../examples/java/Newsgroup/StatusWindow.java | 128 +++-- .../java/Newsgroup/SubscribedNewsgroups.java | 267 +++++----- scripting/examples/java/debugger/DebugRunner.java | 24 +- .../java/debugger/OOBeanShellDebugger.java | 71 ++- .../examples/java/debugger/OORhinoDebugger.java | 40 +- .../examples/java/selector/ScriptSelector.java | 242 ++++----- 14 files changed, 926 insertions(+), 1072 deletions(-) (limited to 'scripting/examples') diff --git a/scripting/examples/java/HelloWorld/HelloWorld.java b/scripting/examples/java/HelloWorld/HelloWorld.java index 3f117a28e8c9..1c960da3244b 100644 --- a/scripting/examples/java/HelloWorld/HelloWorld.java +++ b/scripting/examples/java/HelloWorld/HelloWorld.java @@ -28,15 +28,15 @@ import com.sun.star.text.XText; * */ public class HelloWorld { - public static void printHW(XScriptContext xSc) { + public static void printHW(XScriptContext xSc) { - // getting the text document object - XTextDocument xtextdocument = (XTextDocument) UnoRuntime.queryInterface( -XTextDocument.class, xSc.getDocument()); - XText xText = xtextdocument.getText(); - XTextRange xTextRange = xText.getEnd(); - xTextRange.setString( "Hello World (in Java)" ); + // getting the text document object + XTextDocument xtextdocument = (XTextDocument) UnoRuntime.queryInterface( + XTextDocument.class, xSc.getDocument()); + XText xText = xtextdocument.getText(); + XTextRange xTextRange = xText.getEnd(); + xTextRange.setString("Hello World (in Java)"); - }// printHW + }// printHW } diff --git a/scripting/examples/java/Highlight/HighlightText.java b/scripting/examples/java/Highlight/HighlightText.java index 46c6f738f1bf..f39ccbfa22bf 100644 --- a/scripting/examples/java/Highlight/HighlightText.java +++ b/scripting/examples/java/Highlight/HighlightText.java @@ -54,65 +54,63 @@ public class HighlightText implements com.sun.star.awt.XActionListener { args[0] = context.getDocument(); Object obj; + try { obj = xmcf.createInstanceWithArgumentsAndContext( - "com.sun.star.awt.DialogProvider", args, - context.getComponentContext()); - } - catch (com.sun.star.uno.Exception e) { + "com.sun.star.awt.DialogProvider", args, + context.getComponentContext()); + } catch (com.sun.star.uno.Exception e) { System.err.println("Error getting DialogProvider object"); return; } XDialogProvider xDialogProvider = (XDialogProvider) - UnoRuntime.queryInterface(XDialogProvider.class, obj); + UnoRuntime.queryInterface(XDialogProvider.class, obj); System.err.println("Got DialogProvider, now get dialog"); try { findDialog = xDialogProvider.createDialog( - "vnd.sun.star.script:" + - "ScriptBindingLibrary.Highlight?location=application"); - } - catch (java.lang.Exception e) { + "vnd.sun.star.script:" + + "ScriptBindingLibrary.Highlight?location=application"); + } catch (java.lang.Exception e) { System.err.println("Got exception on first creating dialog: " + - e.getMessage()); + e.getMessage()); } if (findDialog == null) { if (!tryLoadingLibrary(xmcf, context, "Dialog") || - !tryLoadingLibrary(xmcf, context, "Script")) - { + !tryLoadingLibrary(xmcf, context, "Script")) { System.err.println("Error loading ScriptBindingLibrary"); return; } + try { findDialog = xDialogProvider.createDialog( - "vnd.sun.star.script://" + - "ScriptBindingLibrary.Highlight?location=application"); - } - catch (com.sun.star.lang.IllegalArgumentException iae) { + "vnd.sun.star.script://" + + "ScriptBindingLibrary.Highlight?location=application"); + } catch (com.sun.star.lang.IllegalArgumentException iae) { System.err.println("Error loading ScriptBindingLibrary"); return; } } XControlContainer controls = (XControlContainer) - UnoRuntime.queryInterface(XControlContainer.class, findDialog); + UnoRuntime.queryInterface(XControlContainer.class, findDialog); XButton highlightButton = (XButton) UnoRuntime.queryInterface( - XButton.class, controls.getControl("HighlightButton")); + XButton.class, controls.getControl("HighlightButton")); highlightButton.setActionCommand("Highlight"); findTextBox = (XTextComponent) UnoRuntime.queryInterface( - XTextComponent.class, controls.getControl("HighlightTextField")); + XTextComponent.class, controls.getControl("HighlightTextField")); XButton exitButton = (XButton) UnoRuntime.queryInterface( - XButton.class, controls.getControl("ExitButton")); + XButton.class, controls.getControl("ExitButton")); exitButton.setActionCommand("Exit"); theDocument = (XTextDocument) UnoRuntime.queryInterface( - XTextDocument.class, context.getDocument()); + XTextDocument.class, context.getDocument()); highlightButton.addActionListener(this); exitButton.addActionListener(this); @@ -124,8 +122,7 @@ public class HighlightText implements com.sun.star.awt.XActionListener { if (e.ActionCommand.equals("Exit")) { findDialog.endExecute(); return; - } - else if (e.ActionCommand.equals("Highlight")) { + } else if (e.ActionCommand.equals("Highlight")) { searchKey = findTextBox.getText(); // highlight the text in red @@ -133,7 +130,7 @@ public class HighlightText implements com.sun.star.awt.XActionListener { int red = cRed.getRGB(); XReplaceable replaceable = (XReplaceable) - UnoRuntime.queryInterface(XReplaceable.class, theDocument); + UnoRuntime.queryInterface(XReplaceable.class, theDocument); XReplaceDescriptor descriptor = (XReplaceDescriptor) replaceable.createReplaceDescriptor(); @@ -141,17 +138,17 @@ public class HighlightText implements com.sun.star.awt.XActionListener { // Gets a XPropertyReplace object for altering the properties // of the replaced text XPropertyReplace xPropertyReplace = (XPropertyReplace) - UnoRuntime.queryInterface(XPropertyReplace.class, descriptor); + UnoRuntime.queryInterface(XPropertyReplace.class, descriptor); // Sets the replaced text property fontweight value to Bold PropertyValue wv = new PropertyValue("CharWeight", -1, - new Float(com.sun.star.awt.FontWeight.BOLD), - com.sun.star.beans.PropertyState.DIRECT_VALUE); + new Float(com.sun.star.awt.FontWeight.BOLD), + com.sun.star.beans.PropertyState.DIRECT_VALUE); // Sets the replaced text property color value to RGB parameter PropertyValue cv = new PropertyValue("CharColor", -1, - Integer.valueOf(red), - com.sun.star.beans.PropertyState.DIRECT_VALUE); + Integer.valueOf(red), + com.sun.star.beans.PropertyState.DIRECT_VALUE); // Apply the properties PropertyValue[] props = new PropertyValue[] { cv, wv }; @@ -163,20 +160,16 @@ public class HighlightText implements com.sun.star.awt.XActionListener { descriptor.setPropertyValue( "SearchCaseSensitive", Boolean.TRUE); descriptor.setPropertyValue("SearchWords", Boolean.TRUE); - } - catch (com.sun.star.beans.UnknownPropertyException upe) { + } catch (com.sun.star.beans.UnknownPropertyException upe) { System.err.println("Error setting up search properties"); return; - } - catch (com.sun.star.beans.PropertyVetoException pve) { + } catch (com.sun.star.beans.PropertyVetoException pve) { System.err.println("Error setting up search properties"); return; - } - catch (com.sun.star.lang.WrappedTargetException wte) { + } catch (com.sun.star.lang.WrappedTargetException wte) { System.err.println("Error setting up search properties"); return; - } - catch (com.sun.star.lang.IllegalArgumentException iae) { + } catch (com.sun.star.lang.IllegalArgumentException iae) { System.err.println("Error setting up search properties"); return; } @@ -189,40 +182,39 @@ public class HighlightText implements com.sun.star.awt.XActionListener { } } - public void disposing(EventObject o) - { + public void disposing(EventObject o) { // do nothing } private boolean tryLoadingLibrary( - XMultiComponentFactory xmcf, XScriptContext context, String name) - { + XMultiComponentFactory xmcf, XScriptContext context, String name) { System.err.println("Try to load ScriptBindingLibrary"); try { Object obj = xmcf.createInstanceWithContext( - "com.sun.star.script.Application" + name + "LibraryContainer", - context.getComponentContext()); + "com.sun.star.script.Application" + name + "LibraryContainer", + context.getComponentContext()); XLibraryContainer xLibraryContainer = (XLibraryContainer) - UnoRuntime.queryInterface(XLibraryContainer.class, obj); + UnoRuntime.queryInterface(XLibraryContainer.class, obj); System.err.println("Got XLibraryContainer"); Object serviceObj = context.getComponentContext().getValueByName( - "/singletons/com.sun.star.util.theMacroExpander"); + "/singletons/com.sun.star.util.theMacroExpander"); XMacroExpander xme = (XMacroExpander) AnyConverter.toObject( - new Type(XMacroExpander.class), serviceObj); + new Type(XMacroExpander.class), serviceObj); String bootstrapName = "bootstraprc"; + if (System.getProperty("os.name").startsWith("Windows")) { bootstrapName = "bootstrap.ini"; } String libURL = xme.expandMacros( - "$BRAND_BASE_DIR/$BRAND_SHARE_SUBDIR/basic/ScriptBindingLibrary/" + - name.toLowerCase() + ".xlb/"); + "$BRAND_BASE_DIR/$BRAND_SHARE_SUBDIR/basic/ScriptBindingLibrary/" + + name.toLowerCase() + ".xlb/"); System.err.println("libURL is: " + libURL); @@ -235,6 +227,7 @@ public class HighlightText implements com.sun.star.awt.XActionListener { System.err.println("Got an exception loading lib: " + e.getMessage()); return false; } + return true; } } diff --git a/scripting/examples/java/MemoryUsage/MemoryUsage.java b/scripting/examples/java/MemoryUsage/MemoryUsage.java index 63a643e90621..a01d2baceff8 100644 --- a/scripting/examples/java/MemoryUsage/MemoryUsage.java +++ b/scripting/examples/java/MemoryUsage/MemoryUsage.java @@ -39,11 +39,9 @@ import com.sun.star.sheet.*; import com.sun.star.script.provider.XScriptContext; -public class MemoryUsage -{ +public class MemoryUsage { public void updateMemoryUsage(XScriptContext ctxt) - throws Exception - { + throws Exception { XSpreadsheet sheet = createSpreadsheet(ctxt); Runtime runtime = Runtime.getRuntime(); @@ -55,37 +53,35 @@ public class MemoryUsage byte[] bytes = new byte[len]; addData(sheet, date.toString(), - runtime.totalMemory(), runtime.freeMemory()); + runtime.totalMemory(), runtime.freeMemory()); addChart(sheet); } private XSpreadsheet createSpreadsheet(XScriptContext ctxt) - throws Exception - { + throws Exception { XComponentLoader loader = (XComponentLoader) - UnoRuntime.queryInterface( - XComponentLoader.class, ctxt.getDesktop()); + UnoRuntime.queryInterface( + XComponentLoader.class, ctxt.getDesktop()); XComponent comp = loader.loadComponentFromURL( - "private:factory/scalc", "_blank", 4, new PropertyValue[0]); + "private:factory/scalc", "_blank", 4, new PropertyValue[0]); XSpreadsheetDocument doc = (XSpreadsheetDocument) - UnoRuntime.queryInterface(XSpreadsheetDocument.class, comp); + UnoRuntime.queryInterface(XSpreadsheetDocument.class, comp); XIndexAccess index = (XIndexAccess) - UnoRuntime.queryInterface(XIndexAccess.class, doc.getSheets()); + UnoRuntime.queryInterface(XIndexAccess.class, doc.getSheets()); XSpreadsheet sheet = (XSpreadsheet) AnyConverter.toObject( - new Type(com.sun.star.sheet.XSpreadsheet.class), index.getByIndex(0)); + new Type(com.sun.star.sheet.XSpreadsheet.class), index.getByIndex(0)); return sheet; } private void addData( XSpreadsheet sheet, String date, long total, long free) - throws Exception - { + throws Exception { sheet.getCellByPosition(0, 0).setFormula("Used"); sheet.getCellByPosition(0, 1).setFormula("Free"); sheet.getCellByPosition(0, 2).setFormula("Total"); @@ -96,8 +92,7 @@ public class MemoryUsage } private void addChart(XSpreadsheet sheet) - throws Exception - { + throws Exception { Rectangle rect = new Rectangle(); rect.X = 500; rect.Y = 3000; @@ -105,13 +100,13 @@ public class MemoryUsage rect.Height = 8000; XCellRange range = (XCellRange) - UnoRuntime.queryInterface(XCellRange.class, sheet); + UnoRuntime.queryInterface(XCellRange.class, sheet); XCellRange myRange = range.getCellRangeByName("A1:B2"); XCellRangeAddressable rangeAddr = (XCellRangeAddressable) - UnoRuntime.queryInterface(XCellRangeAddressable.class, myRange); + UnoRuntime.queryInterface(XCellRangeAddressable.class, myRange); CellRangeAddress myAddr = rangeAddr.getRangeAddress(); @@ -119,42 +114,44 @@ public class MemoryUsage addr[0] = myAddr; XTableChartsSupplier supp = (XTableChartsSupplier) - UnoRuntime.queryInterface( XTableChartsSupplier.class, sheet); + UnoRuntime.queryInterface(XTableChartsSupplier.class, sheet); XTableCharts charts = supp.getCharts(); charts.addNewByName("Example", rect, addr, false, true); - try { Thread.sleep(3000); } catch (InterruptedException e) { } + try { + Thread.sleep(3000); + } catch (InterruptedException e) { } // get the diagram and Change some of the properties XNameAccess chartsAccess = (XNameAccess) - UnoRuntime.queryInterface( XNameAccess.class, charts); + UnoRuntime.queryInterface(XNameAccess.class, charts); XTableChart tchart = (XTableChart) - UnoRuntime.queryInterface( - XTableChart.class, chartsAccess.getByName("Example")); + UnoRuntime.queryInterface( + XTableChart.class, chartsAccess.getByName("Example")); XEmbeddedObjectSupplier eos = (XEmbeddedObjectSupplier) - UnoRuntime.queryInterface( XEmbeddedObjectSupplier.class, tchart ); + UnoRuntime.queryInterface(XEmbeddedObjectSupplier.class, tchart); XInterface xifc = eos.getEmbeddedObject(); XChartDocument xChart = (XChartDocument) - UnoRuntime.queryInterface(XChartDocument.class, xifc); + UnoRuntime.queryInterface(XChartDocument.class, xifc); XMultiServiceFactory xDocMSF = (XMultiServiceFactory) - UnoRuntime.queryInterface(XMultiServiceFactory.class, xChart); + UnoRuntime.queryInterface(XMultiServiceFactory.class, xChart); Object diagObject = xDocMSF.createInstance("com.sun.star.chart.PieDiagram"); XDiagram xDiagram = (XDiagram) - UnoRuntime.queryInterface(XDiagram.class, diagObject); + UnoRuntime.queryInterface(XDiagram.class, diagObject); xChart.setDiagram(xDiagram); XPropertySet propset = (XPropertySet) - UnoRuntime.queryInterface( XPropertySet.class, xChart.getTitle() ); + UnoRuntime.queryInterface(XPropertySet.class, xChart.getTitle()); propset.setPropertyValue("String", "JVM Memory Usage"); } } diff --git a/scripting/examples/java/Newsgroup/MimeConfiguration.java b/scripting/examples/java/Newsgroup/MimeConfiguration.java index 03e6c1b03116..03b964834384 100644 --- a/scripting/examples/java/Newsgroup/MimeConfiguration.java +++ b/scripting/examples/java/Newsgroup/MimeConfiguration.java @@ -30,33 +30,29 @@ import javax.activation.*; import java.io.*; -public class MimeConfiguration -{ +public class MimeConfiguration { // Office Installation path private static String instPath = ""; - public static boolean createFiles( XScriptContext xsc ) - { - try - { + public static boolean createFiles(XScriptContext xsc) { + try { XComponentContext xcc = xsc.getComponentContext(); XMultiComponentFactory xmf = xcc.getServiceManager(); - Object pathSub = xmf.createInstanceWithContext( "com.sun.star.comp.framework.PathSubstitution", xcc ); - XStringSubstitution stringSub = ( XStringSubstitution ) UnoRuntime.queryInterface( XStringSubstitution.class, pathSub ); - instPath = stringSub.getSubstituteVariableValue( "$(inst)" ); + Object pathSub = + xmf.createInstanceWithContext("com.sun.star.comp.framework.PathSubstitution", + xcc); + XStringSubstitution stringSub = (XStringSubstitution) UnoRuntime.queryInterface( + XStringSubstitution.class, pathSub); + instPath = stringSub.getSubstituteVariableValue("$(inst)"); - } - catch( com.sun.star.beans.UnknownPropertyException upe ) - { - System.out.println( "com.sun.star.beans.UnknownPropertyException" ); + } catch (com.sun.star.beans.UnknownPropertyException upe) { + System.out.println("com.sun.star.beans.UnknownPropertyException"); upe.printStackTrace(); - } - catch( com.sun.star.uno.Exception e ) - { - System.out.println( "com.sun.star.uno.Exception" ); + } catch (com.sun.star.uno.Exception e) { + System.out.println("com.sun.star.uno.Exception"); e.printStackTrace(); } @@ -70,46 +66,38 @@ public class MimeConfiguration - private static void writeMailCap() - { - String mailcapPath = getConfigDir() + System.getProperty( "file.separator" ) + "mailcap"; + private static void writeMailCap() { + String mailcapPath = getConfigDir() + System.getProperty("file.separator") + + "mailcap"; - try - { - if( ! new File( java.net.URLDecoder.decode( mailcapPath ) ).exists() ) - { - File mailcapFile = new File( mailcapPath ); - FileWriter out = new FileWriter( mailcapFile ); + try { + if (! new File(java.net.URLDecoder.decode(mailcapPath)).exists()) { + File mailcapFile = new File(mailcapPath); + FileWriter out = new FileWriter(mailcapFile); String[] lines = getMailcapText(); - for( int i=0; i@. // (string at least 2 chars long) // consider .@.. format? (array of dot positons?) String replyString = replyTextField.getText(); - int atPos = replyString.indexOf( "@" ); - int dotPos = replyString.lastIndexOf( "." ); + int atPos = replyString.indexOf("@"); + int dotPos = replyString.lastIndexOf("."); int length = replyString.length(); - if( length == 0 || atPos == -1 || dotPos == -1 || atPos < 2 || dotPos < atPos || dotPos + 2 == length || atPos + 2 == dotPos || atPos != replyString.lastIndexOf( "@" ) || replyString.indexOf(" ") != -1 ) - { + + if (length == 0 || atPos == -1 || dotPos == -1 || atPos < 2 || dotPos < atPos + || dotPos + 2 == length || atPos + 2 == dotPos + || atPos != replyString.lastIndexOf("@") || replyString.indexOf(" ") != -1) { replyTextField.requestFocus(); - JOptionPane.showMessageDialog( window, "Please enter a valid reply to email address", "Input Error", JOptionPane.ERROR_MESSAGE ); + JOptionPane.showMessageDialog(window, + "Please enter a valid reply to email address", "Input Error", + JOptionPane.ERROR_MESSAGE); return false; } // subjectTextField must not be blank? String subjectString = subjectTextField.getText(); - if( subjectString.length() == 0 ) - { + + if (subjectString.length() == 0) { subjectTextField.requestFocus(); - JOptionPane.showMessageDialog( window, "Please enter subject title", "Input Error", JOptionPane.ERROR_MESSAGE ); + JOptionPane.showMessageDialog(window, "Please enter subject title", + "Input Error", JOptionPane.ERROR_MESSAGE); return false; } diff --git a/scripting/examples/java/Newsgroup/Sender.java b/scripting/examples/java/Newsgroup/Sender.java index efa3ed4c6753..00b3db87bacb 100644 --- a/scripting/examples/java/Newsgroup/Sender.java +++ b/scripting/examples/java/Newsgroup/Sender.java @@ -26,116 +26,112 @@ import java.io.*; import javax.activation.*; -public class Sender -{ +public class Sender { // Constructor params: private StatusWindow status = null; private OfficeAttachment attachments = null; private String replyto = ""; - private String subject = ""; - private String comment = ""; - private String hostname = ""; - private String newsgroup = ""; + private String subject = ""; + private String comment = ""; + private String hostname = ""; + private String newsgroup = ""; private String statusLine = ""; - public Sender( StatusWindow sw, OfficeAttachment attach, String reply, - String sub, String com, String host, String group ) - { + public Sender(StatusWindow sw, OfficeAttachment attach, String reply, + String sub, String com, String host, String group) { status = sw; attachments = attach; - replyto = reply; - subject = sub; - comment = com; - hostname = host; - newsgroup = group; + replyto = reply; + subject = sub; + comment = com; + hostname = host; + newsgroup = group; } - public boolean sendMail() - { + public boolean sendMail() { int statusPos = 5; - try - { + + try { attachments.createTempDocs(); // Property for any information Properties props = new Properties(); // Create unique session (null is unused authenticator info) statusLine = "Creating unique session"; - status.setStatus( statusPos, statusLine ); // 5 - Session session = Session.getInstance( props, null ); + status.setStatus(statusPos, statusLine); // 5 + Session session = Session.getInstance(props, null); // Create message statusPos++; // 6 statusLine = "Creating message"; - status.setStatus( statusPos, statusLine ); - MimeMessage message = new MimeMessage( session ); - message.setFrom( new InternetAddress( replyto ) ); - message.setSubject( subject ); - message.setText( comment ); - message.addHeader( "Newsgroups", newsgroup ); + status.setStatus(statusPos, statusLine); + MimeMessage message = new MimeMessage(session); + message.setFrom(new InternetAddress(replyto)); + message.setSubject(subject); + message.setText(comment); + message.addHeader("Newsgroups", newsgroup); // Buildup bodypart with text and attachments Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); - messageBodyPart.setText( comment ); - multipart.addBodyPart( messageBodyPart ); + messageBodyPart.setText(comment); + multipart.addBodyPart(messageBodyPart); statusPos++; // 7 statusLine = "Adding attachment(s)"; - status.setStatus( statusPos, statusLine ); + status.setStatus(statusPos, statusLine); File attachs[] = attachments.getAttachments(); - for(int i=0; i < attachs.length; i++ ) - { + + for (int i = 0; i < attachs.length; i++) { messageBodyPart = new MimeBodyPart(); - DataSource filesource = new FileDataSource( attachs[i] ); - messageBodyPart.setDataHandler( new DataHandler( filesource )); - messageBodyPart.setFileName( attachs[i].getName() ); - multipart.addBodyPart( messageBodyPart ); + DataSource filesource = new FileDataSource(attachs[i]); + messageBodyPart.setDataHandler(new DataHandler(filesource)); + messageBodyPart.setFileName(attachs[i].getName()); + multipart.addBodyPart(messageBodyPart); } // Add multipart to mail - message.setContent( multipart ); + message.setContent(multipart); // Create and send NNTP transport statusPos += 2; // 9 statusLine = "Creating NNTP transport"; - status.setStatus( statusPos, statusLine ); - Transport transport = new NNTPTransport( session, new URLName( "news:" + newsgroup )); + status.setStatus(statusPos, statusLine); + Transport transport = new NNTPTransport(session, + new URLName("news:" + newsgroup)); // Null parameters are for user name and password statusPos++; // 10 statusLine = "Connecting to mail server"; - status.setStatus( statusPos, statusLine ); - transport.connect( hostname, null, null ); + status.setStatus(statusPos, statusLine); + transport.connect(hostname, null, null); statusPos++; // 11 statusLine = "Sending message"; - status.setStatus( statusPos, statusLine ); - transport.sendMessage( message, message.getAllRecipients() ); + status.setStatus(statusPos, statusLine); + transport.sendMessage(message, message.getAllRecipients()); statusPos++; // 12 statusLine = "Closing transport"; - status.setStatus( statusPos, statusLine ); + status.setStatus(statusPos, statusLine); transport.close(); // Clean up when finished attachments.removeTempDocs(); return true; - } - catch( MessagingException me ) - { - if( statusPos == 10 ) - { + } catch (MessagingException me) { + if (statusPos == 10) { statusLine = "Error connecting (User authentication?)"; } - status.setStatus( statusPos, statusLine ); - System.out.println( "Error sending message: "); + + status.setStatus(statusPos, statusLine); + System.out.println("Error sending message: "); me.printStackTrace(); return false; } diff --git a/scripting/examples/java/Newsgroup/StatusWindow.java b/scripting/examples/java/Newsgroup/StatusWindow.java index b95fb3a91b07..7b37c8fa79d0 100644 --- a/scripting/examples/java/Newsgroup/StatusWindow.java +++ b/scripting/examples/java/Newsgroup/StatusWindow.java @@ -23,8 +23,7 @@ import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; -public class StatusWindow extends JFrame -{ +public class StatusWindow extends JFrame { private JProgressBar progressBar = null; private JTextField statusLabel = null; @@ -36,62 +35,59 @@ public class StatusWindow extends JFrame private final int MINPROGRESS = 0; - public StatusWindow( PostNewsgroup mw, String title, int parentX, int parentY ) - { - this.setTitle( title ); - this.setLocation( parentX + 100, parentY + 100 ); + public StatusWindow(PostNewsgroup mw, String title, int parentX, int parentY) { + this.setTitle(title); + this.setLocation(parentX + 100, parentY + 100); statusWindow = this; mainWindow = mw; - mainWindow.enableButtons( false ); + mainWindow.enableButtons(false); - statusWindow.addWindowListener( new WindowAdapter() - { - public void windowClosing( WindowEvent event ) { - mainWindow.enableButtons( true ); + statusWindow.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent event) { + mainWindow.enableButtons(true); } }); progressBar = new JProgressBar(); - progressBar.setStringPainted( true ); - progressBar.setMaximum( MAXPROGRESS ); - progressBar.setMinimum( MINPROGRESS ); - progressBar.setSize( 30, 400 ); + progressBar.setStringPainted(true); + progressBar.setMaximum(MAXPROGRESS); + progressBar.setMinimum(MINPROGRESS); + progressBar.setSize(30, 400); - JLabel progLabel = new JLabel( "Progress:" ); + JLabel progLabel = new JLabel("Progress:"); JPanel progressPanel = new JPanel(); - progressPanel.setLayout( new BorderLayout( 10, 0 ) ); - progressPanel.add( progLabel, "West" ); - progressPanel.add( progressBar, "East" ); + progressPanel.setLayout(new BorderLayout(10, 0)); + progressPanel.add(progLabel, "West"); + progressPanel.add(progressBar, "East"); statusLabel = new JTextField(); - statusLabel.setColumns( 25 ); - statusLabel.setEditable( false ); - statusLabel.setBorder( null ); + statusLabel.setColumns(25); + statusLabel.setEditable(false); + statusLabel.setBorder(null); JPanel statusPanel = new JPanel(); - statusPanel.setLayout( new BorderLayout() ); - statusPanel.add( statusLabel, "West" ); - - cancelButton = new JButton( "Cancel" ); - cancelButton.setSize( 30, 100 ); - cancelButton.setEnabled( false ); - cancelButton.addActionListener( new ActionListener() - { - public void actionPerformed( ActionEvent event ) { - // cancelling actions - mainWindow.enableButtons( true ); + statusPanel.setLayout(new BorderLayout()); + statusPanel.add(statusLabel, "West"); + + cancelButton = new JButton("Cancel"); + cancelButton.setSize(30, 100); + cancelButton.setEnabled(false); + cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { + // cancelling actions + mainWindow.enableButtons(true); statusWindow.dispose(); - } - }); + } + }); JPanel buttonPanel = new JPanel(); - buttonPanel.setLayout( new BorderLayout( 0, 5 ) ); - buttonPanel.add( cancelButton, "East" ); - buttonPanel.add( new JSeparator( SwingConstants.HORIZONTAL ), "North" ); + buttonPanel.setLayout(new BorderLayout(0, 5)); + buttonPanel.add(cancelButton, "East"); + buttonPanel.add(new JSeparator(SwingConstants.HORIZONTAL), "North"); Container container = getContentPane(); - container.setLayout( new GridBagLayout() ); + container.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; @@ -99,55 +95,51 @@ public class StatusWindow extends JFrame constraints.gridy = 0; constraints.gridwidth = 1; constraints.gridheight = 1; - constraints.insets = new Insets( 15, 15, 10, 15 ); - container.add( progressPanel, constraints ); + constraints.insets = new Insets(15, 15, 10, 15); + container.add(progressPanel, constraints); constraints.gridx = 0; constraints.gridy = 1; constraints.gridwidth = 1; constraints.gridheight = 1; - constraints.insets = new Insets( 10, 15, 10, 15 ); - container.add( statusPanel, constraints ); + constraints.insets = new Insets(10, 15, 10, 15); + container.add(statusPanel, constraints); constraints.gridx = 0; constraints.gridy = 2; constraints.gridwidth = 1; constraints.gridheight = 1; - constraints.insets = new Insets( 10, 15, 5, 15 ); - container.add( buttonPanel, constraints ); + constraints.insets = new Insets(10, 15, 5, 15); + container.add(buttonPanel, constraints); this.pack(); - this.setResizable( false ); + this.setResizable(false); } - public void setStatus( int progress, String status ) - { - progressBar.setValue( progress ); - statusLabel.setText( status ); - statusLabel.setToolTipText( status ); - if( progress == MAXPROGRESS ) - { - cancelButton.setEnabled( true ); - cancelButton.setText( "Close" ); + public void setStatus(int progress, String status) { + progressBar.setValue(progress); + statusLabel.setText(status); + statusLabel.setToolTipText(status); + + if (progress == MAXPROGRESS) { + cancelButton.setEnabled(true); + cancelButton.setText("Close"); } - update( getGraphics() ); - mainWindow.update( mainWindow.getGraphics() ); + + update(getGraphics()); + mainWindow.update(mainWindow.getGraphics()); } - public void enableCancelButton( boolean enable ) - { - if( enable ) - { - cancelButton.setEnabled( true ); - cancelButton.setText( "Finish" ); - } - else - { - cancelButton.setEnabled( false ); - cancelButton.setText( "Cancel" ); + public void enableCancelButton(boolean enable) { + if (enable) { + cancelButton.setEnabled(true); + cancelButton.setText("Finish"); + } else { + cancelButton.setEnabled(false); + cancelButton.setText("Cancel"); } } diff --git a/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java b/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java index a4f230becee7..eb135a3e8f3d 100644 --- a/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java +++ b/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java @@ -28,21 +28,18 @@ public class SubscribedNewsgroups { private static NewsGroup[] allSubscribed = null; private static boolean windows = false; - public static void main( String[] args ) { + public static void main(String[] args) { // Test the class SubscribedNewsgroups subscribed = new SubscribedNewsgroups(); NewsGroup allGroups[] = subscribed.getNewsGroups(); - if( allGroups == null ) - { + if (allGroups == null) { System.out.println("Could not find subscribed newsgroups from mozilla/netscape mailrc files"); - } - else - { - for( int i=0; i < allGroups.length; i++ ) - { - System.out.println( "Hostname is: " + allGroups[i].getHostName() + " Newsgroup is: " + allGroups[i].getNewsgroupName() ); + } else { + for (int i = 0; i < allGroups.length; i++) { + System.out.println("Hostname is: " + allGroups[i].getHostName() + + " Newsgroup is: " + allGroups[i].getNewsgroupName()); } } } @@ -51,84 +48,87 @@ public class SubscribedNewsgroups { // Only public method of the class // Returns and array of unique NewsGroup objects - public NewsGroup[] getNewsGroups() - { + public NewsGroup[] getNewsGroups() { windows = false; - if( System.getProperty( "os.name" ).indexOf( "Windows" ) != -1 ) - { + + if (System.getProperty("os.name").indexOf("Windows") != -1) { windows = true; } String mozillaHome = ""; - if( windows ) - { - mozillaHome = System.getProperty( "user.home" ) + System.getProperty( "file.separator" ) + "Application Data" + System.getProperty( "file.separator" ) + "Mozilla" + System.getProperty( "file.separator" ) + "Profiles"; - } - else - { - mozillaHome = System.getProperty( "user.home" ) + System.getProperty( "file.separator" ) + ".mozilla"; + + if (windows) { + mozillaHome = System.getProperty("user.home") + + System.getProperty("file.separator") + "Application Data" + + System.getProperty("file.separator") + "Mozilla" + + System.getProperty("file.separator") + "Profiles"; + } else { + mozillaHome = System.getProperty("user.home") + + System.getProperty("file.separator") + ".mozilla"; } - if( !new File( mozillaHome ).isDirectory() ) - { + + if (!new File(mozillaHome).isDirectory()) { return null; } // Get all the profiles belonging to the user - File profiles[] = findProfiles( new File ( mozillaHome ) ); - if( profiles.length < 1 ) - { + File profiles[] = findProfiles(new File(mozillaHome)); + + if (profiles.length < 1) { return null; } // Get the News directory for each profile File allNewsDirs[] = new File[ profiles.length ]; - for( int i=0; i < profiles.length; i++ ) { - File newsDir = findNewsDir( profiles[i] ); + + for (int i = 0; i < profiles.length; i++) { + File newsDir = findNewsDir(profiles[i]); allNewsDirs[i] = newsDir; } + // Check that at least one News directory exists and remove nulls boolean newsFound = false; - for( int i=0; i < allNewsDirs.length; i++ ) { - if( allNewsDirs[i] != null ) { + + for (int i = 0; i < allNewsDirs.length; i++) { + if (allNewsDirs[i] != null) { newsFound = true; break; } } - if( !newsFound ) - { + + if (!newsFound) { return null; } // Get all the mailrc files for each News directory - File allMailrcs[] = findMailrcFiles( allNewsDirs ); - if( allMailrcs == null ) - { + File allMailrcs[] = findMailrcFiles(allNewsDirs); + + if (allMailrcs == null) { return null; } ArrayList subscribed = new ArrayList(); + // Get the newsgroups in each mailrc file - for( int i=0; i < allMailrcs.length; i++ ) - { + for (int i = 0; i < allMailrcs.length; i++) { File mailrc = (File) allMailrcs[i]; - NewsGroup newsgroup[] = findNewsgroups( mailrc ); + NewsGroup newsgroup[] = findNewsgroups(mailrc); + //if the Newsgroup has not already been added to the list - for( int j=0; j < newsgroup.length; j++ ) - { + for (int j = 0; j < newsgroup.length; j++) { // if newsgroup is unique then add to the list - if( !listed( newsgroup[j], subscribed ) ) - { - subscribed.addElement( newsgroup[j] ); + if (!listed(newsgroup[j], subscribed)) { + subscribed.addElement(newsgroup[j]); } } } // Copy all unique Newsgroups into the global array allSubscribed = new NewsGroup[ subscribed.size() ]; - subscribed.toArray( allSubscribed ); + subscribed.toArray(allSubscribed); + // Test that at least one subscribed newsgroup has been found - if( allSubscribed.length < 1 ) - { + if (allSubscribed.length < 1) { return null; } @@ -139,16 +139,17 @@ public class SubscribedNewsgroups { // Tests if the NewsGroup object has already been listed by another mailrc file - private static boolean listed( NewsGroup newsgroup, ArrayList uniqueSubscription ) - { - for(int i=0; i < uniqueSubscription.size(); i++) - { + private static boolean listed(NewsGroup newsgroup, + ArrayList uniqueSubscription) { + for (int i = 0; i < uniqueSubscription.size(); i++) { NewsGroup tempGroup = uniqueSubscription.elementAt(i); + // Test for duplication - if(newsgroup.getHostName().equalsIgnoreCase( tempGroup.getHostName()) && - newsgroup.getNewsgroupName().equalsIgnoreCase( tempGroup.getNewsgroupName() ) ) + if (newsgroup.getHostName().equalsIgnoreCase(tempGroup.getHostName()) && + newsgroup.getNewsgroupName().equalsIgnoreCase(tempGroup.getNewsgroupName())) return true; } + return false; } @@ -156,8 +157,7 @@ public class SubscribedNewsgroups { // Finds all the NewsGroups in an individual mailrc file - private static NewsGroup[] findNewsgroups(File mailrcfile ) - { + private static NewsGroup[] findNewsgroups(File mailrcfile) { String hostname = ""; String newsgroup = ""; @@ -168,46 +168,45 @@ public class SubscribedNewsgroups { //If the newsgroup is not already contained in the global NewsGroup[] array then add it String filename = mailrcfile.getPath(); - if( windows ) - { + + if (windows) { // Windows format "staroffice-news.germany.sun.com.rc" int hostNameStart = filename.lastIndexOf("\\") + 1; int hostNameEnd = filename.indexOf(".rc"); - hostname = filename.substring( hostNameStart, hostNameEnd ); - } - else - { + hostname = filename.substring(hostNameStart, hostNameEnd); + } else { // Unix/Linux format "newsrc-staroffice-news.germany.sun.com" int hostNameStart = filename.lastIndexOf("newsrc-") + 7; - hostname = filename.substring( hostNameStart, filename.length() ); + hostname = filename.substring(hostNameStart, filename.length()); } // Assumes the content format in Window is the same as Unix/Linux (unknown at the moment) // i.e. a list of newsgroups each ending with a ":" LineNumberReader in = null; + try { - in = new LineNumberReader( new FileReader( mailrcfile ) ); + in = new LineNumberReader(new FileReader(mailrcfile)); ArrayList groups = new ArrayList(); String inString = ""; int line = 0; - while( inString != null ) - { - in.setLineNumber( line ); + + while (inString != null) { + in.setLineNumber(line); inString = in.readLine(); line++; - if( inString != null ) - { + + if (inString != null) { int newsgroupEnd = inString.indexOf(":"); - newsgroup = inString.substring( 0, newsgroupEnd ); - NewsGroup group = new NewsGroup( hostname, newsgroup ); - groups.addElement( group ); + newsgroup = inString.substring(0, newsgroupEnd); + NewsGroup group = new NewsGroup(hostname, newsgroup); + groups.addElement(group); } } + mailrcNewsGroups = new NewsGroup[ groups.size() ]; groups.copyInto(mailrcNewsGroups); in.close(); - } - catch( IOException ioe ) { + } catch (IOException ioe) { ioe.printStackTrace(); } @@ -216,28 +215,25 @@ public class SubscribedNewsgroups { // Finds all the mailrc files for all the given News directories - private static File[] findMailrcFiles(File[] newsDirs) - { + private static File[] findMailrcFiles(File[] newsDirs) { ArrayList allFiles = new ArrayList(); - for( int i=0; i < newsDirs.length; i++ ) - { - if( newsDirs[i] != null ) - { - File mailrcFiles[] = newsDirs[i].listFiles( new VersionFilter() ); - if( mailrcFiles != null ) - { - for( int j=0; j < mailrcFiles.length; j++ ) - { - allFiles.addElement( mailrcFiles[j] ); + for (int i = 0; i < newsDirs.length; i++) { + if (newsDirs[i] != null) { + File mailrcFiles[] = newsDirs[i].listFiles(new VersionFilter()); + + if (mailrcFiles != null) { + for (int j = 0; j < mailrcFiles.length; j++) { + allFiles.addElement(mailrcFiles[j]); } } } } + File allMailrcFiles[] = new File[ allFiles.size() ]; allFiles.copyInto(allMailrcFiles); - if( allMailrcFiles.length == 0 ) { + if (allMailrcFiles.length == 0) { return null; } @@ -246,18 +242,15 @@ public class SubscribedNewsgroups { // Finds all profiles belonging to one user (can be more than one) - private static File[] findProfiles(File start) - { + private static File[] findProfiles(File start) { // Get all files and directories in .mozilla File allFiles[] = start.listFiles(); File[] dirs = new File[allFiles.length]; int dirCounter = 0; // Remove files leaving directories only - for(int i=0; i < allFiles.length; i++ ) - { - if(allFiles[i].isDirectory()) - { + for (int i = 0; i < allFiles.length; i++) { + if (allFiles[i].isDirectory()) { dirs[dirCounter] = allFiles[i]; dirCounter++; } @@ -265,8 +258,8 @@ public class SubscribedNewsgroups { // Add each directory to a user profile array File[] profileDirs = new File[dirCounter]; - for( int i=0; i < dirCounter; i++ ) - { + + for (int i = 0; i < dirCounter; i++) { profileDirs[i] = dirs[i]; } @@ -276,97 +269,81 @@ public class SubscribedNewsgroups { // Recursively searches for the News directory for a given profile directory - private static File findNewsDir(File start) - { - File mailrcFile = null; + private static File findNewsDir(File start) { + File mailrcFile = null; // File array containing all matches for the version filter ("News") - File files[] = start.listFiles(new VersionFilter()); + File files[] = start.listFiles(new VersionFilter()); + // If the array is empty then no matches were found - if (files.length == 0) - { + if (files.length == 0) { // File array of all the directories in File start - File dirs[] = start.listFiles(new DirFilter()); + File dirs[] = start.listFiles(new DirFilter()); + // for each of the directories check for a match - for (int i=0; i< dirs.length; i++) - { - mailrcFile = findNewsDir(dirs[i]); - if (mailrcFile != null) - { + for (int i = 0; i < dirs.length; i++) { + mailrcFile = findNewsDir(dirs[i]); + + if (mailrcFile != null) { // break the for loop - break; - } - } + break; } - else - { + } + } else { // end recursion // Check for a News directory inside the News directory (fix for bug) // Original solution had only "mailrcFile = files[0];" boolean noChildNews = true; File checkChildNewsDirs[] = files[0].listFiles(new VersionFilter()); - if( checkChildNewsDirs != null ) - { - for( int i=0; i < checkChildNewsDirs.length; i++ ) - { - if( checkChildNewsDirs[i].getName().equals( "News" ) ) - { + + if (checkChildNewsDirs != null) { + for (int i = 0; i < checkChildNewsDirs.length; i++) { + if (checkChildNewsDirs[i].getName().equals("News")) { noChildNews = false; break; } } } - if( noChildNews ) - { - mailrcFile = files[0]; - } - else - { - String childNewsPathName = files[0].getAbsolutePath() + System.getProperty( "file.separator" ) + "News"; - mailrcFile = new File( childNewsPathName ); + if (noChildNews) { + mailrcFile = files[0]; + } else { + String childNewsPathName = files[0].getAbsolutePath() + + System.getProperty("file.separator") + "News"; + mailrcFile = new File(childNewsPathName); } } // return a File representing the News dir in a profile - return mailrcFile; + return mailrcFile; } } -class DirFilter implements FileFilter -{ - public boolean accept(File aFile) - { - return aFile.isDirectory(); - } +class DirFilter implements FileFilter { + public boolean accept(File aFile) { + return aFile.isDirectory(); + } } -class VersionFilter implements FileFilter -{ - public boolean accept(File aFile) - { - if( System.getProperty( "os.name" ).indexOf( "Windows" ) != -1 ) - { +class VersionFilter implements FileFilter { + public boolean accept(File aFile) { + if (System.getProperty("os.name").indexOf("Windows") != -1) { if (aFile.getName().compareToIgnoreCase("News") == 0 || - aFile.getName().indexOf(".rc") != -1 ) - { + aFile.getName().indexOf(".rc") != -1) { return true; } - } - else - { + } else { if (aFile.getName().compareToIgnoreCase("News") == 0 || - aFile.getName().indexOf("newsrc") != -1 ) - { + aFile.getName().indexOf("newsrc") != -1) { return true; } } - return false; - } + return false; + } } diff --git a/scripting/examples/java/debugger/DebugRunner.java b/scripting/examples/java/debugger/DebugRunner.java index 4a5ee119608e..8e6c1438a8fc 100644 --- a/scripting/examples/java/debugger/DebugRunner.java +++ b/scripting/examples/java/debugger/DebugRunner.java @@ -31,22 +31,20 @@ import com.sun.star.script.framework.runtime.XScriptContext; public class DebugRunner { private static final String FILE_URL_PREFIX = - System.getProperty("os.name").startsWith("Windows") == true ? - "file:///" : "file://"; + System.getProperty("os.name").startsWith("Windows") == true ? + "file:///" : "file://"; public void go(final XScriptContext xsctxt, String language, String uri, - String filename) { + String filename) { OOScriptDebugger debugger; String path = ""; if (language.equals("JavaScript")) { debugger = new OORhinoDebugger(); - } - else if (language.equals("BeanShell")) { + } else if (language.equals("BeanShell")) { debugger = new OOBeanShellDebugger(); - } - else { + } else { return; } @@ -60,14 +58,13 @@ public class DebugRunner { if (!filename.equals("")) { path = new File(f, filename).getAbsolutePath(); } - } - else { + } else { path = f.getAbsolutePath(); } } + debugger.go(xsctxt, path); - } - else { + } else { if (!uri.endsWith("/")) { uri += "/"; } @@ -77,13 +74,12 @@ public class DebugRunner { try { is = PathUtils.getScriptFileStream( - script, xsctxt.getComponentContext()); + script, xsctxt.getComponentContext()); if (is != null) { debugger.go(xsctxt, is); } - } - catch (IOException ioe) { + } catch (IOException ioe) { System.out.println("Error loading script: " + script); } } diff --git a/scripting/examples/java/debugger/OOBeanShellDebugger.java b/scripting/examples/java/debugger/OOBeanShellDebugger.java index a3286fbc0546..23811fd6aa49 100644 --- a/scripting/examples/java/debugger/OOBeanShellDebugger.java +++ b/scripting/examples/java/debugger/OOBeanShellDebugger.java @@ -50,7 +50,8 @@ import java.io.IOException; import drafts.com.sun.star.script.framework.runtime.XScriptContext; import bsh.Interpreter; -public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, DocumentListener { +public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, + DocumentListener { private JFrame frame; private JTextArea ta; @@ -69,11 +70,10 @@ public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, Do FileInputStream fis = new FileInputStream(filename); this.filename = filename; go(context, fis); - } - catch (IOException ioe) { + } catch (IOException ioe) { JOptionPane.showMessageDialog(frame, - "Error loading file: " + ioe.getMessage(), - "Error", JOptionPane.ERROR_MESSAGE); + "Error loading file: " + ioe.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); } } } @@ -86,11 +86,10 @@ public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, Do if (in != null) { try { loadFile(in); - } - catch (IOException ioe) { + } catch (IOException ioe) { JOptionPane.showMessageDialog(frame, - "Error loading stream: " + ioe.getMessage(), - "Error", JOptionPane.ERROR_MESSAGE); + "Error loading stream: " + ioe.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); } } } @@ -111,8 +110,7 @@ public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, Do try { in.close(); - } - catch (IOException ignore) { + } catch (IOException ignore) { } /* Update the GlyphGutter and add back the DocumentListener */ @@ -190,29 +188,28 @@ public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, Do try { interpreter.set("context", context); interpreter.eval(ta.getText()); - } - catch (bsh.EvalError err) { + } catch (bsh.EvalError err) { currentPosition = err.getErrorLineNumber() - 1; + try { // scroll to line of the error int line = ta.getLineStartOffset(currentPosition); Rectangle rect = ta.modelToView(line); ta.scrollRectToVisible(rect); - } - catch (Exception e) { + } catch (Exception e) { // couldn't scroll to line, do nothing } + gg.repaint(); JOptionPane.showMessageDialog(frame, "Error at line " + - String.valueOf(err.getErrorLineNumber()) + - "\n\n: " + err.getErrorText(), - "Error", JOptionPane.ERROR_MESSAGE); - } - catch (Exception e) { + String.valueOf(err.getErrorLineNumber()) + + "\n\n: " + err.getErrorText(), + "Error", JOptionPane.ERROR_MESSAGE); + } catch (Exception e) { JOptionPane.showMessageDialog(frame, - "Error: " + e.getMessage(), - "Error", JOptionPane.ERROR_MESSAGE); + "Error: " + e.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); } } }; @@ -226,6 +223,7 @@ public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, Do if (f.isDirectory() || f.getName().endsWith(".bsh")) { return true; } + return false; } @@ -238,6 +236,7 @@ public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, Do if (ret == JFileChooser.APPROVE_OPTION) { filename = chooser.getSelectedFile().getAbsolutePath(); + if (!filename.endsWith(".bsh")) { filename += ".bsh"; } @@ -251,24 +250,22 @@ public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, Do } FileOutputStream fos = null; + if (filename != null) { try { File f = new File(filename); fos = new FileOutputStream(f); String s = ta.getText(); fos.write(s.getBytes(), 0, s.length()); - } - catch (IOException ioe) { + } catch (IOException ioe) { JOptionPane.showMessageDialog(frame, - "Error saving file: " + ioe.getMessage(), - "Error", JOptionPane.ERROR_MESSAGE); - } - finally { + "Error saving file: " + ioe.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + } finally { if (fos != null) { try { fos.close(); - } - catch (IOException ignore) { + } catch (IOException ignore) { } } } @@ -278,14 +275,11 @@ public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, Do public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Run")) { startExecution(); - } - else if (e.getActionCommand().equals("Close")) { + } else if (e.getActionCommand().equals("Close")) { frame.dispose(); - } - 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")) { ta.setText(""); } } @@ -319,6 +313,7 @@ class GlyphGutter extends JComponent { int lineCount = textArea.getLineCount() + 1; String dummy = Integer.toString(lineCount); + if (dummy.length() < 2) { dummy = DUMMY_STRING; } @@ -349,6 +344,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; } @@ -376,12 +372,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/examples/java/debugger/OORhinoDebugger.java b/scripting/examples/java/debugger/OORhinoDebugger.java index b4858e40c278..f0d7aee3c0fa 100644 --- a/scripting/examples/java/debugger/OORhinoDebugger.java +++ b/scripting/examples/java/debugger/OORhinoDebugger.java @@ -52,32 +52,33 @@ public class OORhinoDebugger implements OOScriptDebugger { try { final Main sdb = new Main("Rhino JavaScript Debugger"); swingInvoke(new Runnable() { - public void run() { - sdb.pack(); - sdb.setSize(640, 640); - sdb.setVisible(true); - } - }); + public void run() { + sdb.pack(); + sdb.setSize(640, 640); + sdb.setVisible(true); + } + }); sdb.setExitAction(new Runnable() { - public void run() { - sdb.dispose(); - } - }); + public void run() { + sdb.dispose(); + } + }); Context.addContextListener(sdb); sdb.setScopeProvider(new ScopeProvider() { - public Scriptable getScope() { - Context ctxt = Context.enter(); - ImporterTopLevel scope = new ImporterTopLevel(ctxt); - Scriptable jsArgs = Context.toObject(xsctxt, scope); - scope.put("XSCRIPTCONTEXT", scope, jsArgs); - Context.exit(); - return scope; - } - }); + public Scriptable getScope() { + Context ctxt = Context.enter(); + ImporterTopLevel scope = new ImporterTopLevel(ctxt); + Scriptable jsArgs = Context.toObject(xsctxt, scope); + scope.put("XSCRIPTCONTEXT", scope, jsArgs); + Context.exit(); + return scope; + } + }); return sdb; } catch (Exception exc) { exc.printStackTrace(); } + return null; } @@ -86,6 +87,7 @@ public class OORhinoDebugger implements OOScriptDebugger { f.run(); return; } + try { SwingUtilities.invokeAndWait(f); } catch (Exception exc) { diff --git a/scripting/examples/java/selector/ScriptSelector.java b/scripting/examples/java/selector/ScriptSelector.java index e0ff41e65cdf..ed3cfd441ab5 100644 --- a/scripting/examples/java/selector/ScriptSelector.java +++ b/scripting/examples/java/selector/ScriptSelector.java @@ -63,25 +63,23 @@ public class ScriptSelector { private ScriptSelectorPanel selectorPanel; - public ScriptSelector() - { + public ScriptSelector() { } - public void showOrganizer(final XScriptContext ctxt) - { + public void showOrganizer(final XScriptContext ctxt) { try { XBrowseNode root = getRootNode(ctxt); final XScriptProvider msp = (XScriptProvider)UnoRuntime.queryInterface( - XScriptProvider.class, root); + XScriptProvider.class, root); final JFrame client = new JFrame("Script"); selectorPanel = new ScriptSelectorPanel(root); final JButton runButton, closeButton, createButton, - editButton, deleteButton; + editButton, deleteButton; runButton = new JButton("Run"); runButton.setEnabled(false); @@ -111,27 +109,24 @@ public class ScriptSelector { southButtons.add(deleteButton); selectorPanel.tree.addTreeSelectionListener( - new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - XBrowseNode xbn = selectorPanel.getSelection(); - XPropertySet props = (XPropertySet) - UnoRuntime.queryInterface(XPropertySet.class, xbn); - - checkEnabled(props, "Creatable", createButton); - checkEnabled(props, "Deletable", deleteButton); - checkEnabled(props, "Editable", editButton); - - if (xbn != null && - xbn.getType() == BrowseNodeTypes.SCRIPT) - { - runButton.setEnabled(true); - } - else - { - runButton.setEnabled(false); - } + new TreeSelectionListener() { + public void valueChanged(TreeSelectionEvent e) { + XBrowseNode xbn = selectorPanel.getSelection(); + XPropertySet props = (XPropertySet) + UnoRuntime.queryInterface(XPropertySet.class, xbn); + + checkEnabled(props, "Creatable", createButton); + checkEnabled(props, "Deletable", deleteButton); + checkEnabled(props, "Editable", editButton); + + if (xbn != null && + xbn.getType() == BrowseNodeTypes.SCRIPT) { + runButton.setEnabled(true); + } else { + runButton.setEnabled(false); } } + } ); ActionListener listener = new ActionListener() { @@ -149,36 +144,31 @@ public class ScriptSelector { num[0] = new short[0]; script.invoke(new Object[0], num, out); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } - } - else if (event.getSource() == closeButton) { + } else if (event.getSource() == closeButton) { client.dispose(); - } - else if (event.getSource() == editButton) { + } else if (event.getSource() == editButton) { DefaultMutableTreeNode node = - (DefaultMutableTreeNode) - selectorPanel.tree.getLastSelectedPathComponent(); + (DefaultMutableTreeNode) + selectorPanel.tree.getLastSelectedPathComponent(); if (node == null) return; showEditor(ctxt, node); - } - else if (event.getSource() == createButton) { + } else if (event.getSource() == createButton) { DefaultMutableTreeNode node = - (DefaultMutableTreeNode) - selectorPanel.tree.getLastSelectedPathComponent(); + (DefaultMutableTreeNode) + selectorPanel.tree.getLastSelectedPathComponent(); if (node == null) return; doCreate(ctxt, node); - } - else if (event.getSource() == deleteButton) { + } else if (event.getSource() == deleteButton) { DefaultMutableTreeNode node = - (DefaultMutableTreeNode) - selectorPanel.tree.getLastSelectedPathComponent(); + (DefaultMutableTreeNode) + selectorPanel.tree.getLastSelectedPathComponent(); if (node == null) return; @@ -217,114 +207,96 @@ public class ScriptSelector { client.setLocation(x, y); client.show(); - } - catch (com.sun.star.uno.RuntimeException rue) { + } catch (com.sun.star.uno.RuntimeException rue) { rue.printStackTrace(); - } - catch (java.lang.Exception e) { + } catch (java.lang.Exception e) { e.printStackTrace(); } } public void showOrganizer(final XScriptContext ctxt, - final com.sun.star.awt.MouseEvent e) - { + final com.sun.star.awt.MouseEvent e) { showOrganizer(ctxt); } public void showOrganizer(final XScriptContext ctxt, - final com.sun.star.awt.ActionEvent e) - { + final com.sun.star.awt.ActionEvent e) { showOrganizer(ctxt); } private void doDelete( - XScriptContext ctxt, DefaultMutableTreeNode node) - { + XScriptContext ctxt, DefaultMutableTreeNode node) { Object obj = node.getUserObject(); XInvocation inv = (XInvocation)UnoRuntime.queryInterface( - XInvocation.class, obj); + XInvocation.class, obj); Object[] args = new Object[] { ctxt }; + try { Object result = inv.invoke("Deletable", args, - new short[1][0], new Object[1][0]); + new short[1][0], new Object[1][0]); - if (result != null && AnyConverter.toBoolean(result) == true) - { + if (result != null && AnyConverter.toBoolean(result) == true) { selectorPanel.removeNode(node); } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } private void doCreate( - XScriptContext ctxt, DefaultMutableTreeNode node) - { + XScriptContext ctxt, DefaultMutableTreeNode node) { Object obj = node.getUserObject(); XInvocation inv = (XInvocation)UnoRuntime.queryInterface( - XInvocation.class, obj); + XInvocation.class, obj); Object[] args = new Object[] { ctxt }; + try { Object result = inv.invoke("Creatable", args, - new short[1][0], new Object[1][0]); + new short[1][0], new Object[1][0]); - if (result != null) - { + if (result != null) { XBrowseNode xbn = (XBrowseNode) - AnyConverter.toObject(new Type(XBrowseNode.class), result); + AnyConverter.toObject(new Type(XBrowseNode.class), result); selectorPanel.addNode(node, xbn); } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } private void showEditor( - XScriptContext ctxt, DefaultMutableTreeNode node) - { + XScriptContext ctxt, DefaultMutableTreeNode node) { Object obj = node.getUserObject(); XInvocation inv = (XInvocation)UnoRuntime.queryInterface( - XInvocation.class, obj); + XInvocation.class, obj); Object[] args = new Object[] { ctxt }; + try { inv.invoke("Editable", args, - new short[1][0], new Object[1][0]); - } - catch (Exception e) { + new short[1][0], new Object[1][0]); + } catch (Exception e) { e.printStackTrace(); } } private void checkEnabled(XPropertySet props, String name, - JButton button) - { + JButton button) { boolean enable = false; - try - { - if (props != null) - { + try { + if (props != null) { Object o = props.getPropertyValue(name); enable = AnyConverter.toBoolean( - props.getPropertyValue(name)); + props.getPropertyValue(name)); } - } - catch (com.sun.star.lang.IllegalArgumentException iae) - { + } catch (com.sun.star.lang.IllegalArgumentException iae) { // leave enable set to false - } - catch (com.sun.star.beans.UnknownPropertyException upe) - { + } catch (com.sun.star.beans.UnknownPropertyException upe) { // leave enable set to false - } - catch (com.sun.star.lang.WrappedTargetException wte) - { + } catch (com.sun.star.lang.WrappedTargetException wte) { // leave enable set to false } @@ -339,12 +311,13 @@ public class ScriptSelector { XComponentContext xcc = ctxt.getComponentContext(); XMultiComponentFactory xmcf = xcc.getServiceManager(); XBrowseNodeFactory xBrowseFac = (XBrowseNodeFactory) - UnoRuntime.queryInterface( XBrowseNodeFactory.class, xcc.getValueByName( - "/singletons/com.sun.star.script.browse.theBrowseNodeFactory") ); + UnoRuntime.queryInterface(XBrowseNodeFactory.class, xcc.getValueByName( + "/singletons/com.sun.star.script.browse.theBrowseNodeFactory")); result = (XBrowseNode)UnoRuntime.queryInterface( - XBrowseNode.class, xBrowseFac.createView( BrowseNodeFactoryViewTypes.MACROORGANIZER ) ); + XBrowseNode.class, xBrowseFac.createView( + BrowseNodeFactoryViewTypes.MACROORGANIZER)); return result; } } @@ -356,15 +329,14 @@ class ScriptSelectorPanel extends JPanel { public JTree tree; public DefaultTreeModel treeModel; - public ScriptSelectorPanel(XBrowseNode root) - { + public ScriptSelectorPanel(XBrowseNode root) { this.myrootnode = root; initUI(); } public XBrowseNode getSelection() { DefaultMutableTreeNode node = (DefaultMutableTreeNode) - tree.getLastSelectedPathComponent(); + tree.getLastSelectedPathComponent(); if (node == null) { return null; @@ -377,11 +349,11 @@ class ScriptSelectorPanel extends JPanel { setLayout(new BorderLayout()); DefaultMutableTreeNode top = - new DefaultMutableTreeNode(myrootnode) { - public String toString() { - return ((XBrowseNode)getUserObject()).getName(); - } - }; + new DefaultMutableTreeNode(myrootnode) { + public String toString() { + return ((XBrowseNode)getUserObject()).getName(); + } + }; initNodes(myrootnode, top); treeModel = new DefaultTreeModel(top); tree = new JTree(treeModel); @@ -389,13 +361,13 @@ class ScriptSelectorPanel extends JPanel { tree.setCellRenderer(new ScriptTreeRenderer()); tree.getSelectionModel().setSelectionMode - (TreeSelectionModel.SINGLE_TREE_SELECTION); + (TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { XBrowseNode xbn = getSelection(); XPropertySet props = (XPropertySet)UnoRuntime.queryInterface( - XPropertySet.class, xbn); + XPropertySet.class, xbn); if (xbn == null) { textField.setText(""); @@ -403,16 +375,16 @@ class ScriptSelectorPanel extends JPanel { } String str = xbn.getName(); - if (xbn.getType() == BrowseNodeTypes.SCRIPT && props != null) - { + + if (xbn.getType() == BrowseNodeTypes.SCRIPT && props != null) { try { str = AnyConverter.toString( - props.getPropertyValue("URI")); - } - catch (Exception ignore) { + props.getPropertyValue("URI")); + } catch (Exception ignore) { // default will be used } } + textField.setText(str); } }); @@ -426,6 +398,7 @@ class ScriptSelectorPanel extends JPanel { public void removeNode(DefaultMutableTreeNode node) { MutableTreeNode parent = (MutableTreeNode)(node.getParent()); + if (parent != null) { treeModel.removeNodeFromParent(node); } @@ -433,19 +406,18 @@ class ScriptSelectorPanel extends JPanel { public void addNode(DefaultMutableTreeNode parent, XBrowseNode xbn) { DefaultMutableTreeNode newNode = - new DefaultMutableTreeNode(xbn) { - public String toString() { - return ((XBrowseNode)getUserObject()).getName(); - } - }; + new DefaultMutableTreeNode(xbn) { + public String toString() { + return ((XBrowseNode)getUserObject()).getName(); + } + }; treeModel.insertNodeInto(newNode, parent, parent.getChildCount()); tree.scrollPathToVisible(new TreePath(newNode.getPath())); } private void initNodes(XBrowseNode parent, DefaultMutableTreeNode top) { - if ( parent == null || parent.hasChildNodes() == false ) - { + if (parent == null || parent.hasChildNodes() == false) { return; } @@ -454,22 +426,21 @@ class ScriptSelectorPanel extends JPanel { try { if (children != null) { for (int i = 0; i < children.length; i++) { - if ( children[i] == null ) - { + if (children[i] == null) { continue; } + DefaultMutableTreeNode newNode = - new DefaultMutableTreeNode(children[i]) { - public String toString() { - return ((XBrowseNode)getUserObject()).getName(); - } - }; + new DefaultMutableTreeNode(children[i]) { + public String toString() { + return ((XBrowseNode)getUserObject()).getName(); + } + }; top.add(newNode); initNodes(children[i], newNode); } } - } - catch (java.lang.Exception e) { + } catch (java.lang.Exception e) { e.printStackTrace(); } } @@ -488,28 +459,27 @@ class ScriptTreeRenderer extends DefaultTreeCellRenderer { } public Component getTreeCellRendererComponent( - JTree tree, - Object value, - boolean sel, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) { + JTree tree, + Object value, + boolean sel, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { super.getTreeCellRendererComponent( - tree, value, sel, - expanded, leaf, row, - hasFocus); + tree, value, sel, + expanded, leaf, row, + hasFocus); DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; XBrowseNode xbn = (XBrowseNode)node.getUserObject(); + if (xbn.getType() == BrowseNodeTypes.SCRIPT) { setIcon(scriptIcon); - } - else if(xbn.getType() == BrowseNodeTypes.CONTAINER) { + } else if (xbn.getType() == BrowseNodeTypes.CONTAINER) { setIcon(containerIcon); - } - else if(xbn.getType() == BrowseNodeTypes.ROOT) { + } else if (xbn.getType() == BrowseNodeTypes.ROOT) { setIcon(sofficeIcon); } -- cgit