Counting tokens in a GUI

hey all im a first time poster and a first year IT student so sorry if this is old hat but i need a hand.
Im using a standard Tokenizer...in a GUI .
I have it that the program prints each token (word or whatever) on a seperate line to each other in the output field.........but what i need as well, is to count the amount of tokens in the same output field as well or a different one (dose not bother me).....any ideas would be VERY apprieciated.
This is not an ssignment but just an exercise hand in.
Here is my code so you can see what im on about.
Thanks for your help
Armatige
---------------=================---------------------------
public void buttonClicked( JButton theButton ){
          if( theButton == clickMe ){
          String inputValue = inputField.getText();
          inputField.setText( "" );
          output2Field.append( "--> " +               
inputValue );
     StringTokenizer tokens = new StringTokenizer(inputValue);
     while (tokens.hasMoreTokens())
          outputField.append( "\n" + tokens.nextToken());
     public static void main( String [] args ){
          Example01 tpo = new Example01();
          tpo.setTitle( "Example01" );
          tpo.setSize( 250, 150 );
          tpo.setVisible( true );

Hi...
Not too sure if I understand your post. Surely you can just use the following method of StringTokenizer to get at what you want?
http://java.sun.com/j2se/1.4/docs/api/java/util/StringTokenizer.html#countTokens()
//your code
StringTokenizer tokens = new StringTokenizer (inputValue);
int numTokens = tokens.countTokens ( )
//some more of your code, doing something with numTokens variable (displaying it perhaps)

Similar Messages

  • Count of tokens using group by + SYN operator + Spell Checking + Stemming

    Hi,
    I have a text data on which i have created context index and populated the tokens table using "CTX_DOC.TOKENS" procedure.
    Now i want to find the number of occurences of tokens using count and group by function.
    I am using the foll query on table "INSP_INS_IDX_TOK"
    select token ,count(token)
    from INSP_INS_IDX_TOK
    group by token
    order By 2 desc
    Token count(Token)
    WORK     84
    WORKING     24
    TAKING     14
    TAKE     13
    now i want to use the synonym operator, stemming operator and spelling check to be implemented while finding the count of tokens so that, it would give more insights.
    o/p should be like
    Token count(Token)
    WORK     108
    TAKE     27
    Please suggest me some inputs on the same.
    Thanks in Advance.

    put it in a table, create context index and then query....
    --- As oracle text can be used.
    On the different note, try to create a context index and look at the $I table of that index. You may find something relevant.

  • How to Look at current Token

    When using the tokenizer in Java I see that you can count tokens "countTokens() " , see if a string has more tokens "hasMoreTokens()", etc. But how do you work with the current token?
    For example:
    while ((str = in.readLine()) != null )
         StringTokenizer tokens = new StringTokenizer(str);
         while (tokens.hasMoreTokens())
              System.out.println( tokens.nextToken() + "\n" );
              //tokenStr = tokens.nextToken();
              count++;
              //if (tokenStr.equals("<body>"))
              //     bodycount++;
             }I can count all the tokens in the string but how can I count the tokens "<body>"?
    Any help please
    eddiemjm

    You are almost there. Trywhile ((str = in.readLine()) != null )
         StringTokenizer tokens = new StringTokenizer(str);
         while (tokens.hasMoreTokens())
              tokenStr = tokens.nextToken();
              System.out.println( tokenStr + "\n" );
              count++;
              if (tokenStr.equals("<body>"))
                   bodycount++;
             }Note the change and move of the println() call.

  • TreeCellRendere updating icons

    I have a TreeCellRederer which changes the icons of JTREE when openen/closing items (linked to start/stop applications)
    When an item (application) is open and i switch to another item, the icon does not change (correct because app is still running). When i select an item and close the application, the icon is changed correctly (from closed to open and vise versa).
    When an item (app3) is open and i switch to another application (app2) and then close the app2, my cursus jumps to item 0 (top level) and the icon of the app2 is closed. Then i close app3 (without selecting it first). Now it is goes wrong, the icon is not changed. This is because the line is not rendered.
    I can force closing of the item by jumping to the last item in the list and then to the first item in the list "removeFromActiveApplicationList(String application)" method, but this is a bit of overkill.
    The problem is that the item-row is not rendered when application is closed without the item be-ing active. Any idea how to solve this?
    I will include all coding but icon-iconimages.
    MenuApplication:
    package myMenu;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyVetoException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.StringTokenizer;
    import java.util.logging.Handler;
    import java.util.logging.Logger;
    import javax.swing.ImageIcon;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import testje.testApp;
    import testje.testInternalFrame;
    public class MenuTest extends JFrame implements TreeSelectionListener{
        // System Properties
        public static Logger myLogger = Logger.getLogger(MenuTest.class.getName());
        public Handler myHandler = null;
        private static String appName;
        // Variables
        public ArrayList activeApplicationList;
        private Object[] [] data;
        private ArrayList sflData;
        public String selectedApplication;
        // Swing objects and varialbles
        public JDesktopPane myDeskTop;
        private JPanel jContentPane = null;
        private JSplitPane jSplitPane = null;
        private JTree jTree = null;
        private javax.swing.JMenuBar jJMenuBar = null;
        private javax.swing.JMenu fileMenu = null;
        private javax.swing.JMenuItem exitMenuItem = null;
        private boolean packFrame = false;
        private PropertyChangeEvent currentEvent;
        // Applications
        private testApp myPanelTestje;
        private testInternalFrame myFrameTestje;
         * This is the default constructor
        public MenuTest() {
            super();
            initialize();
            setAppName("Test Menu");
         * Launches this application
        public static void main(String[] args) {
             MenuTest myMenu = new MenuTest();
             myMenu.setVisible(true);
         * This method initializes this
         * @return void
        private void initialize() {
            setContentPane(getJContentPane());
            setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
            setJMenuBar(getJJMenuBar());
            setSize(800, 600);
            setTitle("MyMenu");
            setVisible(true);
            //Validate frames that have preset sizes
            //Pack frames that have useful preferred size info, e.g. from their layout
            if (packFrame) {
              this.pack();
            else {
              this.validate();
            //Center the window
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = this.getSize();
            if (frameSize.height > screenSize.height) {
              frameSize.height = screenSize.height;
            if (frameSize.width > screenSize.width) {
              frameSize.width = screenSize.width;
            setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
         * This method initializes jJMenuBar   
         * @return javax.swing.JMenuBar
        private javax.swing.JMenuBar getJJMenuBar() {
            if (jJMenuBar == null) {
                jJMenuBar = new javax.swing.JMenuBar();
                jJMenuBar.add(getFileMenu());
            return jJMenuBar;
         * This method initializes jMenu   
         * @return javax.swing.JMenu   
        private javax.swing.JMenu getFileMenu() {
            if (fileMenu == null) {
                fileMenu = new javax.swing.JMenu();
                fileMenu.setText("File");
                fileMenu.add(getExitMenuItem());
            return fileMenu;
         * This method initializes jMenuItem   
         * @return javax.swing.JMenuItem   
        private javax.swing.JMenuItem getExitMenuItem() {
            if (exitMenuItem == null) {
                exitMenuItem = new javax.swing.JMenuItem();
                exitMenuItem.setText("Exit");
                exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent e) {   
                        System.exit(0);
            return exitMenuItem;
         * This method initializes jContentPane
         * @return javax.swing.JPanel  
        private JPanel getJContentPane() {
            if (jContentPane == null) {
                jContentPane = new JPanel();
                jContentPane.setLayout(new BorderLayout());
                jContentPane.add(getJSplitPane(), java.awt.BorderLayout.CENTER);
            return jContentPane;
         * This method initializes jSplitPane  
         * @return javax.swing.JSplitPane  
        private JSplitPane getJSplitPane() {
            if (jSplitPane == null) {
                jSplitPane = new JSplitPane();
                jSplitPane.setLeftComponent(getJTree());
                myDeskTop = new JDesktopPane();
                jSplitPane.setRightComponent(myDeskTop);
                jSplitPane.setDividerLocation(150);
            return jSplitPane;
        private JTree getJTree() {
            if (jTree == null) {
                // Create Root
                DefaultMutableTreeNode root = new DefaultMutableTreeNode("Conti7");
                setActiveApplicationList(new ArrayList());
                // Create ApplicationsList
                // Get Applicationlist
                getApplicationList();
                // Process MenuArray to create Menu
                String previousFolder = "";
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode();
                for (int i = 0; i < sflData.size(); i++){
                    myLogger.fine(
                            "Dataline "+i +" =" + data[0] + " | "
    + data[i][1] + " | "
    + data[i][2] + " | "
    + data[i][3] + " | "
    + data[i][4] + " | "
    + data[i][5]);
    if (!(((String)data[i][2]).equals(previousFolder))) {
    if (!(previousFolder.equals(""))){
    root.add(newNode);
    previousFolder = (String)data[i][2];
    newNode = new DefaultMutableTreeNode(previousFolder);
    newNode.add(new DefaultMutableTreeNode(data[i][3]));
    if (!previousFolder.equals("")){
    root.add(newNode);
    // Add Full menu to tree
    jTree = new JTree(root);
    jTree.setCellRenderer(new TreeExRenderer());
    jTree.addTreeSelectionListener(this);
    return jTree;
    public void valueChanged(TreeSelectionEvent event) {
    String selectedApplication = jTree.getLastSelectedPathComponent().toString();
    myLogger.info(
    "Current Item Selection = " + selectedApplication);
    setSelectedApplication(selectedApplication);
    activateApplication(selectedApplication);
    private void activateApplication(String selectedApplication) {
    if (getSelectedApplication().equals("PanelTestje")){
    if (myPanelTestje==null){
    myPanelTestje = new testje.testApp();
    addInternalFrame(myPanelTestje);
    activateInternalFrame(myPanelTestje);
    if (getSelectedApplication().equals("FrameTestje")){
    if (myFrameTestje==null){
    myFrameTestje = new testje.testInternalFrame();
    addInternalFrame(myFrameTestje);
    activateInternalFrame(myFrameTestje);
    public void addInternalFrame(JInternalFrame myFrame) {
    myDeskTop.add(myFrame);
    myFrame.pack();
    myFrame.setClosable(true);
    try {
    myFrame.setMaximum(true);
    } catch (PropertyVetoException e){}
    myFrame.addPropertyChangeListener(new PropertyChangeHandler());
    activeApplicationList.add(getSelectedApplication());
    Collections.sort(activeApplicationList);
    public void activateInternalFrame(JInternalFrame myFrame) {
    myFrame.setVisible(true);
    myFrame.toFront();
    class PropertyChangeHandler implements PropertyChangeListener {
    public void propertyChange(PropertyChangeEvent e) {
    if (((String)e.getPropertyName()).equals("closed")){
    setCurrentEvent(e);
    deActivateApplication(e);
    private void deActivateApplication(PropertyChangeEvent currentEvent){
    if ((getCurrentEvent().getSource() instanceof testje.testApp)){
    myPanelTestje = null;
    removeFromActiveApplicationList("PanelTestje");
    if ((getCurrentEvent().getSource() instanceof testje.testInternalFrame)){
    myFrameTestje = null;
    removeFromActiveApplicationList("FrameTestje");
    * Deze methode wordt gebruikt om de applicatienaam op
    * te vragen.
    * <p>
    * @return appName : appName Objectvalue.
    public static String getAppName() {
    return appName;
    * Deze methode wordt gebruikt om de applicatie af te sluiten
    * nadat eerst connectieObject wordt afgesloten.
    * <p>
    public static void exitApplication() {
    myLogger.info("End application.");
    System.exit(0);
    private static void setAppName(String appName)
    MenuTest.appName = appName;
    public class TreeExRenderer extends DefaultTreeCellRenderer {
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
    row, hasFocus);
    String nodeName = value.toString();
    ImageIcon main_leaf = createImageIcon("/images/jTreeRoot.gif");
    ImageIcon main_open = createImageIcon("/images/jTreeRoot.gif");
    ImageIcon main_close = createImageIcon("/images/jTreeRoot.gif");
    ImageIcon leafIcon = createImageIcon("/images/jTreeFolderClosed.gif");
    ImageIcon leafOpen = createImageIcon("/images/jTreeFolderOpen.gif");
    ImageIcon leafClosed = createImageIcon("/images/jTreeFolderClosed.gif");
    ImageIcon leafSelected = createImageIcon("/images/jTreeItemSelected.gif");
    ImageIcon leafActivated = createImageIcon("/images/jTreeItemSelected.gif");
    if (row==0){
    setIcon(main_leaf);
    } else {
    if(sel){
    setIcon(leafSelected);
    } else {
    if (!expanded) {
    if (isApplicationInActiveList(nodeName)){
    setIcon(leafActivated);
    } else {
    setIcon(leafClosed);
    }else{
    setIcon(leafOpen);
    return this;
    public ImageIcon createImageIcon(String path) {
    URL imgURL = MenuTest.class.getResource(path);
    URL imgURL1 = MenuTest.class.getResource(path);
    if ((imgURL != null)) {
    return new ImageIcon(imgURL);
    } else if ((imgURL == null)) {
    return new ImageIcon(imgURL1);
    } else {
    System.out.println("Hello ");
    System.err.println("Couldn't find file: " + path);
    return null;
    private ArrayList getActiveApplicationList()
    return activeApplicationList;
    private void setActiveApplicationList(ArrayList activeApplicationList)
    this.activeApplicationList = activeApplicationList;
    private boolean isApplicationInActiveList(String nodeName)
    if (activeApplicationList.indexOf(nodeName)>-1) {
    return true;
    } else {
    return false;
    public void removeFromActiveApplicationList(String application)
    activeApplicationList.remove(activeApplicationList.indexOf(application));
    // jTree.setSelectionRow((jTree.getRowCount())-1);
    jTree.setSelectionRow(0);
    public String getSelectedApplication()
    return selectedApplication;
    private void setSelectedApplication(String selectedApplication)
    this.selectedApplication = selectedApplication;
    public PropertyChangeEvent getCurrentEvent()
    return currentEvent;
    private void setCurrentEvent(PropertyChangeEvent currentEvent)
    this.currentEvent = currentEvent;
    private void getApplicationList() {
    sflData = new ArrayList();
    // Get Applicationlist
    sflData.add("PGO;50;General;App1;pack.myApp1;Application 1");
    sflData.add("PGO;55;Operational;App2;pack.myApp2;Application 2");
    sflData.add("PGO;60;Operational;App3;pack.myApp3;Application 3");
    sflData.add("PGO;65;Expeditie;PanelTestje;testje.Paneltestje;Expeditie Paneltestje");
    sflData.add("PGO;70;Desktop;App4;pack.myApp4;Application 4");
    sflData.add("PGO;75;Manifest;FrameTestje;testje.FrameTestje;Maritiem FrameTestje");
    sflData.add("PGO;80;Desktop;App5;pack.myApp5;Application 5");
    // Convert applicationlist to MenuArray
    data = new Object[sflData.size()][6];
    for (int i = 0; i < sflData.size(); i++){
    int count = 0;
    String str;
    str = (String)sflData.get(i);
    StringTokenizer token = new StringTokenizer(str,";");
    while (token.hasMoreTokens()){
    data [i] [count] = token.nextToken();
    count++;
    *testapp1*package testje;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    * @author pgo
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class testApp
    extends JInternalFrame {
         testPanel p;
    Container c;
    boolean packFrame = false;
         public testApp() {
              super("Swing-Toepassing PanelTestje");
              c = getContentPane();
    c.setLayout(new BorderLayout());
              p = new testPanel();
              c.add(p);
    //setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setVisible(true);
    //Validate frames that have preset sizes
    //Pack frames that have useful preferred size info, e.g. from their layout
    if (packFrame) {
    this.pack();
    else {
    this.validate();
    // addWindowListener(new WindowAdapter() {
    // public void windowClosed(WindowEvent e) {
    // System.exit(0);
         public static void main(String[] args) {
              // final JFrame f = new testApp();
    // new testApp();
    *testInternalFrame*/*
    * Created on 19-apr-2007
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package testje;
    import javax.swing.*;
    import java.awt.*;
    * @author pgo
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class testInternalFrame extends JInternalFrame {
         public void testInternalFrame(){
              setBackground(Color.white);
              Container contentPane = getContentPane();
              setLocation(20,20);
              setTitle("Internal Frame");
              setClosable(true);
              setResizable(true);
              setMaximizable(true);
              setIconifiable(true);
              setVisible(true);
              contentPane.setLayout(new FlowLayout());
              contentPane.add(new JTextArea(5,15), "Center");
              pack();
    *testPanel*/*
    * Created on 19-apr-2007
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package testje;
    import javax.swing.*;
    import java.awt.*;
    * @author pgo
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class testPanel extends JPanel {
         public void testPanel(){
              setBackground(Color.blue);
         public void paintComponent (Graphics g){
              super.paintComponent(g);
              g.drawString("Groeten van Patrick", 0, 60);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    When you say "the JLabel changes" I'm guessing you mean that the JLabel variable named "imageLabel" was the thing that changed? That won't change the GUI's reference to the original JLabel object.
    Which is what you have to change. You have a reference to that object in the form of the "imageLabel" variable; to change the object you call one of its methods, like maybe setIcon() or something... whatever your ImageManager class is doing to create the label in the first place.

  • What is wrong with my code

    If you don't mind this lost post, but I'm having trouble with the execution of this application I wrote. Seeing that java gave me the NoClassDefFoundError. Is there a way I can avoid this problem? BTW, if you have found any bugs or problems in the program, please post the correction. Thank you very much!
    import java.lang.String.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class SentenceTestWindow extends JFrame
    private ActionEventHandler handler;
    private Container c;
    private int count, i = 0;
    private JTextField input;
    private JTextField output;
    private JLabel inputLabel;
    private JLabel outputLabel;
    private JPanel top;
    //SnowPanel snow;
    private String result = "", sentence;
    private StringTokenizer tokens;
    public SentenceTestWindow()
    super( "A Sentence Test" );
    top = new JPanel();
    top.setLayout(new FlowLayout());
    inputLabel = new JLabel("Enter a sentence: ");
    input = new JTextField(60);
    input.addActionListener(handler);
    outputLabel = new JLabel("Result: ");
    output = new JTextField(60);
    output.setEnabled(false);
    //snow = new SnowPanel();
    c = getContentPane();
    c.add(top);
    //c.add(snow, BorderLayout.CENTER);
    private class ActionEventHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    if (e.getSource() == input)
    sentence = e.getActionCommand();
    output.setFont(new Font(input.getName(), Font.BOLD + Font.ITALIC, 16));
    output.setForeground(Color.blue);
    tokens = new StringTokenizer(sentence);
    count = tokens.countTokens();
    String words[] = new String[count];
    input.setText("");
    result = "";
    while(tokens.hasMoreTokens())
    words[i] = tokens.nextToken();
    i++;
    for (i = count; i >= 0; i--)
    result += words[i] + " ";
    output.setText(result);
    int r = (int) (Math.random() * 256);
    int g = (int) (Math.random() * 256);
    int b = (int) (Math.random() * 256);
    c.setBackground(new Color (r,g,b));
    public static void main(String args[])
    SentenceTestWindow window = new SentenceTestWindow();
    window.setSize(500, 500);
    window.show();
    /* public class SnowPanel extends JPanel
    public void paintComponent(Graphics g)
    super.paintComponent */
    }

    Here's the revised code, now the BorderLayout.NORTH is too restricting for the JPanel that I created. Any suggestions?
    import java.lang.String.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    public class SentenceTestWindow extends JFrame
    private ActionEventHandler handler;
    private BorderLayout layout;
    private Container c;
    private int count, i = 0;
    private JTextField input;
    private JTextField output;
    private JLabel inputLabel;
    private JLabel outputLabel;
    private JPanel top;
    SnowPanel snow;
    private String result = "", sentence;
    private StringTokenizer tokens;
    public SentenceTestWindow()
    super( "A Sentence Test" );
    c = getContentPane();
    top = new JPanel();
    top.setLayout(new FlowLayout());
    inputLabel = new JLabel("Enter a sentence: ");
    top.add(inputLabel);
    input = new JTextField(60);
    handler = new ActionEventHandler();
    input.addActionListener(handler);
    top.add(input);
    outputLabel = new JLabel("Result: ");
    top.add(outputLabel);
    output = new JTextField(60);
    top.add(output);
    snow = new SnowPanel();
    layout = new BorderLayout(2,2);
    c.add(top);
    c.add(snow);
    setSize(700,700);
    show();
    private class ActionEventHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    if (e.getSource() == input)
    sentence = input.getText();
    output.setForeground(Color.blue);
    output.setFont(new Font(input.getName(), Font.BOLD + Font.ITALIC, 16));
    tokens = new StringTokenizer(sentence);
    count = tokens.countTokens();
    String words[] = new String[count];
    input.setText("");
    result = "";
    for (i = 0; i < count; i++)
    words[i] = tokens.nextToken();
    for (i = count - 1; i >= 0; i--)
    result += words[i] + " ";
    output.setText(result);
    int r = (int) (Math.random() * 256);
    int g = (int) (Math.random() * 256);
    int b = (int) (Math.random() * 256);
    c.setBackground(new Color (r,g,b));
    public static void main(String args[])
    SentenceTestWindow window = new SentenceTestWindow();
    window.addWindowListener
    new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    window.setSize(700, 700);
    window.show();
    public class SnowPanel extends JPanel
    public void paintComponent(Graphics g)
    super.paintComponent( g );
    int xPoints[] = { 200, 217};
    int yPoints[] = { 100, 112 };
    Graphics2D g2d = ( Graphics2D ) g;
    GeneralPath snow = new GeneralPath();
    snow.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
    for ( int k = 1; k < xPoints.length; k++ )
    snow.lineTo( xPoints[ k ], yPoints[ k ] );
    snow.closePath();
    g2d.translate( 200, 200 );
    for ( int j = 1; j <= 20; j++ )
    g2d.rotate( Math.PI / 10.0 );
    g2d.setColor(
    new Color( ( int ) ( Math.random() * 256 ),
    ( int ) ( Math.random() * 256 ),
    ( int ) ( Math.random() * 256 ) ) );
    g2d.fill( snow ); // draw a filled star

  • Power Mac G4 - invalid node structure

    I am hoping someone can help me. I have a Power Mac G4 - 933....we had a power outage and the Mac would not turn on...the power light lit up when pressed but the computer wouldn't boot...I reset the PRAM and all was good...except a file I had was corrupted and couldn't be opened....after that, a month later, another power outage. This time I had more trouble as resetting the PRAM didn';t work...I reset the logic board (taking out the battery for 30 minutes then replacing) and that didn't work either...I tried several combinations of the above to no avail...I finally took out the battery for over and hour, powered up the computer without the battery and it started...so the battery was corrupted.    I replaced the battery (correct one of 3.6 volts) and the computer fired right up. I ran disk utilities to see if all was okay. Checking preferences was fine but when I tried to verify, Disk Utilities came up with the message that it could not complete verifying and that it found "Invalid node structure" and that it could not repair the disk.   I then tried fsck to repair and to no avail...fsck gave me several messages depending on the repair options I tried including one that included that the problem was in "memory 4, 23412"....it said it could also not repair due to "os/10 i/o error" and the second run I took at it with a different method told me there was a problem with  "DIMM 2/J23 memory"...Apple's website says that if I get an uprepairable message from disk utility that I should back-up, erase and do a clean install...but with these messages indicating the problem is in the memory, since the battery runs the memory, could it be in there instead? ...of important note, I do not have the original install disk...the operating system running it is Tiger 10.4.11...I don't have the orignal disk and I have an empty 10.5 Leopard disk box with no idea where the disk is...I have snow leopard, but that cannot be installed on the G4....after running the last fsck attempt, the computer shut down and is back to only having the power light lit when pressed but no computer booting...where should I start/what do I do? I am hoping you all have good suggestions for me because some of my files were bnot backed up (I know...don't judge) and I got them onto a flashdrive right before the computer went down again, but I have no idea if they took,...further, I love this old dinosaur...

    Hi, only thing I've seen repair that is DiskWarrior, you'd need an older version...
    http://supportdb.alsoft.com:591/FMPro?-db=alsoftsupport&-lay=main&-max=15&-forma t=AlsoftSupport-qa.html&-script=counter&-token=177&-Skip=96&-find
    But it does sound like you have some bad RAM, but have you blown the dust out yet & tried reseating the RAM?

  • Windows 7 64 bit giving BEx Problems. Big time problems (!!)

    Hi there, i just got through an issue with BEx connecting to SAP on a laptop using Windows 7. After googling and sdning and SAP noting for a while did not find any suitable answer to this issue which seems strange to me as Windows 7 64 bit is not really a brand new product. The full specs are as follow. Anyone bringing some light into this subject would be very much appreciatted.
    => SAP Logon 720 with 0 Patch Level.
    => MS Office 2007
    => Windows 7 64 bits
    In C:\Windows i got:
         -> SAPMSG.ini
         -> Saproute.ini
         -> saplogon.ini
    in C:\Users\username\AppData\Roaming\SAP\Common i got:
         -> Sapgrph
         -> saplogon
         -> SapLogonTree.xml
         -> saprules.xml
         -> Saproute
         -> services
    The issue is that i am not able to logon either via BEx 7.x or 3.x. The Error message is:
    Error Group
    RFC_ERROR_COMMUNICATION
    Message
    Connect to message server failed
    Connect_PM  MSHOST=/H/172.17.255.194/H/XXX.intranet.xxxxxxx.com, R3NAME=XX, GROUP=PUBLIC
    LOCATION    CPIC (TCP/IP) on local host my-pc
    ERROR       timeout while pending for route completion
    TIME        Wed Jul 27 10:56:44 2011
    RELEASE     720
    COMPONENT   NI (network interface)
    VERSION     40
    RC          -12
    DETAIL      NiErrSet
    COUNTER     1

    Hi Alex ,
    SAP GUI for Windows 7.20 and all related applications including SAP Desktop Office Integration / BI Frontend / BW Frontend do not support Office 2010 64bit, only 32bit versions of Office are supported.
    This means that when using 64bit operating sytems with SAP GUI for Windows and related components you have to use a 32bit Microsoft Office version .
    For your issue , you can check these Notes.
    1. 1442028 - SAP GUI for Windows 7.20: No support for Office 2010 64bit
    2. 1264857 -   BExAnalyzer 7.X does not work on 64 bit Windows PCs
    3. 1503786  - Precalc server is not created correctly in TA:RSPRECADMIN
    4. 1589565  - Connection problem in Precalc server and Excel hangs
    Regards,
    Lokesh

  • Help/Question with Reinstall  OSX 10.2.1 on iBook G4

    First off...I just want to say that if someone can take the time to assist me I would appreciate it more than you know! Now...on to my issue:
    History:
    I have a iBook G4 running, I think on either 10.3 or 10.4 (I can't tell you now because it won't start up). I have the discs for 10.2.1 that came with the computer. I purchased my iBook from a roommate of mine a few years back and before selling it to me he loading 10.3 or 10.4, and I don't have those discs.
    I was having an issue at start up...It would load to the point where I could see the picture I had on my desktop, and the dock would come up. Then it would stop and none of the icons on my desktop would show and neither would the menu bar at the top of the screen. When I clicked on an application in the dock, it would not load...the computer was trying (you could hear it) but it never would load it.
    So, I did some online searching (using my wife's MacBook...yes, I wish we had two) and used the disk utility to verify my disc. It said the "keys were out of order". So, I clicked repair, and it said that it repaired "Book B" (at least I think that's what it said).
    So, I restarted my computer, and now it comes to the gray screen with the clear spinning thing as though it is about to load. It sits there a while, and then just shuts off. So, I tried to reset the PRAM and that didn't do anything either.
    Problem I now have:
    I am now to the point that I am thinking I need to reinstall OSX...as said, I have the 10.2.1 discs that came with it upon purchase, but I know my roommate upgraded me to a newer version. I have lots of documents on here that I don't want to lose (and programs I don't have the discs for) and I plan to choose the "Archive and Install" and "Preserve User and Network Settings" Options.
    Questions:
    Is this what I should do?
    and if so...
    Will installing an older version than what I currently have any negative impact on the install or in me keeping my current documents and programs?

    DiskWarrior is the only application that "can" fix this problem, but there is no 100% guarantee. You need to get the DW CD & boot from the CD to fix the problem.
    Look at these links about DW.
    http://supportdb.alsoft.com:591/FMPro?-db=alsoftsupport&-lay=main&-max=15&-forma t=AlsoftSupport-qa.html&-script=counter&-token=182&-Skip=101&-find
    http://www.jimarnold.org/blog/2008/10/keys-out-of-order-on-macbook-diskwarrior-t o-the-rescue/
    I assume you don't have a backup of your hard drive, or you could just erase the hard drive & copy the backup files to it. Your next investment should be to buy & use an external hard drive for backup. You can get one for about the price + of DW.
     Cheers, Tom

  • Eracom CSA 8000 and SUN PKCS#11 API

    I'm trying to use Eracom as a cryptographic accelerator for using with JSSE in establishment of SSL connections. I'm using its software version that I haven't installed the hardware but they both have the same functionalities and both uses PKCS11 as their interface to actual operations. The problem is that I have a token contains many entries includes secret keys, Private keys and certificates. But when I construct a keystore in my program in does not contain any entries. I looked at the log created by Eracom and noticed that it does not log in at all. However some of those entries are public and can be seen with Cryptoki Token Browser a GUI for working with tokens.
    I used that graphical interface and logged in as security officer. Then I generated a RSA keypair with subject set to 'CN=myserver'. I used Derive Key on public key to generate a certificate request and in turn prepared a certificate based on that request and imported that certificate using Create Object option. In this case it works it lists it as an entry and uses it in SSL server.

    You need to use the trustanchors nssModule, read the JavaTM PKCS#11 Reference Guide at --
    http://java.sun.com/javase/6/docs/technotes/guides/security/p11guide.html#Config
    For example, you can write your config file like this --
    name=NSS
    nssSecmodDirectory=path_of_your_dbs
    nssLibraryDirectory=path_of_dll_or_so
    nssModule=trustanchors

  • Storing file contents in a Collection

    Hi All,
    Im trying to read a csv file, break the lines by comma, then store them and sort them.
    I have the test code working from: http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
    I am reading the file, but when I System.out.println() I keep getting the last line of the file only. Why is that?
         try {
              BufferedReader in = new BufferedReader(new FileReader("/Users/custodian/Desktop/list.csv"));
    String line;
    //Start reading the file while
    while ((line = in.readLine()) != null) {
    // System.out.println(line);
    StringTokenizer st = new StringTokenizer(line, ",");
    //Counting tokens while
    while (st.hasMoreTokens()){
         count++;
         //System.out.println(st.nextToken());
         fullname = st.nextToken();
         StringTokenizer wsp = new StringTokenizer(fullname, " ");
         //breaking full name apart while
         while(wsp.hasMoreTokens()){
              fname = wsp.nextToken();
              lname = wsp.nextToken();
         email = st.nextToken();
         phone = st.nextToken();
         streetaddress = st.nextToken();
         city = st.nextToken();
         state = st.nextToken();
         zip = st.nextToken();
         contactArray = new Contact(fname, lname, email, phone, streetaddress, city, state, zip);
         System.out.println(contactArray.toString());
         List <Contact> contacts = Arrays.asList(contactArray);
         Collections.sort(contacts);
         System.out.println(contacts);

    Hi,
    im trying to sort by state then write to another file:
    I keep getting an error on Collections.sort(contacts, new StateComparator());
    Collections.sort(contacts, new StateComparator());
                             try {
                                  BufferedWriter out = new BufferedWriter(new FileWriter("state-sort.csv"));
                                  //PrintWriter p = new PrintWriter(out);
                                  out.write(firstLine + "\n");
                                  Iterator it = contacts.listIterator();
                                  while(it.hasNext()) {
                                  Object o = it.next();     
                                  out.write(o.toString() + "\n");
                                  out.flush();
                                  out.close();
                             }catch(FileNotFoundException ee) {}
                             catch(IOException ioe) {}
    Here is my Comparator
    package mybeans;
    class StateComparator implements Comparable
         String state;
         public String getState() { return state; }
         public int compare(Object obj1, Object obj2)
              if(obj1 == obj2)
                   return 0;
              Contact c1 = (Contact) obj1;
              Contact c2 = (Contact) obj2;
              return c1.getState().compareTo(c2.getState());
         public int compareTo(Object obj)
              Contact c = (Contact) obj;
              return (state).compareTo(c.state + c.state);
    Any help appreciated.

  • Weird "keys out of order" problem

    So, keys out of order was new to me, but I've read up about possible fixes... My situation seems strange, here's why...
    I was working on my dual 1.8 G5, 10.4.11, clicked on a video link, then got the greyed out screen, and the multilingual restart message.
    So, I did several restarts, but the fans would go to full, and it would shut down before showing any activity on screen. So I entered single user mode, and typed the command for checking the disk (thankfully I could get info from the web on my macbook). That's when the 'keys out of order' message was first seen. After reading up I tried to run the fsck thing, which I read could be an option. I got an 'unable to repair' message. Then I put my workmates machine into target disk mode and started from that disk and tried to run disk utility over my startup disk, of course it didn't work, with several warnings in read about keys out of order etc.
    So I'm learning that DiskWarior is probably my best bet, but in the meantime I put my machine in target disk mode, and using a handy hint I found online, dsragged out my g3 iMac, booted it into OS9, extensions off. Connected by firewire, my G5 HD showed up and I was able to drag off some recent files, Mail folder etc. (At this point let me say I did a system back to a DMG file on a separate partition of an external USB drive several months ago, and that maybe 99% of my work and important files are on another external drive, so it's not life and death here.)
    NOW... comes the strange part. I go back to my machine, and just for a lark try to start it up again.... and it starts up fine, no problems, everything normal. Wow I think, I'll go and run disk utility over it now, so I restart using my friends powermac, and run said program, and get exactly the same errors, keys out of order. hmmm.
    So I go back to my machine, restart using its own system, all good, all fine. So I plug in another external HD and do a clone of the internal drive while its all working fine.
    So, since then its been running fine, (about a day and a half). But what should I do, and what's going on? Should I reformat my drive and out the earlier cloned system on it? Would the recent system clone I did likely be corrupt? Does it seem right that my system should work OK now, when Disk Utility was still reporting keys out of order? Should I pony up and buy DiskWarrior? (can't really afford to to be honest)
    I'm a bit flummoxed, thanks for any help...

    Hi, weird but not completely inexplicable.
    Indeed Disk Warrior is your best bet, IMHO every Mac oener should have it.
    I wouldn't completely trust any clone/backup once you get that error.
    Generally the only real fix for that error is DW, or Zeroing your drive & reinstalling.
    http://supportdb.alsoft.com:591/FMPro?-db=alsoftsupport&-lay=main&-max=15&-forma t=AlsoftSupport-qa.html&-script=counter&-token=182&-Skip=101&-find

  • Delegated Admin reports strange number of users

    I recently noted that our Delegated Admin (Delegated Administrator 6.4-2.05, B2008-04-29) Organizations page
    (the one which lists the hosted domains and particularly their "Number of Users") lists this number plain wrong.
    For many organizations it is reported as 0 or 1, for one there's a blank line, and only one seemingly has 39 users.
    When I click on organizations however, I see their full lists of users (I believe, ones which have a non-empty mail
    attribute set in LDAP) and there are tens in most orgs and over a hundred accounts in the larger org.
    What is wrong? Does DA's Organization-List page use some other means of counting the users than the individual
    Organization's page?

    JimKlimov wrote:
    In fact, while importing our old server, I did initialize most domains' users via
    ldapclient queries as discussed on-list in mid-2008. Nobody said that there
    are other static values outside of a user's account data :)The sunnumusers: attribute is commonly overlooked -- primarily because it is for admin-interface purposes only and doesn't impact on the operation of user accounts.
    Is it possible to replace this value of sunnumusers by a dynamic search (or
    counter), either in the GUI code or perhaps in the LDAP attribute?No. Any such dynamic search would have an adverse performance impact on the DA interface for large environments.
    What is the logically correct value, the count of users with mail attribute set?If you want the sunnumusers: to match the number of users displayed when you click on the organisation in the "Organizations" tab then you would count the users which matched the following search for the domain:
    ""(&(uid=*)(&(objectClass=inetuser)(|(inetUserStatus=active)(inetUserStatus=inactive))))""
    Regards,
    Shane.

  • Do you use Virtual Box VM... Please help with this.

    hey everyone I'm extremely new with all this stuff...
    I have a iMac 10.5.4 with the most current version of Virtual Box.
    When i load Virtual Box everything is rocking and extremely cool... but after an hour or so my network/server connections dies off on the mac side.
    when i go to GO >> Connect to Server >>
    smb://ipaddress
    I get this pop up...
    error connecting to the server >>
    I click OK and i get an error code -36
    the only way for me to connect again to the server is to shut down everything and restart the iMac it works just fine and i load VB back up and than everything works for about another hour or so and than i have to restart everything again.
    any clues to my issue?
    thanks for helping a newbie!
    cp

    ...but since you are learning, and would like to know where was the bug, I tried your code and updated it.
    The only two small problems I found:
    1. You have a while loop that checks if there are more tokens.. it's not needed and this while loop will only run because by the second run, you would have consumed all the tokens in the for loop, check would fail and while loop will be exited. [I have removed this while loop in my version below]
    2. Now, here is the bug:your for loop has a condition that evaluates (i < st.countTokens()).
    Now count tokens will only return "remaining" tokens. Assuming test string "this is a test", countTokens return 4. Then as you consume the first token, it is 3, then 2 then 1. All this while for loop's i is going 1,2...
    i = 0, countTokens = 4
    i = 1, countTokens = 3
    i = 2, countTokens = 2, check fails, and for loop is exited.
    So all you have in your array is first two tokens. Rest of the array is null as it was when you created the array.
    So then when you loop back and check index 3,2,1,0.. 3 and 2 elements are still nill, that's why you get the result you are getting.
    Here is the fixed code:
    String sentence = "this is second test"; //String variable to hold user input
    String output = ""; //String variable to enable display of output
    String buffer = "";//String variable to hold output
    st = new StringTokenizer(sentence);
    int tokenCount = st.countTokens();
    //Array to hold tokens
    String tokenHolder[] = new String[tokenCount];
    //Walk through the tokens
    for (int i = 0; i < tokenCount; i++)
         tokenHolder[i] = st.nextToken();
    String reversedTokens[] = new String[tokenCount];
    //Walk through the array in reverse
    for (int j = tokenCount-1; j >= 0; j--)
    //Add the reversed token to the ouptut string
    output += tokenHolder[j] + " ";
    System.out.println(output);
    }

  • Whitelist a domain

    Hello,
    I need to whitelist a domain on 10.10 server:
    sudo serveradmin settings mail:postfix:add_whitelist_domain = "domain.com"
    but for this i get result:
    mail:postfix:add_whitelist_domain = _empty_array
    What should I correct?
    Is there any documentation how to properly add values to settings in serveradmin?
    I found this: mail:postfix:host_whitelist = _empty_array – Add whitelisted hosts
    But I not helped.

    Hi,
    the following things you need to do:
    Forget what the Server Admin guide says, it doesn't work that way.
    I'm assuming you want to use greylisting, right?
    /usr/libexec/postfix/greylist.pl has issues in 10.10.x you need to replace it with correct version i.e. from OS X Mavericks (see further down)
    delete the files in the following directory to start fresh: sudo rm /Library/Server/Mail/Data/gldb/*
    restart the Mail Server
    Type the following command to add a domain that should be whitelisted: sudo serveradmin settings mail:postfix:add_whitelist_domain = "google.com"
    when it's done it will give you a list of already whitelisted domains and/or the one you just entered
    in this case google.com will be whitelisted and will pass through the greylist without the initial temporary rejection
    you can follow-up in the smtp.log in the server app to see that it works.
    I tested this in 10.10.2 OS X Server 4.0.3.
    I don't know what Apple did with the greylist.pl file it's missing some important code.
    This is what you need to put in you greylist.pl file to restore what's missing:
    #!/usr/bin/perl
    use DB_File;
    use Fcntl;
    use Sys::Syslog qw(:DEFAULT setlogsock);
    # Usage: greylist.pl [-v]
    # Demo delegated Postfix SMTPD policy server. This server implements
    # greylisting. State is kept in a Berkeley DB database.  Logging is
    # sent to syslogd.
    # How it works: each time a Postfix SMTP server process is started
    # it connects to the policy service socket, and Postfix runs one
    # instance of this PERL script.  By default, a Postfix SMTP server
    # process terminates after 100 seconds of idle time, or after serving
    # 100 clients. Thus, the cost of starting this PERL script is smoothed
    # out over time.
    # To run this from /etc/postfix/master.cf:
    #    policy  unix  -      n      n      -      -      spawn
    #      user=nobody argv=/usr/bin/perl /usr/libexec/postfix/greylist.pl
    # To use this from Postfix SMTPD, use in /etc/postfix/main.cf:
    #    smtpd_recipient_restrictions =
    # reject_unauth_destination
    # check_policy_service unix:private/policy
    # NOTE: specify check_policy_service AFTER reject_unauth_destination
    # or else your system can become an open relay.
    # To test this script by hand, execute:
    #    % perl greylist.pl
    # Each query is a bunch of attributes. Order does not matter, and
    # the demo script uses only a few of all the attributes shown below:
    #    request=smtpd_access_policy
    #    protocol_state=RCPT
    #    protocol_name=SMTP
    #    helo_name=some.domain.tld
    #    queue_id=8045F2AB23
    #    [email protected]
    #    [email protected]
    #    client_address=1.2.3.4
    #    client_name=another.domain.tld
    #    instance=123.456.7
    #    sasl_method=plain
    #    sasl_username=you
    #    sasl_sender=
    #    size=12345
    #    [empty line]
    # The policy server script will answer in the same style, with an
    # attribute list followed by a empty line:
    #    action=dunno
    #    [empty line]
    # greylist status database and greylist time interval. DO NOT create the
    # greylist status database in a world-writable directory such as /tmp
    # or /var/tmp. DO NOT create the greylist database in a file system
    # that can run out of space.
    # In case of database corruption, this script saves the database as
    # $database_name.time(), so that the mail system does not get stuck.
    $database_name="/Library/Server/Mail/Data/gldb/greylist.db";
    $whitelist_host_file="/Library/Server/Mail/Data/gldb/whitelist_host";
    $whitelist_domain_file="/Library/Server/Mail/Data/gldb/whitelist_domain";
    $whitelist_db_name="/Library/Server/Mail/Data/gldb/whitelist.db";
    $greylist_delay=60;
    # Auto-whitelist threshold. Specify 0 to disable, or the number of
    # successful "come backs" after which a client is no longer subject
    # to greylisting.
    $auto_whitelist_threshold = 10;
    # Syslogging options for verbose mode and for fatal errors.
    # NOTE: comment out the $syslog_socktype line if syslogging does not
    # work on your system.
    $syslog_socktype = 'unix'; # inet, unix, stream, console
    $syslog_facility="mail";
    $syslog_options="pid";
    $syslog_priority="info";
    sub add_whitelist {
      # check for null host name
      my ($_host_name) = $attr{"host_name"};
      if ($_host_name eq "") {
      syslog $syslog_priority, "Warning: missing whitelist host name attribute";
      return 0;
      # Open the database on the fly.
      open_whitelist_db() unless $whitelist_db_obj;
      # Is host already in white list
      $value = read_whitelist_db($attr{"host_name"});
      # Add host if not in database
      if ($value == 0) {
      syslog $syslog_priority, "adding host: %s to whitelist host", $attr{"host_name"} if $verbose;
      update_whitelist_db($attr{"host_name"}, 1);
      open WHITELIST_FILE, ">> $whitelist_host_file" or
      syslog $syslog_priority, "Error: unable to open whitelist host file: %s", $whitelist_host_file;
      print WHITELIST_FILE "$attr{\"host_name\"}\n";
      close WHITELIST_FILE;
    sub add_whitelist_domain {
      # check for null host name
      my ($_domain_name) = $attr{"domain_name"};
      if ($_domain_name eq "") {
      syslog $syslog_priority, "Warning: missing whitelist domain name attribute";
      return 0;
      # Open the database on the fly.
      open_whitelist_db() unless $whitelist_db_obj;
      # Is domain already in white list
      $value = read_whitelist_db($attr{"domain_name"});
      # Add domain if not in database
      if ($value == 0) {
      syslog $syslog_priority, "adding domain: %s to whitelist doman", $attr{"domain_name"} if $verbose;
      update_whitelist_db($attr{"domain_name"}, 1);
      open WHITELIST_FILE, ">> $whitelist_domain_file" or
      syslog $syslog_priority, "Error: unable to open whitelist domain file: %s", $whitelist_domain_file;
      print WHITELIST_FILE "$attr{\"domain_name\"}\n";
      close WHITELIST_FILE;
    # Demo SMTPD access policy routine. The result is an action just like
    # it would be specified on the right-hand side of a Postfix access
    # table.  Request attributes are available via the %attr hash.
    sub smtpd_access_policy {
        my($key, $time_stamp, $now, $count, $domain);
        # Open the database on the fly.
        open_database() unless $database_obj;
        # Open the whitelist database on the fly.
        open_whitelist_db() unless $whitelist_db_obj;
        # Check if domain is whitelisted
      $domain = get_domain_name($attr{"client_name"});
      $count = read_whitelist_db($domain);
      if ($count > 0) {
      syslog $syslog_priority, "domain: %s is whitelisted", $domain if $verbose;
        return "dunno";
        # Check if host is whitelisted
      $count = read_whitelist_db($attr{"client_name"});
      if ($count > 0) {
      syslog $syslog_priority, "host: %s is whitelisted", $attr{"client_name"} if $verbose;
        return "dunno";
        # Search the auto-whitelist.
        if ($auto_whitelist_threshold > 0) {
            $count = read_database($attr{"client_address"});
            if ($count > $auto_whitelist_threshold) {
        return "dunno";
        # Lookup the time stamp for this client/sender/recipient.
        $key =
      lc $attr{"client_address"}."/".$attr{"sender"}."/".$attr{"recipient"};
        $time_stamp = read_database($key);
        $now = time();
        # If this is a new request add this client/sender/recipient to the database.
        if ($time_stamp == 0) {
      $time_stamp = $now;
      update_database($key, $time_stamp);
        # The result can be any action that is allowed in a Postfix access(5) map.
        # To label mail, return ``PREPEND'' headername: headertext
        # In case of success, return ``DUNNO'' instead of ``OK'' so that the
        # check_policy_service restriction can be followed by other restrictions.
        # In case of failure, specify ``DEFER_IF_PERMIT optional text...''
        # so that mail can still be blocked by other access restrictions.
        syslog $syslog_priority, "request age %d", $now - $time_stamp if $verbose;
        if ($now - $time_stamp > $greylist_delay) {
      # Update the auto-whitelist.
      if ($auto_whitelist_threshold > 0) {
        update_database($attr{"client_address"}, $count + 1);
      return "dunno";
        } else {
      # Apple
      syslog $syslog_priority, "Temporary message rejection to: <$attr{\"recipient\"}> from: <$attr{\"sender\"}> sent from: [$attr{\"client_address\"}] for: $greylist_delay seconds due to greylisting";
      return "defer_if_permit Service is unavailable";
    # You should not have to make changes below this point.
    sub LOCK_SH { 1 }; # Shared lock (used for reading).
    sub LOCK_EX { 2 }; # Exclusive lock (used for writing).
    sub LOCK_NB { 4 }; # Don't block (for testing).
    sub LOCK_UN { 8 }; # Release lock.
    # Log an error and abort.
    sub fatal_exit {
        my($first) = shift(@_);
        syslog "err", "fatal: $first", @_;
        exit 1;
    # Open hash database.
    sub open_database {
        my($database_fd);
        # Use tied database to make complex manipulations easier to express.
        $database_obj = tie(%db_hash, 'DB_File', $database_name,
      O_CREAT|O_RDWR, 0644, $DB_BTREE);
      if ( !$database_obj ) {
      # don't prevent mail deliveries due to corrupt database
      my $db_backup = $database_name . "." . time();
      syslog $syslog_priority, "Warning: open failed for: %s : backing up to: %s",
      $database_name, $db_backup;
      rename $database_name, $db_backup ||
      fatal_exit "Can't save %s as %s: $!", $database_name, $db_backup;
      # try again
      $database_obj = tie(%db_hash, 'DB_File', $database_name,
      O_CREAT|O_RDWR, 0644, $DB_BTREE) ||
      fatal_exit "Cannot open database %s: $!", $database_name;
        $database_fd = $database_obj->fd;
        open DATABASE_HANDLE, "+<&=$database_fd" ||
      fatal_exit "Cannot fdopen database %s: $!", $database_name;
        syslog $syslog_priority, "open %s", $database_name if $verbose;
    # Open hash whitelist database.
    sub open_whitelist_db {
        my($whitelist_db_fd);
        # Use tied database to make complex manipulations easier to express.
      $whitelist_db_obj = tie(%db_hash, 'DB_File', $whitelist_db_name,
      O_CREAT|O_RDWR, 0644, $DB_BTREE);
      if ( !$whitelist_db_obj ) {
      # don't prevent mail deliveries due to corrupt database
      my $db_backup = $whitelist_db_name . "." . time();
      syslog $syslog_priority, "Warning: open failed for: %s : backing up to: %s",
      $whitelist_db_name, $db_backup;
      rename $whitelist_db_name, $db_backup ||
      fatal_exit "Can't save %s as %s: $!", $whitelist_db_name, $db_backup;
      # try again
      $whitelist_db_obj = tie(%db_hash, 'DB_File', $whitelist_db_name,
      O_CREAT|O_RDWR, 0644, $DB_BTREE) ||
      fatal_exit "Cannot open database %s: $!", $whitelist_db_name;
        $whitelist_db_fd = $whitelist_db_obj->fd;
        open WHITELIST_DB_HANDLE, "+<&=$whitelist_db_fd" ||
      fatal_exit "Cannot fdopen database %s: $!", $whitelist_db_name;
        syslog $syslog_priority, "open %s", $whitelist_db_name if $verbose;
    # Read database. Use a shared lock to avoid reading the database
    # while it is being changed. XXX There should be a way to synchronize
    # our cache from the on-file database before looking up the key.
    sub read_database {
        my($key) = @_;
        my($value);
        flock DATABASE_HANDLE, LOCK_SH ||
      fatal_exit "Can't get shared lock on %s: $!", $database_name;
        # XXX Synchronize our cache from the on-disk copy before lookup.
        $value = $db_hash{$key};
        syslog $syslog_priority, "lookup %s: %s", $key, $value if $verbose;
        flock DATABASE_HANDLE, LOCK_UN ||
      fatal_exit "Can't unlock %s: $!", $database_name;
        return $value;
    # Read database. Use a shared lock to avoid reading the database
    # while it is being changed. XXX There should be a way to synchronize
    # our cache from the on-file database before looking up the key.
    sub read_whitelist_db {
        my($key) = @_;
        my($value);
        flock WHITELIST_DB_HANDLE, LOCK_SH ||
      fatal_exit "Can't get shared lock on %s: $!", $whitelist_db_name;
        # XXX Synchronize our cache from the on-disk copy before lookup.
        $value = $db_hash{$key};
        syslog $syslog_priority, "whitelist lookup %s: %s", $key, $value if $verbose;
        flock WHITELIST_DB_HANDLE, LOCK_UN ||
      fatal_exit "Can't unlock %s: $!", $whitelist_db_name;
        return $value;
    # Update database. Use an exclusive lock to avoid collisions with
    # other updaters, and to avoid surprises in database readers. XXX
    # There should be a way to synchronize our cache from the on-file
    # database before updating the database.
    sub update_database {
        my($key, $value) = @_;
        syslog $syslog_priority, "store %s: %s", $key, $value if $verbose;
        flock DATABASE_HANDLE, LOCK_EX ||
      fatal_exit "Can't exclusively lock %s: $!", $database_name;
        # XXX Synchronize our cache from the on-disk copy before update.
        $db_hash{$key} = $value;
        $database_obj->sync() &&
      fatal_exit "Can't update %s: $!", $database_name;
        flock DATABASE_HANDLE, LOCK_UN ||
      fatal_exit "Can't unlock %s: $!", $database_name;
    # Update database. Use an exclusive lock to avoid collisions with
    # other updaters, and to avoid surprises in database readers. XXX
    # There should be a way to synchronize our cache from the on-file
    # database before updating the database.
    sub update_whitelist_db {
        my($key, $value) = @_;
        syslog $syslog_priority, "store whitelist host %s: %s", $key, $value if $verbose;
        flock WHITELIST_DB_HANDLE, LOCK_EX ||
      fatal_exit "Can't exclusively lock %s: $!", $whitelist_db_name;
        # XXX Synchronize our cache from the on-disk copy before update.
        $db_hash{$key} = $value;
        $whitelist_db_obj->sync() &&
      fatal_exit "Can't update %s: $!", $whitelist_db_name;
        flock WHITELIST_DB_HANDLE, LOCK_UN ||
      fatal_exit "Can't unlock %s: $!", $whitelist_db_name;
    # Parse hostname to obtain domain name
    sub get_domain_name {
        my($in_host_name) = @_;
        my($value);
      my($count) = 0;
      @tokens = split(/\./, $in_host_name);
      $count = $#tokens;
      $value=$tokens[$count-1] . "." . $tokens[$count];
      return $value;
    # Signal 11 means that we have some kind of database corruption (yes
    # Berkeley DB should handle this better).  Move the corrupted database
    # out of the way, and start with a new database.
    sub sigsegv_handler {
        my $backup = $database_name . "." . time();
        rename $database_name, $backup ||
      fatal_exit "Can't save %s as %s: $!", $database_name, $backup;
        fatal_exit "Caught signal 11; the corrupted database is saved as $backup";
        my $wl_backup = $whitelist_db_name . "." . time();
        rename $whitelist_db_name, $wl_backup ||
      fatal_exit "Can't save %s as %s: $!", $whitelist_db_name, $wl_backup;
        fatal_exit "Caught signal 11; the corrupted database is saved as $wl_backup";
    $SIG{'SEGV'} = 'sigsegv_handler';
    # This process runs as a daemon, so it can't log to a terminal. Use
    # syslog so that people can actually see our messages.
    setlogsock $syslog_socktype;
    openlog $0, $syslog_options, $syslog_facility;
    # We don't need getopt() for now.
    while ($option = shift(@ARGV)) {
        if ($option eq "-v") {
      $verbose = 1;
        } else {
      syslog $syslog_priority, "Invalid option: %s. Usage: %s [-v]",
      $option, $0;
      exit 1;
    # Unbuffer standard output.
    select((select(STDOUT), $| = 1)[0]);
    # Receive a bunch of attributes, evaluate the policy, send the result.
    while (<STDIN>) {
        if (/([^=]+)=(.*)\n/) {
      $attr{substr($1, 0, 512)} = substr($2, 0, 512);
        } elsif ($_ eq "\n") {
      if ($verbose) {
        for (keys %attr) {
      syslog $syslog_priority, "Attribute: %s=%s", $_, $attr{$_};
      if ( $attr{"request"} eq "smtpd_access_policy" ) {
      $action = smtpd_access_policy();
      } elsif ( $attr{"request"} eq "whitelist" ) {
      $action = add_whitelist();
      } elsif ( $attr{"request"} eq "whitelist_domain" ) {
      $action = add_whitelist_domain();
      } else {
      fatal_exit "unrecognized request type: '%s'", $attr{request};
      syslog $syslog_priority, "Action: %s", $action if $verbose;
      print STDOUT "action=$action\n\n";
      %attr = ();
        } else {
      chop;
      syslog $syslog_priority, "warning: ignoring garbage: %.100s", $_;

  • OS X 10.9 Server Mail Domain Whitelisting

    I just cannot understand why this isn't working.
    I've added gmail, googlemail, mac, me, icloud to the whitelist, but emails from those domains still get greylisted:
    $ sudo serveradmin settings Mail | grep whitelist
    Mail:postfix:add_whitelist_domain:_array_index:5 = "gmail.com"
    Mail:postfix:add_whitelist_domain:_array_index:6 = "googlemail.com"
    Mail:postfix:add_whitelist_domain:_array_index:7 = "mac.com"
    Mail:postfix:add_whitelist_domain:_array_index:8 = "me.com"
    Mail:postfix:add_whitelist_domain:_array_index:9 = "icloud.com"
    Mail:postfix:domain_whitelist:_array_index:5 = "gmail.com"
    Mail:postfix:domain_whitelist:_array_index:6 = "googlemail.com"
    Mail:postfix:domain_whitelist:_array_index:7 = "mac.com"
    Mail:postfix:domain_whitelist:_array_index:8 = "me.com"
    Mail:postfix:domain_whitelist:_array_index:9 = "icloud.com"
    I tried:
    $ sudo serveradmin settings Mail:postfix:whitelist_enabled = yes
    2014-05-02 02:56:37.103 serveradmin[2894:507] Error: servermgr_mail: postconf read error: /usr/sbin/postconf: warning: whitelist_enabled: unknown parameter
    2014-05-02 02:56:37.104 serveradmin[2894:507] unable to save key: whitelist_enabled (unknown parameter)
    I've tried restarting the mail service and restarting the computer.
    Has anyone been successful in whitelisting a domain on 10.9 Server?
    May  2 02:37:47 example.com postfix/smtpd[1398]: connect from mail-oa0-f48.google.com[209.85.219.48]
    May  2 02:37:47 example /usr/libexec/postfix/greylist.pl[1403]: Temporary message rejection to: <[email protected]> from: <[email protected]> sent from: [209.85.219.48] for: 60 seconds due to greylisting
    May  2 02:37:48 example.com postfix/smtpd[1398]: NOQUEUE: reject: RCPT from mail-oa0-f48.google.com[209.85.219.48]: 450 4.7.1 <[email protected]>: Recipient address rejected: Service is unavailable; from=<[email protected]> to=<[email protected]> proto=ESMTP helo=<mail-oa0-f48.google.com>
    May  2 02:37:48 example.com postfix/smtpd[1398]: disconnect from mail-oa0-f48.google.com[209.85.219.48]

    #!/usr/bin/perl
    use DB_File;
    use Fcntl;
    use Sys::Syslog qw(:DEFAULT setlogsock);
    # Usage: greylist.pl [-v]
    # Demo delegated Postfix SMTPD policy server. This server implements
    # greylisting. State is kept in a Berkeley DB database.  Logging is
    # sent to syslogd.
    # How it works: each time a Postfix SMTP server process is started
    # it connects to the policy service socket, and Postfix runs one
    # instance of this PERL script.  By default, a Postfix SMTP server
    # process terminates after 100 seconds of idle time, or after serving
    # 100 clients. Thus, the cost of starting this PERL script is smoothed
    # out over time.
    # To run this from /etc/postfix/master.cf:
    #    policy  unix  -       n       n       -       -       spawn
    #      user=nobody argv=/usr/bin/perl /usr/libexec/postfix/greylist.pl
    # To use this from Postfix SMTPD, use in /etc/postfix/main.cf:
    #    smtpd_recipient_restrictions =
    #          reject_unauth_destination
    #          check_policy_service unix:private/policy
    # NOTE: specify check_policy_service AFTER reject_unauth_destination
    # or else your system can become an open relay.
    # To test this script by hand, execute:
    #    % perl greylist.pl
    # Each query is a bunch of attributes. Order does not matter, and
    # the demo script uses only a few of all the attributes shown below:
    #    request=smtpd_access_policy
    #    protocol_state=RCPT
    #    protocol_name=SMTP
    #    helo_name=some.domain.tld
    #    queue_id=8045F2AB23
    #    [email protected]
    #    [email protected]
    #    client_address=1.2.3.4
    #    client_name=another.domain.tld
    #    instance=123.456.7
    #    sasl_method=plain
    #    sasl_username=you
    #    sasl_sender=
    #    size=12345
    #    [empty line]
    # The policy server script will answer in the same style, with an
    # attribute list followed by a empty line:
    #    action=dunno
    #    [empty line]
    # greylist status database and greylist time interval. DO NOT create the
    # greylist status database in a world-writable directory such as /tmp
    # or /var/tmp. DO NOT create the greylist database in a file system
    # that can run out of space.
    # In case of database corruption, this script saves the database as
    # $database_name.time(), so that the mail system does not get stuck.
    $database_name="/Library/Server/Mail/Data/gldb/greylist.db";
    $whitelist_host_file="/Library/Server/Mail/Data/gldb/whitelist_host";
    $whitelist_domain_file="/Library/Server/Mail/Data/gldb/whitelist_domain";
    $whitelist_db_name="/Library/Server/Mail/Data/gldb/whitelist.db";
    $greylist_delay=60;
    # Auto-whitelist threshold. Specify 0 to disable, or the number of
    # successful "come backs" after which a client is no longer subject
    # to greylisting.
    $auto_whitelist_threshold = 10;
    # Syslogging options for verbose mode and for fatal errors.
    # NOTE: comment out the $syslog_socktype line if syslogging does not
    # work on your system.
    $syslog_socktype = 'unix'; # inet, unix, stream, console
    $syslog_facility="mail";
    $syslog_options="pid";
    $syslog_priority="info";
    sub add_whitelist {
              # check for null host name
              my ($_host_name) = $attr{"host_name"};
              if ($_host_name eq "") {
                        syslog $syslog_priority, "Warning: missing whitelist host name attribute";
                        return 0;
              # Open the database on the fly.
              open_whitelist_db() unless $whitelist_db_obj;
              # Is host already in white list
              $value = read_whitelist_db($attr{"host_name"});
              # Add host if not in database
              if ($value == 0) {
                        syslog $syslog_priority, "adding host: %s to whitelist host", $attr{"host_name"} if $verbose;
                        update_whitelist_db($attr{"host_name"}, 1);
                        open WHITELIST_FILE, ">> $whitelist_host_file" or
                                  syslog $syslog_priority, "Error: unable to open whitelist host file: %s", $whitelist_host_file;
                        print WHITELIST_FILE "$attr{\"host_name\"}\n";
                        close WHITELIST_FILE;
    sub add_whitelist_domain {
              # check for null host name
              my ($_domain_name) = $attr{"domain_name"};
              if ($_domain_name eq "") {
                        syslog $syslog_priority, "Warning: missing whitelist domain name attribute";
                        return 0;
              # Open the database on the fly.
              open_whitelist_db() unless $whitelist_db_obj;
              # Is domain already in white list
              $value = read_whitelist_db($attr{"domain_name"});
              # Add domain if not in database
              if ($value == 0) {
                        syslog $syslog_priority, "adding domain: %s to whitelist doman", $attr{"domain_name"} if $verbose;
                        update_whitelist_db($attr{"domain_name"}, 1);
                        open WHITELIST_FILE, ">> $whitelist_domain_file" or
                                  syslog $syslog_priority, "Error: unable to open whitelist domain file: %s", $whitelist_domain_file;
                        print WHITELIST_FILE "$attr{\"domain_name\"}\n";
                        close WHITELIST_FILE;
    # Demo SMTPD access policy routine. The result is an action just like
    # it would be specified on the right-hand side of a Postfix access
    # table.  Request attributes are available via the %attr hash.
    sub smtpd_access_policy {
        my($key, $time_stamp, $now, $count, $domain);
        # Open the database on the fly.
        open_database() unless $database_obj;
        # Open the whitelist database on the fly.
        open_whitelist_db() unless $whitelist_db_obj;
        # Check if domain is whitelisted
              $domain = get_domain_name($attr{"client_name"});
              $count = read_whitelist_db($domain);
              if ($count > 0) {
                        syslog $syslog_priority, "domain: %s is whitelisted", $domain if $verbose;
                  return "dunno";
        # Check if host is whitelisted
              $count = read_whitelist_db($attr{"client_name"});
              if ($count > 0) {
                        syslog $syslog_priority, "host: %s is whitelisted", $attr{"client_name"} if $verbose;
                  return "dunno";
        # Search the auto-whitelist.
        if ($auto_whitelist_threshold > 0) {
            $count = read_database($attr{"client_address"});
            if ($count > $auto_whitelist_threshold) {
                  return "dunno";
        # Lookup the time stamp for this client/sender/recipient.
        $key =
              lc $attr{"client_address"}."/".$attr{"sender"}."/".$attr{"recipient"};
        $time_stamp = read_database($key);
        $now = time();
        # If this is a new request add this client/sender/recipient to the database.
        if ($time_stamp == 0) {
              $time_stamp = $now;
              update_database($key, $time_stamp);
        # The result can be any action that is allowed in a Postfix access(5) map.
        # To label mail, return ``PREPEND'' headername: headertext
        # In case of success, return ``DUNNO'' instead of ``OK'' so that the
        # check_policy_service restriction can be followed by other restrictions.
        # In case of failure, specify ``DEFER_IF_PERMIT optional text...''
        # so that mail can still be blocked by other access restrictions.
        syslog $syslog_priority, "request age %d", $now - $time_stamp if $verbose;
        if ($now - $time_stamp > $greylist_delay) {
              # Update the auto-whitelist.
              if ($auto_whitelist_threshold > 0) {
                  update_database($attr{"client_address"}, $count + 1);
              return "dunno";
        } else {
              # Apple
              syslog $syslog_priority, "Temporary message rejection to: <$attr{\"recipient\"}> from: <$attr{\"sender\"}> sent from: [$attr{\"client_address\"}] for: $greylist_delay seconds due to greylisting";
              return "defer_if_permit Service is unavailable";
    # You should not have to make changes below this point.
    sub LOCK_SH { 1 };          # Shared lock (used for reading).
    sub LOCK_EX { 2 };          # Exclusive lock (used for writing).
    sub LOCK_NB { 4 };          # Don't block (for testing).
    sub LOCK_UN { 8 };          # Release lock.
    # Log an error and abort.
    sub fatal_exit {
        my($first) = shift(@_);
        syslog "err", "fatal: $first", @_;
        exit 1;
    # Open hash database.
    sub open_database {
        my($database_fd);
        # Use tied database to make complex manipulations easier to express.
        $database_obj = tie(%db_hash, 'DB_File', $database_name,
                                            O_CREAT|O_RDWR, 0644, $DB_BTREE);
              if ( !$database_obj ) {
                        # don't prevent mail deliveries due to corrupt database
                        my $db_backup = $database_name . "." . time();
                        syslog $syslog_priority, "Warning: open failed for: %s : backing up to: %s",
                                                                                              $database_name, $db_backup;
                        rename $database_name, $db_backup ||
                                  fatal_exit "Can't save %s as %s: $!", $database_name, $db_backup;
                        # try again
                        $database_obj = tie(%db_hash, 'DB_File', $database_name,
                                                      O_CREAT|O_RDWR, 0644, $DB_BTREE) ||
                                                      fatal_exit "Cannot open database %s: $!", $database_name;
        $database_fd = $database_obj->fd;
        open DATABASE_HANDLE, "+<&=$database_fd" ||
              fatal_exit "Cannot fdopen database %s: $!", $database_name;
        syslog $syslog_priority, "open %s", $database_name if $verbose;
    # Open hash whitelist database.
    sub open_whitelist_db {
        my($whitelist_db_fd);
        # Use tied database to make complex manipulations easier to express.
              $whitelist_db_obj = tie(%db_hash, 'DB_File', $whitelist_db_name,
                                            O_CREAT|O_RDWR, 0644, $DB_BTREE);
              if ( !$whitelist_db_obj ) {
                        # don't prevent mail deliveries due to corrupt database
                        my $db_backup = $whitelist_db_name . "." . time();
                        syslog $syslog_priority, "Warning: open failed for: %s : backing up to: %s",
                                                                                              $whitelist_db_name, $db_backup;
                        rename $whitelist_db_name, $db_backup ||
                                  fatal_exit "Can't save %s as %s: $!", $whitelist_db_name, $db_backup;
                        # try again
                        $whitelist_db_obj = tie(%db_hash, 'DB_File', $whitelist_db_name,
                                                      O_CREAT|O_RDWR, 0644, $DB_BTREE) ||
                                                      fatal_exit "Cannot open database %s: $!", $whitelist_db_name;
        $whitelist_db_fd = $whitelist_db_obj->fd;
        open WHITELIST_DB_HANDLE, "+<&=$whitelist_db_fd" ||
              fatal_exit "Cannot fdopen database %s: $!", $whitelist_db_name;
        syslog $syslog_priority, "open %s", $whitelist_db_name if $verbose;
    # Read database. Use a shared lock to avoid reading the database
    # while it is being changed. XXX There should be a way to synchronize
    # our cache from the on-file database before looking up the key.
    sub read_database {
        my($key) = @_;
        my($value);
        flock DATABASE_HANDLE, LOCK_SH ||
              fatal_exit "Can't get shared lock on %s: $!", $database_name;
        # XXX Synchronize our cache from the on-disk copy before lookup.
        $value = $db_hash{$key};
        syslog $syslog_priority, "lookup %s: %s", $key, $value if $verbose;
        flock DATABASE_HANDLE, LOCK_UN ||
              fatal_exit "Can't unlock %s: $!", $database_name;
        return $value;
    # Read database. Use a shared lock to avoid reading the database
    # while it is being changed. XXX There should be a way to synchronize
    # our cache from the on-file database before looking up the key.
    sub read_whitelist_db {
        my($key) = @_;
        my($value);
        flock WHITELIST_DB_HANDLE, LOCK_SH ||
              fatal_exit "Can't get shared lock on %s: $!", $whitelist_db_name;
        # XXX Synchronize our cache from the on-disk copy before lookup.
        $value = $db_hash{$key};
        syslog $syslog_priority, "whitelist lookup %s: %s", $key, $value if $verbose;
        flock WHITELIST_DB_HANDLE, LOCK_UN ||
              fatal_exit "Can't unlock %s: $!", $whitelist_db_name;
        return $value;
    # Update database. Use an exclusive lock to avoid collisions with
    # other updaters, and to avoid surprises in database readers. XXX
    # There should be a way to synchronize our cache from the on-file
    # database before updating the database.
    sub update_database {
        my($key, $value) = @_;
        syslog $syslog_priority, "store %s: %s", $key, $value if $verbose;
        flock DATABASE_HANDLE, LOCK_EX ||
              fatal_exit "Can't exclusively lock %s: $!", $database_name;
        # XXX Synchronize our cache from the on-disk copy before update.
        $db_hash{$key} = $value;
        $database_obj->sync() &&
              fatal_exit "Can't update %s: $!", $database_name;
        flock DATABASE_HANDLE, LOCK_UN ||
              fatal_exit "Can't unlock %s: $!", $database_name;
    # Update database. Use an exclusive lock to avoid collisions with
    # other updaters, and to avoid surprises in database readers. XXX
    # There should be a way to synchronize our cache from the on-file
    # database before updating the database.
    sub update_whitelist_db {
        my($key, $value) = @_;
        syslog $syslog_priority, "store whitelist host %s: %s", $key, $value if $verbose;
        flock WHITELIST_DB_HANDLE, LOCK_EX ||
              fatal_exit "Can't exclusively lock %s: $!", $whitelist_db_name;
        # XXX Synchronize our cache from the on-disk copy before update.
        $db_hash{$key} = $value;
        $whitelist_db_obj->sync() &&
              fatal_exit "Can't update %s: $!", $whitelist_db_name;
        flock WHITELIST_DB_HANDLE, LOCK_UN ||
              fatal_exit "Can't unlock %s: $!", $whitelist_db_name;
    # Parse hostname to obtain domain name
    sub get_domain_name {
        my($in_host_name) = @_;
        my($value);
              my($count) = 0;
              @tokens = split(/\./, $in_host_name);
              $count = $#tokens;
              $value=$tokens[$count-1] . "." . $tokens[$count];
              return $value;
    # Signal 11 means that we have some kind of database corruption (yes
    # Berkeley DB should handle this better).  Move the corrupted database
    # out of the way, and start with a new database.
    sub sigsegv_handler {
        my $backup = $database_name . "." . time();
        rename $database_name, $backup ||
              fatal_exit "Can't save %s as %s: $!", $database_name, $backup;
        fatal_exit "Caught signal 11; the corrupted database is saved as $backup";
        my $wl_backup = $whitelist_db_name . "." . time();
        rename $whitelist_db_name, $wl_backup ||
              fatal_exit "Can't save %s as %s: $!", $whitelist_db_name, $wl_backup;
        fatal_exit "Caught signal 11; the corrupted database is saved as $wl_backup";
    $SIG{'SEGV'} = 'sigsegv_handler';
    # This process runs as a daemon, so it can't log to a terminal. Use
    # syslog so that people can actually see our messages.
    setlogsock $syslog_socktype;
    openlog $0, $syslog_options, $syslog_facility;
    # We don't need getopt() for now.
    while ($option = shift(@ARGV)) {
        if ($option eq "-v") {
              $verbose = 1;
        } else {
              syslog $syslog_priority, "Invalid option: %s. Usage: %s [-v]",
                        $option, $0;
              exit 1;
    # Unbuffer standard output.
    select((select(STDOUT), $| = 1)[0]);
    # Receive a bunch of attributes, evaluate the policy, send the result.
    while (<STDIN>) {
        if (/([^=]+)=(.*)\n/) {
              $attr{substr($1, 0, 512)} = substr($2, 0, 512);
        } elsif ($_ eq "\n") {
              if ($verbose) {
                  for (keys %attr) {
                        syslog $syslog_priority, "Attribute: %s=%s", $_, $attr{$_};
                        if ( $attr{"request"} eq "smtpd_access_policy" ) {
                                  $action = smtpd_access_policy();
                        } elsif ( $attr{"request"} eq "whitelist" ) {
                                  $action = add_whitelist();
                        } elsif ( $attr{"request"} eq "whitelist_domain" ) {
                                  $action = add_whitelist_domain();
                        } else {
                                  fatal_exit "unrecognized request type: '%s'", $attr{request};
                        syslog $syslog_priority, "Action: %s", $action if $verbose;
                        print STDOUT "action=$action\n\n";
                        %attr = ();
        } else {
              chop;
              syslog $syslog_priority, "warning: ignoring garbage: %.100s", $_;

Maybe you are looking for

  • Numbers problem after updates

    I bought numbers from the app store. After updates and reboot, the app will not save or print. it is telling me my free trail period is over,and i need to purchase?

  • IPad2 with ios8 has major problem!

    My iPad was frozen up just minutes ago. The screen only shows the background pic. The triple click is available, so are the notif. center and control center but it doesnt work. No apps. Its just blank. YOU CANT DO ANYTHING ON IT. Nothing works!!! It'

  • Installation/deployement of an application with wls

    Hello, I'm trying to package an application that I deployed under wls7 so that I could give it to someone else and he/she would be able to deploy it under his/her own wls7 installation. If I zip my application and unzip it under another wls7 installa

  • CVS connection functions

    Hi, I am looking for functions/libraries that I can use to connect to my CVS. I want to connect to my CVS, check out couple of files, make some operations on them and send them back [commit] to CVS. is it possible? thanks.

  • Error while Connecting to forms10g(ORA-00604)

    Hi all, I installed forms10g and reports10g. when I am trying to connect database I am getting ORA-00604-Error occured at recursive SQL level1 Operating system:windows home basic vista Thanks & Regards venkat Edited by: venkata on Jul 26, 2009 10:52