How do I ensure a Map key maps to the correct data type?

Hi,
I have a simple event processing interface, where an Action class processes an event, and optionally generates a response event. I want to store a map of all registered actions, and then select the one matching an incoming event at run time:
// the basic types
public abstract class Event {
  protected String type;
  protected String data;
  public String getType()  { return type; }
  @Override
  public String toString() { return data; }
// an action processes a request event and optionally returns a response event
public interface Action<ReqE extends Event, ResE extends Event> {
  public ResE process(ReqE request);
// two simple events
public class Event1 extends Event {
  public Event1(String data) { this.type = "ev1"; this.data = data; }
public class Event2 extends Event {
  public Event2(String data) { this.type = "ev2"; this.data = data; }
// simple test class
public class Test {
  Map<String, Action<? extends Event, ? extends Event>> actions
    = new HashMap<String, Action<? extends Event, ? extends Event>>();
  public void run() {
    // source event
    Event1 request = new Event1("hello");
    // register an action - takes an Event1 and returns an Event2
    actions.put(request.getType(), new Action<Event1, Event2>() {
      @Override
      public Event2 process(Event1 req) {
        return new Event2(req.data);
    // run it
    Action<Event, Event> action = getAction(request.getType());
    Event response = action == null ? null : action.process(request);
    System.out.println("Response=" + String.valueOf(response));
  public Action<Event, Event> getAction(String type) {
    return (Action<Event, Event>)actions.get(type);
  public static void main(String[] args) {
    new Test().run();
}This all works, but the problem is obviously the cast in the getAction() method. I can see what the problem is: there is nothing to stop me registering a handler with the wrong event types:
  // register an action - this will fail at runtime as request is an Event1
  actions.put(request.getType(), new Action<Event3, Event4>() {
    @Override
    public Event4 process(Event3 req) {
      return new Event4(req.data);
  });So that leads to the map declaration. What I think I need to do is change the key of the map from String to... well, I'm not sure what! Some kind of parameterised EventType class that ties in to the event types of the parameterised Action class, so when I call:
  Map<????, Action<? extends Event, ? extends Event>> actions = ...
  actions.put(????, new Action<Event1, Event2>() {...});the key type ties in to Event1/Event2 so that it ensures the eventual call to "process" will receive the correct types. But this is really getting beyond my knowledge of generics!
So if anybody has any useful pointers on where to go from here I'd be realy grateful.
Cheers,
Barney

The obvious choice for the key would be the type of the request event instead of a plain String.
Thus, declare the map like this:
Map<Class<? extends Event>, Action<?,?>>Below, I've modified your code so that it is typesafe, provided you use the public methods "registerAction" and "getAction".
import java.util.HashMap;
import java.util.Map;
abstract class Event {
       protected String type;
       protected String data;
       public String getType()  { return type; }
       @Override
       public String toString() { return data; }
     // an action processes a request event and optionally returns a response event
      interface Action<ReqE extends Event, ResE extends Event> {
       public ResE process(ReqE request);
     // two simple events
      class Event1 extends Event {
       public Event1(String data) { this.type = "ev1"; this.data = data; }
      class Event2 extends Event {
       public Event2(String data) { this.type = "ev2"; this.data = data; }
     // simple test class
     public class EventTest {
       Map<Class<? extends Event>, Action<?,?>> actions
         = new HashMap<Class<? extends Event>, Action<?,?>>();
       public void run() {
         // source event
         Event1 request = new Event1("hello");
         // register an action - takes an Event1 and returns an Event2
         registerAction(Event1.class, new Action<Event1, Event2>() {
           public Event2 process(Event1 req) {
             return new Event2(req.data);
         // run it
         Action<? super Event1,?> action = getAction(Event1.class);
         Event response = action == null ? null : action.process(request);
         System.out.println("Response=" + String.valueOf(response));
       @SuppressWarnings("unchecked")
     public <E extends Event> Action<? super E,?> getAction(Class<E> type) {
         return (Action<? super E,?>)actions.get(type);
       public <E extends Event> void registerAction(Class<E> type, Action<? super E,?> action) {
              actions.put(type, action);
       public static void main(String[] args) {
         new EventTest().run();
     }

Similar Messages

  • How to access the Custom Data type variable given in Expression edit control To and From LabVIEW

    Hello, I would like to know how to access the custom data type variable given in the Espression Edit Control from LabVIEW and vice-versa
    Say, the FileGlobals.Reference_Handle (Custom Data Type Variable) contains the
    VISA I/O session (Which in turn contains VISA_DeviceName: String, Session: Number),
    Channel1: Number and
    Channel2: Number
    I am expecting the user to give FileGlobals.Reference_Handle as the input at the ExpressionEdit Control in the edit screen of the VI Call.
    I would like to know how to get the values of this custom data type to LabVIEW?
    Say, if I have the Cluster in LabVIEW like VISA I/O session (Deive Name and Session Number), Channel1 and Channel2
    how do i need to set this cluster to the Custom Data type variable in TestStand?
    Thanks and Regards
    Prakash 

    Hi,
    TestStand to LabVIEW: i didnt understand what you r trying to achieve. But if you are using references, Use Property nodes and Invoke nodes to achieve what you want in LabVIEW.
     LabVIEW to TestStand: check the image below: You need to click the button next to 'container'. I have used a cluster output in the VI.
    Hope this helps
    .......^___________________^
    ....../ '---_BOT ____________ ]
    ...../_==O;;;;;;;;_______.:/
    Attachments:
    1.JPG ‏187 KB

  • Issue with xsd Data type mapping for collection of user defined data type

    Hi,
    I am facing a issue with wsdl for xsd mapping for collection of user defined data type.
    Here is the code snippet.
    sample.java
    @WebMethod
    public QueryPageOutput AccountQue(QueryPageInput qpInput)
    public class QueryPageInput implements Serializable, Cloneable
    protected Account_IO fMessage = null;
    public class QueryPageOutput implements Serializable, Cloneable
    protected Account_IO fMessage = null;
    public class Account_IO implements Serializable, Cloneable {
    protected ArrayList <AccountIC> fintObjInst = null;
    public ArrayList<AccountIC>getfintObjInst()
    return (ArrayList<AccountIC>)fintObjInst.clone();
    public void setfintObjInst(AccountIC val)
    fintObjInst = new ArrayList<AccountIC>();
    fintObjInst.add(val);
    Public class AccountIC
    protected String Name;
    protected String Desc;
    public String getName()
    return Name;
    public void setName(String name)
    Name = name;
    For the sample.java code, the wsdl generated is as below:
    <?xml version="1.0" encoding="UTF-8" ?>
    <wsdl:definitions
    name="SimpleService"
    targetNamespace="http://example.org"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:tns="http://example.org"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
    >
    <wsdl:types>
    <xs:schema version="1.0" targetNamespace="http://examples.org" xmlns:ns1="http://example.org/types"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:import namespace="http://example.org/types"/>
    <xs:element name="AccountWSService" type="ns1:accountEMRIO"/>
    </xs:schema>
    <xs:schema version="1.0" targetNamespace="http://example.org/types" xmlns:ns1="http://examples.org"
    xmlns:tns="http://example.org/types" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:import namespace="http://examples.org"/>
    <xs:complexType name="queryPageOutput">
    <xs:sequence>
    <xs:element name="fSiebelMessage" type="tns:accountEMRIO" minOccurs="0"/>
    </xs:sequence>
    </xs:complexType>
    <xs:complexType name="accountEMRIO">
    <xs:sequence>
    <xs:element name="fIntObjectFormat" type="xs:string" minOccurs="0"/>
    <xs:element name="fMessageType" type="xs:string" minOccurs="0"/>
    <xs:element name="fMessageId" type="xs:string" minOccurs="0"/>
    <xs:element name="fIntObjectName" type="xs:string" minOccurs="0"/>
    <xs:element name="fOutputIntObjectName" type="xs:string" minOccurs="0"/>
    <xs:element name="fintObjInst" type="xs:anyType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    </xs:complexType>
    <xs:complexType name="queryPageInput">
    <xs:sequence>
    <xs:element name="fPageSize" type="xs:string" minOccurs="0"/>
    <xs:element name="fSiebelMessage" type="tns:accountEMRIO" minOccurs="0"/>
    <xs:element name="fStartRowNum" type="xs:string" minOccurs="0"/>
    <xs:element name="fViewMode" type="xs:string" minOccurs="0"/>
    </xs:sequence>
    </xs:complexType>
    </xs:schema>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://example.org"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://example.org" xmlns:ns1="http://example.org/types">
    <import namespace="http://example.org/types"/>
    <xsd:complexType name="AccountQue">
    <xsd:sequence>
    <xsd:element name="arg0" type="ns1:queryPageInput"/>
    </xsd:sequence>
    </xsd:complexType>
    <xsd:element name="AccountQue" type="tns:AccountQue"/>
    <xsd:complexType name="AccountQueResponse">
    <xsd:sequence>
    <xsd:element name="return" type="ns1:queryPageOutput"/>
    </xsd:sequence>
    </xsd:complexType>
    <xsd:element name="AccountQueResponse" type="tns:AccountQueResponse"/>
    </schema>
    </wsdl:types>
    <wsdl:message name="AccountQueInput">
    <wsdl:part name="parameters" element="tns:AccountQue"/>
    </wsdl:message>
    <wsdl:message name="AccountQueOutput">
    <wsdl:part name="parameters" element="tns:AccountQueResponse"/>
    </wsdl:message>
    <wsdl:portType name="SimpleService">
    <wsdl:operation name="AccountQue">
    <wsdl:input message="tns:AccountQueInput" xmlns:ns1="http://www.w3.org/2006/05/addressing/wsdl"
    ns1:Action=""/>
    <wsdl:output message="tns:AccountQueOutput" xmlns:ns1="http://www.w3.org/2006/05/addressing/wsdl"
    ns1:Action=""/>
    </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="SimpleServiceSoapHttp" type="tns:SimpleService">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="AccountQue">
    <soap:operation soapAction=""/>
    <wsdl:input>
    <soap:body use="literal"/>
    </wsdl:input>
    <wsdl:output>
    <soap:body use="literal"/>
    </wsdl:output>
    </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="SimpleService">
    <wsdl:port name="SimpleServicePort" binding="tns:SimpleServiceSoapHttp">
    <soap:address location="http://localhost:7101/WS-Project1-context-root/SimpleServicePort"/>
    </wsdl:port>
    </wsdl:service>
    </wsdl:definitions>
    In the above wsdl the collection of fintObjInst if of type xs:anytype. From the wsdl, I do not see the xsd mapping for AccountIC which includes Name and Desc. Due to which, when invoking the web service from a different client like c#(by creating proxy business service), I am unable to set the parameters for AccountIC. I am using JAX-WS stack and WLS 10.3. I have already looked at blog http://weblogs.java.net/blog/kohlert/archive/2006/10/jaxws_and_type.html but unable to solve this issue. However, at run time using a tool like SoapUI, when this wsdl is imported, I am able to see all the params related to AccountIC class.
    Can some one help me with this.
    Thanks,
    Sudha.

    Did you try adding the the XmlSeeAlso annotation to the webservice
    @XmlSeeAlso({<package.name>.AccountIC.class})
    This will add the schema for the data type (AccountIC) to the WSDL.
    Hope this helps.
    -Ajay

  • Maps doesn't show the correct position - Asha 311

    Nokia asha 311 latest update
    My maps don't show the correct position. Why?
    Moderator's Note: The subject was amended as the post was moved to the correct board.

    There is no in built GPS chip, so reliant solely upon network triangulation for location which may mean several km out.
    Happy to have helped forum in a small way with a Support Ratio = 37.0

  • How to sync your mouse and key board to the desk top when both the indicators are flashing?

    How to sync your mouse and key board to the desk top when both indicator lights are blinking?  I changed the batteries and I dont know how to sync them when they both wont work to follow the step to sync them up...help!

    The frozen was not clear in your first post…..
    Have you turned the computer off and then back on (force quit if necessary by holding the power button)?
    Try resetting the SMC:
    Shut down the computer.
    Unplug the computer's power cord.
    Wait fifteen seconds.
    Attach the computer's power cord.
    Press the power button to turn on the computer.
    Barry

  • How do I completely crop a PDF so that the cropped data is removed and the file size is reduced?

    How do I completely crop a PDF so that the cropped data is removed and the total file size is reduced?
    When I use the "Crop" function, the cropped data still remains in the file and there is no reduction in file size. I need a way to truly crop a PDF using Acrobat software.

    When you export, try to get the full file path or else you will have to do a lot of manual searching.
    If you downloaded the picture from Messages, the picture is stored in your User Library/Messages. to make your User Library visible, hold down the option key while using the Finder “Go To Folder” command. Enter ~/Library/Messages/Attachments. 
    If you prefer to make your user library permanently visible, use the Terminal command found below.
    http://osxdaily.com/2011/07/04/show-library-directory-in-mac-os-x-lion/
    You might want to bookmark the command. I had to use it again after I installed 10.8.4. I have also been informed that if you drag the user library to Finder it will remain visible.

  • Ensure List/Menu populate my update form with the correct data before update

    Hello,
    Please how do I ensure my update form is populated with the correct data before update?
    On my update page I have text fields and select fields (dynamic list/menu). When I open my profile page to make updates, I see the field well positioned in the text fields but in the select list/menu fields, I see "Select from list" instead of the value that was initiated selected
    Correct Values before update
    Wrong values during update
    As you can see from the images below, when I open the update page, the list automatically populate the select fields with the last values in the list instead of the Initial values that where selected by the user before the update.
    Can anyone please review and let me know where I have gone wrong.
    Thank you
    Mike

    Hello All,
    Once more thank you. I have sorted the issue out.
    I observed that I was selecting the wrong field. I selected the field matching the record set of the select instead of the field matching the record set of the table I am working as seen on the image belew
    I was selecting this - This is the record set of the table that hold values for the city select list
    Instead of this. This is the record set of the table behind the form I am working on
    My issue is now re-solved.
    Mike

  • HT1296 I have a problem synching calendar data between my iPhone 3GS iOS 5.1 & Outlook 2007 on MS7.  The basic calendar is OK but the birthdays (little box icon) are a day early & cannot be changed to the correct date. How can I fix this?

    I have a problem synching calendar data between my iPhone 3GS iOS 5.1 & Outlook 2007 on MS7.  The basic calendar data transfer is OK but the birthdays (little box icon) are a day early & cannot be changed to the correct date. The birthday entries in my Outlook contacts have correct dates.How can I fix this?

    The following peocess corrects the calendar entry:
    edit the contact & change the birthday, save the change; edit the contact & change the birthday to the correct value, save the change again. The calendar entry then displays on the correct date.  Alternatively as a temp solution I can just de-select the "birthdays" calendar which stops the icon being displayed.
    Thanks for your advice, I think that it's n going to be a slow process to fix all the entries for not much return.

  • How can I get my clock to remain on the correct time when starting bootcamp and windows XP? wireless option is not available.

    How can I get my clock to remain on the correct time when starting bootcamp and windows XP? wireless option is not available.

    Have a look at solutions in here https://discussions.apple.com/message/10689317#10689317
    Regards
    Stefan

  • My wife's iTunes ID will no longer work.  Tried to reset password but did not get email, tried to reset by answering personal questions' but will not accept the correct date of birth.  Has it been hacked?  How can I fix this?

    My wife's iTunes used ID will not work.  Tried resetting the password, but email was not received.  Tried using personal questions method, but would not accept the correct date of birth, so could not go any further.  Has her iTunes ID been hacked?  How can I fix this?

    Thanks for that advice @randers4.
    I linked through and submitted my info as a "topic not covered" in the iCloud section. After entering the serial number of my MBP it turns out I wasn't eligible for technical support (though I don't think this is hardware related support) and the final suggestion was to take my computer into an Apple store. I called my local Apple reseller and asked for assistance. The customer service rep was very nice but unable to help, so suggested I call Apple Support on 1300 321 456. I did so and, again, spoke to two very polite and helpful customer service people (I was transferred to security services). I didn't have to be on hold to speak to either rep for more than a few seconds! After trying a few different things, he worked out what was happening...
    So, to cut a long story short, to solve the problem in my OP, all I had to do was log out of iCloud in my System Preferences and log back in using my current Apple ID. [Edited to add that I had to sign out of everything I was currently signed in to with my Apple ID before logging out and in again.]
    Problem solved!
    Message was edited by: NotBaconBits

  • How to change colors of individual column bar in the same data series

    in mac numbers, how to change colors of individual column bar in the same data series. The entire column series gets selected in the column bars and cannot select to change colors of specifc bars.

    Hi Kiran,
    no its not possible through Theme editor also ,because these colors are coming from Compiler which u are using.
    Regards,
    Govindu

  • All the message dates in the message list changed in every mailbox to a recent date, I don't know why.. The dates within the messages' headlines themselves remained correct.  How do I re-establish the correct dates also in the mailboxes' message list?

    All the message dates in the message list changed in every mailbox to a recent date, I don't know why.. The dates within the messages' headlines themselves remained correct.  How do I re-establish the correct dates also in the mailboxes' message list?

    First thing is to forget all the complex configs and just try to schedule the report to run once now, no alerts, no notifications, no nothing.
    Does that work?
    Then you can build up the schedule, to see where the problem is coming from.
    Sincerely,
    Ted Ueda

  • I delete an individual message but the time I received the message is still showing next to the persons name in my inbox instead of going back into the correct date/time order. Anyone know how to fix this?

    I delete an individual message but the time I received the message is still showing next to the persons name in my inbox instead of going back into the correct date/time order. Anyone know how to fix this?

    SOLUTION
    Open "terminal" on your mac and type the following:
    defaults write com.apple.mail IgnoreSortOrderWhenSelectingAfterDelete 1
    (copy and past the whole line)
    This will stop that behaviour in mail. 
    It works on most opperating systems.
    mine is.
    Mac OSx 10.7.2 Lion
    Cheers

  • How to find the Column data type changes in table

    Hi All,
    I need to find out the column data type changes where made recently in table .
    How do i check past changes in column data type. Any data dictionary are there to find out the data type changes in the column .
    Thanks in advance..

    <FONT FACE="Arial" size=2 color="2D0000">
    You have the answer on hand (user_arguments / all_arguments)!
    SQL> desc user_arguments
    Name                                      Null?    Typ
    OBJECT_NAME      VARCHAR2(30)
    PACKAGE_NAME     VARCHAR2(30)
    OBJECT_ID     NOT NULL NUMBER
    OVERLOAD       VARCHAR2(40)
    ARGUMENT_NAME  VARCHAR2(30)
    POSITION       NOT NULL NUMBER
    SEQUENCE       NOT NULL NUMBER
    DATA_LEVEL     NOT NULL NUMBER
    DATA_TYPE      VARCHAR2(30) --> Data Type
    DEFAULT_VALUE  LONG
    DEFAULT_LENGTH NUMBER
    IN_OUT         VARCHAR2(9) -->Argument direction (IN,OUT,or IN/OUT)
    DATA_LENGTH    NUMBER
    DATA_PRECISION NUMBER
    DATA_SCALE     NUMBER
    RADIX          NUMBER
    CHARACTER_SET_NAME VARCHAR2(44)
    TYPE_OWNER         VARCHAR2(30)
    TYPE_NAME          VARCHAR2(30)
    TYPE_SUBNAME       VARCHAR2(30)
    TYPE_LINK          VARCHAR2(128)
    PLS_TYPE           VARCHAR2(30)
    CHAR_LENGTH        NUMBER
    CHAR_USED          VARCHAR2(1)
    Look for Data_Type where IN_OUT say OUT. That will be the data type retruned by that function.
    Edited :
    or POSITION in argument list,or null for function return value
    -SK
    </FONT>

  • How do i figure it out what app use the cellular data in standby mode?

    How do i figure it out what app use the cellular data in standby mode? I disabled the cellular data for 3 days, and my battery last longer. I don't use push notifications, neither location services. I'm not signed in in skype or any IM app.

    Do you use push email?  Do you have accounts that have synchronized calendars associated with them?  Those features will still use cellular data in the background as the receive mail and send or receive calendar updates.
    Some notifications, like push notifications from Facebook and other social networking sites may use cellular data in the background.  Basically, any automated data task like those may use cellular data when the phone is in standby (note that wifi would be used if available when the phone is active, but wifi turns off in standby and all data goes through the cellular data connection).

Maybe you are looking for

  • How to merge two apple id's?

    I have two apple ID's and would like to merge them. What do I need to do?

  • Ibook G4 (mid 2005) Bluetooth Issue

    I am having trouble with my bluetooth firmware updater it says "This version of the updater is missing the firmware file cannot proceed". I misplace all of my install discs like a moron. do i need the install discs or can the fix be downloaded.

  • Error message (-50) after updating to 7.3 version

    Hi i recently just updated to the newest itunes update which included the new iphone features and stuff (7.3. after i updated i went into my itunes library to find a recurring message dialog saying [The itunes library file cannot be saved. an unknown

  • Predefined Vs Flexible

    Greetings, Is it possible to implement Predefined and Flexible Appraisal Process in the same client? Please provide additional inputs on Yes/No. For annual appraisals we would like to use Predefined and for rest of processes (Surveys etc) would like

  • Oracle discoverer with oracle AS

    Is it oracle discoverer for web version must be install with oracle AS?