diff options
Diffstat (limited to 'scripting/examples/java')
-rw-r--r-- | scripting/examples/java/Newsgroup/MimeConfiguration.java | 219 | ||||
-rw-r--r-- | scripting/examples/java/Newsgroup/NewsGroup.java | 23 | ||||
-rw-r--r-- | scripting/examples/java/Newsgroup/OfficeAttachment.java | 307 | ||||
-rw-r--r-- | scripting/examples/java/Newsgroup/PostNewsgroup.java | 625 | ||||
-rw-r--r-- | scripting/examples/java/Newsgroup/Sender.java | 126 | ||||
-rw-r--r-- | scripting/examples/java/Newsgroup/StatusWindow.java | 137 | ||||
-rw-r--r-- | scripting/examples/java/Newsgroup/SubscribedNewsgroups.java | 343 |
7 files changed, 1780 insertions, 0 deletions
diff --git a/scripting/examples/java/Newsgroup/MimeConfiguration.java b/scripting/examples/java/Newsgroup/MimeConfiguration.java new file mode 100644 index 000000000000..86feec7ce370 --- /dev/null +++ b/scripting/examples/java/Newsgroup/MimeConfiguration.java @@ -0,0 +1,219 @@ +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.uno.XComponentContext; +import drafts.com.sun.star.script.framework.XScriptContext; +import com.sun.star.util.XStringSubstitution; + +import javax.mail.*; +import javax.activation.*; + +import java.io.*; + + +public class MimeConfiguration +{ + + // Office Installation path + private static String instPath = ""; + + + 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)" ); + + } + 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" ); + e.printStackTrace(); + } + + writeMailCap(); + writeMimeTypes(); + + // ToDo: include status feedback to StatusWindow + return true; + } + + + + + private static void writeMailCap() + { + String mailcapPath = getConfigDir() + System.getProperty( "file.separator" ) + "mailcap"; + + try + { + if( ! new File( java.net.URLDecoder.decode( mailcapPath ) ).exists() ) + { + //System.out.println( "URLDecoder: " + java.net.URLDecoder.decode( mailcapPath ) ); + File mailcapFile = new File( mailcapPath ); + FileWriter out = new FileWriter( mailcapFile ); + String[] lines = getMailcapText(); + for( int i=0; i<lines.length; i++ ) + { + out.write( lines[i], 0, lines[i].length() ); + } + out.close(); + } + else + { + //System.out.println( "URLDecoder: " + java.net.URLDecoder.decode( mailcapPath ) ); + } + + + + // use prog dir, if not there then java.io to create/write new file + MailcapCommandMap map = new MailcapCommandMap( mailcapPath ); + CommandMap.setDefaultCommandMap ( map ); + } + catch( IOException ioe ) + { + ioe.printStackTrace(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + } + + + private static String[] getMailcapText() + { + String[] mailcapText = { + "#\n", + "# Default mailcap file for the JavaMail System.\n", + "#\n", + "# JavaMail content-handlers:\n", + "#\n", + "text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain\n", + "text/html;; x-java-content-handler=com.sun.mail.handlers.text_html\n", + "text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml\n", + "image/gif;; x-java-content-handler=com.sun.mail.handlers.image_gif\n", + "image/jpeg;; x-java-content-handler=com.sun.mail.handlers.image_jpeg\n", + "multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed\n", + "message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822\n" + }; + + return mailcapText; + } + + + + private static void writeMimeTypes() + { + String mimetypesPath = getConfigDir() + System.getProperty( "file.separator" ) + "mimetypes.default"; + + try + { + if( ! new File( java.net.URLDecoder.decode( mimetypesPath ) ).exists() ) + { + //System.out.println( "URLDecoder: " + java.net.URLDecoder.decode( mimetypesPath ) ); + File mimetypesFile = new File( mimetypesPath ); + FileWriter out = new FileWriter( mimetypesFile ); + String[] lines = getMimeTypesText(); + for( int i=0; i<lines.length; i++ ) + { + out.write( lines[i], 0, lines[i].length() ); + } + out.close(); + } + else + { + //System.out.println( "URLDecoder: " + java.net.URLDecoder.decode( mimetypesPath ) ); + } + + MimetypesFileTypeMap mimeTypes = new MimetypesFileTypeMap( mimetypesPath ); + FileTypeMap.setDefaultFileTypeMap( mimeTypes ); + } + catch( IOException ioe ) + { + ioe.printStackTrace(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + } + + + private static String[] getMimeTypesText() + { + String[] mimesText = { + "#\n", + "# A simple, old format, mime.types file\n", + "#\n", + "text/html html htm HTML HTM\n", + "text/plain txt text TXT TEXT\n", + "image/gif gif GIF\n", + "image/ief ief\n", + "image/jpeg jpeg jpg jpe JPG\n", + "image/tiff tiff tif\n", + "image/x-xwindowdump xwd\n", + "application/postscript ai eps ps\n", + "application/rtf rtf\n", + "application/x-tex tex\n", + "application/x-texinfo texinfo texi\n", + "application/x-troff t tr roff\n", + "audio/basic au\n", + "audio/midi midi mid\n", + "audio/x-aifc aifc\n", + "audio/x-aiff aif aiff\n", + "audio/x-mpeg mpeg mpg\n", + "audio/x-wav wav\n", + "video/mpeg mpeg mpg mpe\n", + "video/quicktime qt mov\n", + "video/x-msvideo avi\n" + }; + + return mimesText; + } + + + private static String getConfigDir() + { + // mailcap file must be written to the Office user/config directory + + // instPath is a URL, needs to be converted to a system pathname + String config = instPath + "/user/config"; + String configNonURL = ""; + + if( System.getProperty( "os.name" ).indexOf( "Windows" ) != -1 ) + { + // Windows + // removes "file:///" + int start = 8; + configNonURL = config.substring( start, config.length() ); + // Convert forward to back-slashes + while( configNonURL.indexOf( "/" ) != -1 ) + { + int fSlash = configNonURL.indexOf( "/" ); + String firstPart = configNonURL.substring( 0, fSlash ); + String secondPart = configNonURL.substring( fSlash + 1, configNonURL.length() ); + configNonURL = firstPart + "\\" + secondPart; + } + } + else + { + // Unix/Linux + // removes "file://" + int start = 7; + configNonURL = config.substring( start, config.length() ); + } + + return configNonURL; + } + +} diff --git a/scripting/examples/java/Newsgroup/NewsGroup.java b/scripting/examples/java/Newsgroup/NewsGroup.java new file mode 100644 index 000000000000..714b81ec86ce --- /dev/null +++ b/scripting/examples/java/Newsgroup/NewsGroup.java @@ -0,0 +1,23 @@ +public class NewsGroup +{ + + private String hostname = ""; + private String newsgroupName = ""; + + public NewsGroup( String host, String group ) + { + hostname = host; + newsgroupName = group; + } + + public String getHostName() + { + return hostname; + } + + public String getNewsgroupName() + { + return newsgroupName; + } + +} diff --git a/scripting/examples/java/Newsgroup/OfficeAttachment.java b/scripting/examples/java/Newsgroup/OfficeAttachment.java new file mode 100644 index 000000000000..6097fa2667d1 --- /dev/null +++ b/scripting/examples/java/Newsgroup/OfficeAttachment.java @@ -0,0 +1,307 @@ +//import com.sun.star.frame.XComponentLoader; +import java.io.*; +import com.sun.star.lang.XComponent; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.frame.XStorable; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.frame.XModel; +import drafts.com.sun.star.script.framework.XScriptContext; + +// for debug only +import javax.swing.JOptionPane; + +public class OfficeAttachment +{ + + private StatusWindow status = null; + private XStorable storedDoc = null; + private File htmlFile = null; + private File officeFile = null; + private boolean isHtmlDoc = false; + private boolean isOfficeDoc = false; + private String templocationURL = ""; + private String templocationSystem = ""; + private String attachmentName = ""; + private String statusLine = ""; + + public OfficeAttachment( XScriptContext xsc, StatusWindow sw, boolean html, boolean office ) + { + status = sw; + isHtmlDoc = html; + isOfficeDoc = office; + + templocationSystem = templocationURL = System.getProperty( "user.home" ); + if( System.getProperty( "os.name" ).indexOf( "Windows" ) != -1 ) + { + while( templocationURL.indexOf( "\\" ) != -1 ) + { + int sepPos = templocationURL.indexOf( "\\" ); + String firstPart = templocationURL.substring( 0, sepPos ); + String lastPart = templocationURL.substring( sepPos + 1, templocationURL.length() ); + templocationURL = firstPart + "/" + lastPart; + //JOptionPane.showMessageDialog( null, "Temp Location URL is: " + templocationURL + "\nfirstPart is: " + firstPart + "\nlastPart is: " + lastPart ); + } + } + + try + { + statusLine = "Querying Office for current document"; + status.setStatus( 1, statusLine ); + XScriptContext scriptcontext = xsc; + XModel xmodel = scriptcontext.getDocument(); + storedDoc = (XStorable) UnoRuntime.queryInterface(XStorable.class, xmodel); + // find document name from storedDoc + attachmentName = storedDoc.getLocation(); + } + catch( Exception e ) + { + //UNO error + status.setStatus( 1, "Error: " + statusLine ); + } + + if( attachmentName.equalsIgnoreCase( "" ) ) + { + attachmentName = "Attachment"; + } + else + { + //int lastSep = attachmentName.lastIndexOf( System.getProperty( "file.separator" ) ); + int lastSep = attachmentName.lastIndexOf( "/" ); + attachmentName = attachmentName.substring( lastSep + 1, attachmentName.length() ); + int dot = attachmentName.indexOf( "." ); + attachmentName = attachmentName.substring( 0, dot ); + } + } + + + public boolean createTempDocs() + { + String filenameURL = "file:///" + templocationURL + "/" + attachmentName; + //String filenameSystem = templocationSystem + System.getProperty( "file.separator" ) + attachmentName; + //JOptionPane.showMessageDialog( null, "Filename URL " + filenameURL ); + try + { + if( isHtmlDoc ) + { + //JOptionPane.showMessageDialog( null, "Saving doc in HTML format" ); + statusLine = "Saving doc in HTML format"; + status.setStatus( 4, statusLine ); + //System.out.print( "Saving attachment as " + filename + ".html..." ); + PropertyValue[] propertyvalue_html = new PropertyValue[2]; + propertyvalue_html[0] = new PropertyValue(); + propertyvalue_html[0].Name = new String("Overwrite"); + propertyvalue_html[0].Value = new Boolean(true); + propertyvalue_html[1] = new PropertyValue(); + propertyvalue_html[1].Name = ("FilterName"); +// propertyvalue_html[1].Value = new String("scalc: HTML (StarCalc)"); + propertyvalue_html[1].Value = new String("swriter: HTML (StarWriter)"); + storedDoc.storeAsURL( filenameURL + ".html", propertyvalue_html); + + File homedir = new File( templocationSystem ); + //JOptionPane.showMessageDialog( null, "homedir (Java File): " + homedir.getPath() ); + File homefiles[] = homedir.listFiles(); + String file = ""; + for(int i=0; i < homefiles.length; i++ ) + { + if( homefiles[i].getName().equals( attachmentName + ".html" ) ) + { + //htmlFile = new File( homefiles[i].getAbsolutePath() ); + //JOptionPane.showMessageDialog( null, "Found HTML" ); + file = homefiles[i].getAbsolutePath(); + } + } + htmlFile = new File( file ); + //htmlFile = new File( filename + ".html" ); + //htmlFile = new File( storedDoc.getLocation() ); + } + + if( isOfficeDoc ) + { + //JOptionPane.showMessageDialog( null, "Saving doc in .sxw format" ); + statusLine = "Saving doc in .sxw format"; + status.setStatus( 4, statusLine ); + //System.out.print( "Saving attachment as " + filename + ".sxw..." ); + PropertyValue[] propertyvalue_sxw = new PropertyValue[2]; + propertyvalue_sxw[0] = new PropertyValue(); + propertyvalue_sxw[0].Name = new String("Overwrite"); + propertyvalue_sxw[0].Value = new Boolean(true); + propertyvalue_sxw[1] = new PropertyValue(); + propertyvalue_sxw[1].Name = new String("Overwrite"); + propertyvalue_sxw[1].Value = new Boolean(true); + storedDoc.storeAsURL( filenameURL + ".sxw", propertyvalue_sxw); + + File homedir = new File( templocationSystem ); + + //JOptionPane.showMessageDialog( null, "homedir (Java File): " + homedir.getPath() ); + + File homefiles[] = homedir.listFiles(); + String file = ""; + for(int i=0; i < homefiles.length; i++ ) + { + if( homefiles[i].getName().equals( attachmentName + ".sxw" ) ) + { + //officeFile = new File( homefiles[i].getAbsolutePath() ); + //JOptionPane.showMessageDialog( null, "Found .sxw" ); + file = homefiles[i].getAbsolutePath(); + } + } + officeFile = new File( file ); + //officeFile = new File( filename + ".sxw" ); + //officeFile = new File (storedDoc.getLocation() ); + } + + //status.setStatus( 10, "Attachments successfully created" ); + + } + catch( SecurityException se ) + { + status.setStatus( 4, "Error: " + statusLine ); + System.out.println( "Security error while saving temporary Document(s). Check file permissions in home directory." ); + se.printStackTrace(); + htmlFile = null; + officeFile = null; + return false; + } + catch( Exception e ) + { + status.setStatus( 4, "Error: " + statusLine ); + System.out.println( "Error saving temporary Document(s)" ); + e.printStackTrace(); + htmlFile = null; + officeFile = null; + return false; + } + return true; + } + + + public boolean removeTempDocs() + { + /* + if( !htmlFile.exists() && !officeFile.exists() ) + { + System.out.println("Error: Document(s) have not been saved." ); + } + */ + + statusLine = "Removing temp docs"; + status.setStatus( 13, statusLine ); + + try + { + if( isOfficeDoc && isHtmlDoc ) + { + //System.out.println( "Removing: " + htmlFile.getPath() + " " + officeFile.getPath() ); + //System.out.println( "htmlfile " + htmlFile.exists() + " officeFile " + officeFile.exists() ); + //JOptionPane.showMessageDialog( null, "Removing: " + htmlFile.getPath() + " " + officeFile.getPath() ); + //JOptionPane.showMessageDialog( null, "htmlfile " + htmlFile.exists() + " officeFile " + officeFile.exists() ); + htmlFile.delete(); + officeFile.delete(); + //JOptionPane.showMessageDialog( null, "htmlfile " + htmlFile.exists() + " officeFile " + officeFile.exists() ); + } + else + { + if( isOfficeDoc ) + { + //System.out.println( "Removing: " + officeFile.getPath() ); + officeFile.delete(); + } + else + { + //System.out.println( "Removing: " + htmlFile.getPath() ); + htmlFile.delete(); + } + } + } + catch( SecurityException se ) + { + status.setStatus( 13, "Error: " + statusLine ); + System.out.println( "Security Error while deleting temporary Document(s). Check file permissions in home directory." ); + se.printStackTrace(); + return false; + } + return true; + } + + + public void cleanUpOnError() + { + try + { + if( isOfficeDoc && isHtmlDoc ) + { + htmlFile.delete(); + officeFile.delete(); + } + else + { + if( isOfficeDoc ) + { + officeFile.delete(); + } + else + { + htmlFile.delete(); + } + } + } + catch( SecurityException se ) + { + System.out.println( "Security Error while deleting temporary Document(s). Check file permissions in home directory." ); + se.printStackTrace(); + } + } + + + public File[] getAttachments() + { + /* + if( htmlFile == null && officeFile == null ) + { + System.out.println( "Error: Document(s) have not been saved." ); + return null; + } + */ + //(officeDoc) ? (number = 2) : (number = 1); + + statusLine = "Retrieving temp docs"; + status.setStatus( 8, statusLine ); + + File attachments[] = null; + if( isOfficeDoc && isHtmlDoc ) + { + attachments = new File[2]; + attachments[0] = htmlFile; + attachments[1] = officeFile; + } + else + { + if( isOfficeDoc ) + { + attachments = new File[1]; + attachments[0] = officeFile; + } + else + { + attachments = new File[1]; + attachments[0] = htmlFile; + } + } + + return attachments; + } + + + public boolean isHtmlAttachment() + { + return isHtmlDoc; + } + + + public boolean isOfficeAttachment() + { + return isOfficeDoc; + } + +} diff --git a/scripting/examples/java/Newsgroup/PostNewsgroup.java b/scripting/examples/java/Newsgroup/PostNewsgroup.java new file mode 100644 index 000000000000..f8ad17268ce2 --- /dev/null +++ b/scripting/examples/java/Newsgroup/PostNewsgroup.java @@ -0,0 +1,625 @@ +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.border.*; +import java.util.Vector; +import drafts.com.sun.star.script.framework.XScriptContext; + + +public class PostNewsgroup extends JFrame +{ + + // Post to newsgroup objects + private NewsGroup[] subscribedNewsgroups = null; + private XScriptContext xscriptcontext = null; + + private final int FRAMEX = 300; + private final int FRAMEY = 300; + private final int TEXTBOXWIDTH = 300; + private final int TEXTBOXHEIGHT = 24; + private final int TEXTAREAHEIGHT = 70; + private final int BUTTONWIDTH = 80; + private final int BUTTONHEIGHT = 30; + + private PostNewsgroup window = null; + private JComboBox newsgroupComboBox = null; + private JTextField hostTextField = null; + private JTextField replyTextField = null; + private JTextField subjectTextField = null; + private JTextArea commentTextArea = null; + private JRadioButton officeHtmlButton = null; + private JRadioButton officeButton = null; + private JRadioButton htmlButton = null; + private JButton postButton = null; + private JButton cancelButton = null; + + // JFrame for launch progress dialog + private StatusWindow statusWindow = null; + private String statusLine = ""; + + // Tool tip text + private final String newsgroupText = "Newsgroup name"; + private final String hostText = "Newsgroup host/server name"; + private final String replyText = "Email address to reply to"; + private final String subjectText = "Subject title for the mail"; + private final String commentText = "Additional comment on mail"; + private final String officeHtmlText = "Post as both Office and HTML attachments"; + private final String officeText = "Post as Office attachment only"; + private final String htmlText = "Post as HTML attachment only"; + private final String postText = "Post to newsgroup"; + private final String cancelText = "Cancel post to newsgroup"; + + + public void post( XScriptContext xsc ) + { + xscriptcontext = xsc; + window = this; + + // create mailcap and mimetypes files (fix for classloader problem) + MimeConfiguration.createFiles( xscriptcontext ); + + this.setTitle( "Post Document To Newsgroup" ); + this.setLocation( FRAMEX, FRAMEY ); + + this.addFocusListener( new FocusAdapter() + { + public void focusGained( FocusEvent event ) + { + System.out.println( "Focus gained" ); + window.update( window.getGraphics() ); + } + + public void focusLost( FocusEvent event ) + { + System.out.println( "Focus lost" ); + } + }); + + Container container = getContentPane(); + container.setLayout( new GridBagLayout() );; + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + + JPanel labelPanel = constructLabelPanel(); + JPanel textPanel = constructTextPanel(); + JPanel optionPanel = constructOptionPanel(); + JPanel buttonPanel = constructButtonPanel(); + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 3; + constraints.insets = new Insets( 15, 15, 5, 5 ); + container.add( labelPanel, constraints ); + + constraints.gridx = 1; + constraints.gridy = 0; + constraints.gridwidth = 4; + constraints.gridheight = 3; + constraints.insets = new Insets( 15, 5, 5, 15 ); + container.add( textPanel, constraints ); + + constraints.gridx = 0; + constraints.gridy = 3; + constraints.gridwidth = 5; + constraints.gridheight = 1; + constraints.insets = new Insets( 5, 15, 5, 15 ); + container.add( optionPanel, constraints ); + + constraints.gridx = 0; + constraints.gridy = 4; + constraints.gridwidth = 5; + constraints.gridheight = 1; + constraints.insets = new Insets( 5, 5, 5, 5 ); + container.add( buttonPanel, constraints ); + + this.pack(); + this.setResizable( false ); + this.setVisible( true ); + } + + + private JPanel constructLabelPanel() + { + JLabel newsgroupLabel = new JLabel( "Newsgroup:" ); + JLabel hostLabel = new JLabel( "Host:" ); + JLabel replyLabel = new JLabel( "Reply:" ); + JLabel subjectLabel = new JLabel( "Subject:" ); + JLabel commentLabel = new JLabel( "Comment:" ); + + newsgroupLabel.setToolTipText( newsgroupText ); + hostLabel.setToolTipText( hostText ); + replyLabel.setToolTipText( replyText ); + subjectLabel.setToolTipText( subjectText ); + commentLabel.setToolTipText( commentText ); + + JPanel newsgroupPanel = new JPanel(); + newsgroupPanel.setLayout( new BorderLayout() ); + newsgroupPanel.add( newsgroupLabel, "West" ); + JPanel hostPanel = new JPanel(); + hostPanel.setLayout( new BorderLayout() ); + hostPanel.add( hostLabel, "West" ); + JPanel replyPanel = new JPanel(); + replyPanel.setLayout( new BorderLayout() ); + replyPanel.add( replyLabel, "West" ); + JPanel subjectPanel = new JPanel(); + subjectPanel.setLayout( new BorderLayout() ); + subjectPanel.add( subjectLabel, "West" ); + JPanel commentPanel = new JPanel(); + commentPanel.setLayout( new BorderLayout() ); + commentPanel.add( commentLabel, "West" ); + JPanel emptyPanel = new JPanel(); + + final int labelWidth = 80; + newsgroupPanel.setPreferredSize( new Dimension( labelWidth, TEXTBOXHEIGHT ) ); + hostPanel.setPreferredSize( new Dimension( labelWidth, TEXTBOXHEIGHT ) ); + replyPanel.setPreferredSize( new Dimension( labelWidth, TEXTBOXHEIGHT ) ); + subjectPanel.setPreferredSize( new Dimension( labelWidth, TEXTBOXHEIGHT ) ); + commentPanel.setPreferredSize( new Dimension( labelWidth, TEXTBOXHEIGHT ) ); + + JPanel panel = new JPanel(); + panel.setLayout( new GridBagLayout() ); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + constraints.insets = new Insets( 5, 5, 5, 5 ); + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.weightx = constraints.weighty = 0.0; + panel.add( newsgroupPanel, constraints ); + + constraints.gridx = 0; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add( hostPanel, constraints ); + + constraints.gridx = 0; + constraints.gridy = 2; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add( replyPanel, constraints ); + + constraints.gridx = 0; + constraints.gridy = 3; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add( subjectPanel, constraints ); + + constraints.gridx = 0; + constraints.gridy = 4; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add( commentPanel, constraints ); + + constraints.gridx = 0; + constraints.gridy = 5; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.weightx = constraints.weighty = 1.0; + panel.add( emptyPanel, constraints ); + + return panel; + } + + + private JPanel constructTextPanel() + { + hostTextField = new JTextField(); + hostTextField.setPreferredSize( new Dimension( TEXTBOXWIDTH, TEXTBOXHEIGHT ) ); + hostTextField.setToolTipText( hostText ); + hostTextField.setBorder( new EtchedBorder() ); + + //optionPanel.setBorder( new TitledBorder( new EtchedBorder(), "Document Format" ) ); + newsgroupComboBox = getNewsgroupCombo(); + + replyTextField = new JTextField(); + replyTextField.setPreferredSize( new Dimension( TEXTBOXWIDTH, TEXTBOXHEIGHT ) ); + replyTextField.setToolTipText( replyText ); + replyTextField.setBorder( new EtchedBorder() ); + + subjectTextField = new JTextField(); + subjectTextField.setPreferredSize( new Dimension( TEXTBOXWIDTH, TEXTBOXHEIGHT ) ); + subjectTextField.setToolTipText( subjectText ); + subjectTextField.setBorder( new EtchedBorder() ); + + commentTextArea = new JTextArea(); + commentTextArea.setPreferredSize( new Dimension( TEXTBOXWIDTH, TEXTAREAHEIGHT ) ); + commentTextArea.setToolTipText( commentText ); + commentTextArea.setBorder( new EtchedBorder() ); + + JPanel panel = new JPanel(); + panel.setLayout( new GridBagLayout() ); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + constraints.insets = new Insets( 5, 5, 5, 5 ); + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add( newsgroupComboBox, constraints ); + + constraints.gridx = 0; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add( hostTextField, constraints ); + + constraints.gridx = 0; + constraints.gridy = 2; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add( replyTextField, constraints ); + + constraints.gridx = 0; + constraints.gridy = 3; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add( subjectTextField, constraints ); + + constraints.gridx = 0; + constraints.gridy = 4; + constraints.gridwidth = 1; + constraints.gridheight = 2; + panel.add( commentTextArea, constraints ); + + return panel; + } + + + private JComboBox getNewsgroupCombo() + { + newsgroupComboBox = new JComboBox(); + //newsgroupComboBox.setBorder( new EtchedBorder() ); + + newsgroupComboBox.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + // when newsgroup is selected + if( subscribedNewsgroups != null ) + { + int position = newsgroupComboBox.getSelectedIndex(); + if( position != -1 ) + { + hostTextField.setText( subscribedNewsgroups[ position ].getHostName() ); + newsgroupComboBox.setToolTipText( "Newsgroup name: " + subscribedNewsgroups[ position ].getNewsgroupName() + " (Host name: " + subscribedNewsgroups[ position ].getHostName() + ")" ); + } + } + } + }); + + NewsGroup groupToSend = null; + SubscribedNewsgroups newsgroups = new SubscribedNewsgroups(); + subscribedNewsgroups = newsgroups.getNewsGroups(); + + // Test for no .mozilla or no subscribed newsgroups + // subscribedNewsgroups = null; + + if( subscribedNewsgroups == null ) + { + //System.out.println( "Couldn't find any subscibed newsgroups in .mozilla" ); + JOptionPane.showMessageDialog( window, "No subscribed newsgroups found in mozilla/netscape profile \nPlease enter newsgroup and host name", + "Newsgroups Information", JOptionPane.INFORMATION_MESSAGE ); + } + else + { + // Copy all newsgroups into a vector for comparison + // Alter entries (to include host name) if duplication is found + Vector vector = new Vector( subscribedNewsgroups.length ); + for(int i=0; i < subscribedNewsgroups.length; i++ ) + { + vector.add( subscribedNewsgroups[i].getNewsgroupName() ); + } + // Compare and alter + for(int i=0; i < subscribedNewsgroups.length; i++ ) + { + // check if combo box already has a newsgroup with same name + // then add host name to differentiate + for(int j=0; j < subscribedNewsgroups.length; j++ ) + { + if( j != i && subscribedNewsgroups[j].getNewsgroupName().equalsIgnoreCase( subscribedNewsgroups[i].getNewsgroupName() ) ) + { + vector.set( j, subscribedNewsgroups[j].getNewsgroupName() + " (" + subscribedNewsgroups[j].getHostName() + ")" ); + vector.set( i, subscribedNewsgroups[i].getNewsgroupName() + " (" + subscribedNewsgroups[i].getHostName() + ")" ); + } + } + } + // Copy converted newsgroups from vector to combo box + for(int i=0; i < subscribedNewsgroups.length; i++ ) + { + newsgroupComboBox.addItem( vector.elementAt(i) ); + } + }// else + + newsgroupComboBox.setPreferredSize( new Dimension( TEXTBOXWIDTH, TEXTBOXHEIGHT ) ); + newsgroupComboBox.setEditable( true ); + + return newsgroupComboBox; + } + + + + private JPanel constructOptionPanel() + { + officeHtmlButton = new JRadioButton( "Office and HTML", true ); + officeHtmlButton.setToolTipText( officeHtmlText ); + + officeButton = new JRadioButton( "Office" ); + officeButton.setToolTipText( officeText ); + + htmlButton = new JRadioButton( "HTML" ); + htmlButton.setToolTipText( htmlText ); + + JRadioButton[] rbuttons = { officeHtmlButton, officeButton, htmlButton }; + ButtonGroup radioButtonGroup = new ButtonGroup(); + for( int i=0; i < rbuttons.length; i++ ) + { + radioButtonGroup.add( rbuttons[i] ); + } + + JPanel optionPanel = new JPanel(); + //optionPanel.setLayout( new GridLayout( 1, 3, 20, 0 ) ); + optionPanel.setBorder( new TitledBorder( new EtchedBorder(), "Document Format" ) ); + optionPanel.setLayout( new GridBagLayout() ); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets( 5, 5, 5, 30 ); + optionPanel.add( officeHtmlButton, constraints ); + + constraints.gridx = 1; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets( 5, 20, 5, 30 ); + optionPanel.add( officeButton, constraints ); + + constraints.gridx = 2; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets( 5, 20, 5, 5 ); + optionPanel.add( htmlButton, constraints ); + + return optionPanel; + } + + + + public boolean sendingActions() + { + // posting actions + // Validate the data + if( isValidData() ) + { + // Create status window + StatusWindow statusWindow = new StatusWindow( window, "Posting to Newsgroup", FRAMEX, FRAMEY ); + + statusWindow.setVisible( true ); + //statusWindow.requestFocusInWindow(); + statusLine = "Ready to send..."; + statusWindow.setStatus( 0, statusLine ); + + // Get the boolean values for HTML/Office document + // params: ( XScriptContext, StatusWindow, html document, office document ) + + boolean html = false; + boolean office = false; + if( officeHtmlButton.isSelected() ) { html = true; office = true; } + if( officeButton.isSelected() ) { office = true; html = false; } + if( htmlButton.isSelected() ) { html = true; office = false; } + + OfficeAttachment officeAttach = new OfficeAttachment( xscriptcontext, statusWindow, html, office ); + + statusLine = "Getting user input"; + statusWindow.setStatus( 2, statusLine ); + // Get replyto, subject, comment from textboxes + String replyto = replyTextField.getText(); + String subject = subjectTextField.getText(); + String comment = commentTextArea.getText(); + + // Get newsgroup from combo box (corresponding position) + String host = ""; + String group = ""; + int position = newsgroupComboBox.getSelectedIndex(); + if( subscribedNewsgroups == null || position == -1 ) + { + host = hostTextField.getText(); + group = newsgroupComboBox.getSelectedItem().toString(); + } + else + { + //int position = newsgroupComboBox.getSelectedIndex(); + host = subscribedNewsgroups[ position ].getHostName(); + group = subscribedNewsgroups[ position ].getNewsgroupName(); + } + + statusLine = "Creating sender object"; + statusWindow.setStatus( 3, statusLine ); + Sender sender = new Sender( statusWindow, officeAttach, replyto, subject, comment, host, group ); + if( !sender.sendMail() ) + { + //System.out.println( "Should end here (?)" ); + statusWindow.enableCancelButton( true ); + officeAttach.cleanUpOnError(); + return false; + } + + statusLine = "Send is complete"; + statusWindow.setStatus( 14, statusLine ); + } + else + { + //System.out.println( "Non valid data" ); + return false; + } + return true; + } + + + private JPanel constructButtonPanel() + { + Action postAction = new AbstractAction() { + public void actionPerformed( ActionEvent event ) { + // posting actions + sendingActions(); + }// actionPerformed + }; + + Action cancelAction = new AbstractAction() { + public void actionPerformed( ActionEvent event ) { + // cancelling actions + window.dispose(); + } + }; + + postButton = new JButton(); + postButton.setAction( postAction ); + postButton.setToolTipText( postText ); + postButton.setText( "Post" ); + postButton.setPreferredSize( new Dimension( BUTTONWIDTH + 20, BUTTONHEIGHT ) ); + + cancelButton = new JButton(); + cancelButton.setAction( cancelAction ); + cancelButton.setToolTipText( cancelText ); + cancelButton.setText( "Cancel" ); + cancelButton.setPreferredSize( new Dimension( BUTTONWIDTH + 20, BUTTONHEIGHT ) ); + + JSeparator sep = new JSeparator( SwingConstants.HORIZONTAL ); + + JPanel buttonPanel = new JPanel(); + buttonPanel.setLayout( new GridBagLayout() ); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + constraints.insets = new Insets( 5, 5, 5, 5 ); + + JPanel emptyPanel1 = new JPanel(); + emptyPanel1.setPreferredSize( new Dimension( BUTTONWIDTH, BUTTONHEIGHT ) ); + + JPanel emptyPanel2 = new JPanel(); + emptyPanel2.setPreferredSize( new Dimension( BUTTONWIDTH, BUTTONHEIGHT ) ); + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 4; + constraints.gridheight = 1; + buttonPanel.add( sep, constraints ); + + constraints.gridx = 0; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + buttonPanel.add( emptyPanel1, constraints ); + + constraints.gridx = 1; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + buttonPanel.add( emptyPanel2, constraints ); + + constraints.gridx = 2; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + buttonPanel.add( postButton, constraints ); + + constraints.gridx = 3; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets( 5, 5, 5, 0 ); + buttonPanel.add( cancelButton, constraints ); + + return buttonPanel; + } + + + public void enableButtons( boolean enable ) + { + if( enable ) + { + postButton.setEnabled( true ); + cancelButton.setEnabled( true ); + } + else + { + postButton.setEnabled( false ); + cancelButton.setEnabled( false ); + } + } + + + private boolean isValidData() + { + // newsgroupComboBox must not be blank (format? dots and whitespace) + String newsgroupString = ""; + int position = newsgroupComboBox.getSelectedIndex(); + if( subscribedNewsgroups == null || position == -1 ) + { + newsgroupString = newsgroupComboBox.getSelectedItem().toString(); + } + else + { + //int position = newsgroupComboBox.getSelectedIndex(); + newsgroupString = subscribedNewsgroups[ position ].getNewsgroupName(); + } + if( newsgroupString.length() == 0 ) + { + //System.out.println( "Please enter a newsgroup name" ); + newsgroupComboBox.requestFocus(); + JOptionPane.showMessageDialog( window, "Please enter a newsgroup name", "Input Error", JOptionPane.ERROR_MESSAGE ); + return false; + } + + + // hostTextField must not be blank (format?) + String hostString = hostTextField.getText(); + if( hostString.length() == 0 ) + { + //System.out.println( "Please enter a hostname" ); + hostTextField.requestFocus(); + JOptionPane.showMessageDialog( window, "Please enter a hostname", "Input Error", JOptionPane.ERROR_MESSAGE ); + return false; + } + + + // replyTextField must have <string>@<string>.<string> + // (string at least 2 chars long) + // consider <s>.<s>@<s>.<s>.<s> format? (array of dot positons?) + String replyString = replyTextField.getText(); + int atPos = replyString.indexOf( "@" ); + int dotPos = replyString.lastIndexOf( "." ); + int length = replyString.length(); + //System.out.println( "length: " + length + "\n atPos: " + atPos + "\n dotPos: " + dotPos ); + if( length == 0 || atPos == -1 || dotPos == -1 || atPos < 2 || dotPos < atPos || dotPos + 2 == length || atPos + 2 == dotPos || atPos != replyString.lastIndexOf( "@" ) || replyString.indexOf(" ") != -1 ) + { + //System.out.println( "Please enter a valid reply to email address" ); + replyTextField.requestFocus(); + 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 ) + { + //System.out.println( "Please enter subject title" ); + subjectTextField.requestFocus(); + JOptionPane.showMessageDialog( window, "Please enter subject title", "Input Error", JOptionPane.ERROR_MESSAGE ); + return false; + } + + // details are valid + return true; + } + +} diff --git a/scripting/examples/java/Newsgroup/Sender.java b/scripting/examples/java/Newsgroup/Sender.java new file mode 100644 index 000000000000..eb1da2868f0d --- /dev/null +++ b/scripting/examples/java/Newsgroup/Sender.java @@ -0,0 +1,126 @@ +import javax.mail.*; +import javax.mail.internet.*; +import com.msoft.mail.provider.nntp.NNTPTransport; +import java.util.Properties; +import java.io.*; +import javax.activation.*; + + +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 statusLine = ""; + + + + 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; + } + + + + public boolean sendMail() + { + int statusPos = 5; + 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 ); + + // 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 ); + + // Buildup bodypart with text and attachments + Multipart multipart = new MimeMultipart(); + + BodyPart messageBodyPart = new MimeBodyPart(); + messageBodyPart.setText( comment ); + multipart.addBodyPart( messageBodyPart ); + + statusPos++; // 7 + statusLine = "Adding attachment(s)"; + status.setStatus( statusPos, statusLine ); + File attachs[] = attachments.getAttachments(); + for(int i=0; i < attachs.length; i++ ) + { + //System.out.println( "Adding file: " + attachs[i].getName() ); + messageBodyPart = new MimeBodyPart(); + 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 ); + + // 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 )); + + // Null parameters are for user name and password + statusPos++; // 10 + statusLine = "Connecting to mail server"; + status.setStatus( statusPos, statusLine ); + transport.connect( hostname, null, null ); + + statusPos++; // 11 + statusLine = "Sending message"; + status.setStatus( statusPos, statusLine ); + transport.sendMessage( message, message.getAllRecipients() ); + + statusPos++; // 12 + statusLine = "Closing transport"; + status.setStatus( statusPos, statusLine ); + transport.close(); + + // Clean up when finished + attachments.removeTempDocs(); + + return true; + } + catch( MessagingException me ) + { + if( statusPos == 10 ) + { + statusLine = "Error connecting (User authentication?)"; + } + 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 new file mode 100644 index 000000000000..184b33ac5d55 --- /dev/null +++ b/scripting/examples/java/Newsgroup/StatusWindow.java @@ -0,0 +1,137 @@ +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.border.*; + +public class StatusWindow extends JFrame +{ + + private JProgressBar progressBar = null; + private JTextField statusLabel = null; + private JButton cancelButton = null; + private JFrame statusWindow = null; + private PostNewsgroup mainWindow = null; + + private final int MAXPROGRESS = 13; + private final int MINPROGRESS = 0; + + + 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 ); + + 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 ); + + JLabel progLabel = new JLabel( "Progress:" ); + + JPanel progressPanel = new JPanel(); + 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.setBorder( LineBorder.createGrayLineBorder() ); + JPanel statusPanel = new JPanel(); + //statusPanel.setBorder( LineBorder.createBlackLineBorder() ); + 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" ); + + Container container = getContentPane(); + container.setLayout( new GridBagLayout() ); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + 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.gridx = 0; + constraints.gridy = 2; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets( 10, 15, 5, 15 ); + container.add( buttonPanel, constraints ); + + this.pack(); + this.setResizable( false ); + //this.setVisible( true ); + + } + + + 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() ); + } + + + public void enableCancelButton( boolean enable ) + { + if( enable ) + { + cancelButton.setEnabled( true ); + cancelButton.setText( "Close" ); + } + else + { + cancelButton.setEnabled( false ); + cancelButton.setText( "Cancel" ); + } + + } + +} diff --git a/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java b/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java new file mode 100644 index 000000000000..0d78f98c2b9a --- /dev/null +++ b/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java @@ -0,0 +1,343 @@ +import java.io.*; +import java.util.Vector; + + +public class SubscribedNewsgroups { + + + private static NewsGroup[] allSubscribed = null; + private static boolean windows = false; + + public static void main( String[] args ) { + // Test the class + SubscribedNewsgroups subscribed = new SubscribedNewsgroups(); + + NewsGroup allGroups[] = subscribed.getNewsGroups(); + + 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() ); + } + } + } + + + + // Only public method of the class + // Returns and array of unique NewsGroup objects + public NewsGroup[] getNewsGroups() + { + windows = false; + 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"; + System.out.println( "Windows mozilla path: " + mozillaHome ); + } + else + { + mozillaHome = System.getProperty( "user.home" ) + System.getProperty( "file.separator" ) + ".mozilla"; + System.out.println( "Unix/Linux mozilla path: " + mozillaHome ); + } + if( !new File( mozillaHome ).isDirectory() ) + { + System.out.println("Could not find .mozilla directory"); + return null; + } + System.out.println(".mozilla directory found"); + + // Get all the profiles belonging to the user + File profiles[] = findProfiles( new File ( mozillaHome ) ); + if( profiles.length < 1 ) + { + System.out.println("Could not find Profiles"); + return null; + } + System.out.println("Profiles found"); + + // 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] ); + allNewsDirs[i] = newsDir; + //System.out.println( "News is at: " + newsDir.getPath() ); + } + // Check that at least one News directory exists and remove nulls + boolean newsFound = false; + //Vector nonNullNews = new Vector(); + for( int i=0; i < allNewsDirs.length; i++ ) { + if( allNewsDirs[i] != null ) { + newsFound = true; + break; + } + } + if( !newsFound ) + { + System.out.println("Could not find News directory"); + return null; + } + System.out.println("News directory found"); + + // Get all the mailrc files for each News directory + File allMailrcs[] = findMailrcFiles( allNewsDirs ); + if( allMailrcs == null ) + { + System.out.println("Could not find mailrc files"); + return null; + } + System.out.println("mailrc files found"); + + Vector subscribed = new Vector(); + // Get the newsgroups in each mailrc file + for( int i=0; i < allMailrcs.length; i++ ) + { + File mailrc = (File) allMailrcs[i]; + NewsGroup newsgroup[] = findNewsgroups( mailrc ); + //if the Newsgroup has not already been added to the list + 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] ); + } + } + } + + // Copy all unique Newsgroups into the global array + allSubscribed = new NewsGroup[ subscribed.size() ]; + subscribed.copyInto( allSubscribed ); + // Test that at least one subscribed newsgroup has been found + if( allSubscribed.length < 1 ) + { + System.out.println("Could not find Subscribed newsgroups "); + return null; + } + System.out.println("Subscribed newsgroups found"); + + return allSubscribed; + } + + + + + // Tests if the NewsGroup object has already been listed by another mailrc file + private static boolean listed( NewsGroup newsgroup, Vector uniqueSubscription ) + { + for(int i=0; i < uniqueSubscription.size(); i++) + { + NewsGroup tempGroup = (NewsGroup) uniqueSubscription.elementAt(i); + // Test for duplication + if(newsgroup.getHostName().equalsIgnoreCase( tempGroup.getHostName()) && + newsgroup.getNewsgroupName().equalsIgnoreCase( tempGroup.getNewsgroupName() ) ) + return true; + } + return false; + } + + + + + // Finds all the NewsGroups in an individual mailrc file + private static NewsGroup[] findNewsgroups(File mailrcfile ) + { + + String hostname = ""; + String newsgroup = ""; + NewsGroup mailrcNewsGroups[] = null; + + //Retrieve name of news host/server from file name + //Sequentially access each of the newsgroups + //If the newsgroup is not already contained in the global NewsGroup[] array then add it + + String filename = mailrcfile.getPath(); + 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 + { + // Unix/Linux format "newsrc-staroffice-news.germany.sun.com" + int hostNameStart = filename.indexOf("-") + 1; + 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 ) ); + Vector groups = new Vector(); + String inString = ""; + int line = 0; + while( inString != null ) + { + in.setLineNumber( line ); + inString = in.readLine(); + line++; + if( inString != null ) + { + int newsgroupEnd = inString.indexOf(":"); + 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 ) { + ioe.printStackTrace(); + } + + return mailrcNewsGroups; + } + + + // Finds all the mailrc files for all the given News directories + private static File[] findMailrcFiles(File[] newsDirs) + { + Vector allFiles = new Vector(); + + for( int i=0; i < newsDirs.length; i++ ) + { + System.out.println( "Finding mailrc for: " + newsDirs[i] ); + if( newsDirs[i] != null ) + { + File mailrcFiles[] = newsDirs[i].listFiles( new VersionFilter() ); + System.out.println( "Number found: " + mailrcFiles.length ); + for( int j=0; j < mailrcFiles.length; j++ ) + { + System.out.println( "This mailrc was found: " + mailrcFiles[j] ); + allFiles.addElement( mailrcFiles[j] ); + } + } + } + File allMailrcFiles[] = new File[ allFiles.size() ]; + allFiles.copyInto(allMailrcFiles); + + System.out.println( "number of mailrcs in total: " + allMailrcFiles.length ); + + if( allMailrcFiles.length == 0 ) { + System.out.println( "Returning null"); + return null; + } + + System.out.println( "Returning an File array containing mailrcs"); + return allMailrcFiles; + } + + + // Finds all profiles belonging to one user (can be more than one) + 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()) + { + dirs[dirCounter] = allFiles[i]; + dirCounter++; + } + } + + // Add each directory to a user profile array + File[] profileDirs = new File[dirCounter]; + for( int i=0; i < dirCounter; i++ ) + { + profileDirs[i] = dirs[i]; + } + + // return a File array containing the profile dirs + return profileDirs; + } + + + // Recursively searches for the News directory for a given profile directory + 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()); + // If the array is empty then no matches were found + if (files.length == 0) + { + // File array of all the directories in File start + 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) + { + // break the for loop + break; + } + } + } + else + { + mailrcFile = files[0]; + } + + // return a File representing the News dir in a profile + return mailrcFile; + } +} + + + +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 ) + { + if (aFile.getName().compareToIgnoreCase("News") == 0 || + aFile.getName().indexOf(".rc") != -1 ) + { + return true; + } + } + else + { + if (aFile.getName().compareToIgnoreCase("News") == 0 || + aFile.getName().indexOf("newsrc") != -1 ) + { + return true; + } + } + + return false; + } +} |