1 /*
2  * To change this template, choose Tools | Templates
3  * and open the template in the editor.
4  */
5 
6 package com.sun.star.wizards.common;
7 
8 import com.sun.star.beans.PropertyAttribute;
9 import com.sun.star.beans.PropertyState;
10 import com.sun.star.beans.PropertyValue;
11 import com.sun.star.uno.UnoRuntime;
12 import com.sun.star.uno.XInterface;
13 import java.util.HashMap;
14 import java.util.Iterator;
15 import java.util.Map.Entry;
16 
17 /**
18  *
19  * @author frank.schoenheit@sun.com
20  */
21 public class NamedValueCollection
22 {
23     final private HashMap< String, Object >    m_values = new HashMap< String, Object >();
24 
25     public NamedValueCollection()
26     {
27     }
28 
29     public NamedValueCollection( final PropertyValue[] i_values )
30     {
31         for ( int i = 0; i < i_values.length; ++i )
32             m_values.put( i_values[i].Name, i_values[i].Value );
33     }
34 
35     public final void put( final String i_name, final Object i_value )
36     {
37         m_values.put( i_name, i_value );
38     }
39 
40     @SuppressWarnings("unchecked")
41     public final < T  > T getOrDefault( final String i_key, final T i_default )
42     {
43         if ( m_values.containsKey( i_key ) )
44         {
45             final Object value = m_values.get( i_key );
46             try
47             {
48                 return (T)value;
49             }
50             catch ( ClassCastException e ) { }
51         }
52         return i_default;
53     }
54 
55     @SuppressWarnings("unchecked")
56     public final < T extends XInterface > T queryOrDefault( final String i_key, final T i_default, Class i_interfaceClass )
57     {
58         if ( m_values.containsKey( i_key ) )
59         {
60             final Object value = m_values.get( i_key );
61             return (T)UnoRuntime.queryInterface( i_interfaceClass, value );
62         }
63         return i_default;
64     }
65 
66     public final boolean has( final String i_key )
67     {
68         return m_values.containsKey( i_key );
69     }
70 
71     public final PropertyValue[] getPropertyValues()
72     {
73         PropertyValue[] values = new PropertyValue[ m_values.size() ];
74 
75         Iterator< Entry< String, Object > > iter = m_values.entrySet().iterator();
76         int i = 0;
77         while ( iter.hasNext() )
78         {
79             Entry< String, Object > entry = iter.next();
80             values[i++] = new PropertyValue(
81                 entry.getKey(),
82                 0,
83                 entry.getValue(),
84                 PropertyState.DIRECT_VALUE
85             );
86         }
87 
88         return values;
89     }
90 }
91