how to implement Queue in javaBeans - javabeans

I have an instance of NotificationEvent. i have added this instance in a queue whenever this instance is created.Name of the queue should be NotificationQueue.
structure of NotificationEvent is like this :
public class NotificationEvent {
private String sender;
private String receiver;
private String message;
/**
* #return the sender
*/
public String getSender() {
return sender;
}
/**
* #param sender the sender to set
*/
public void setSender(String sender) {
this.sender = sender;
}
/**
* #return the receiver
*/
public String getReceiver() {
return receiver;
}
/**
* #param receiver the receiver to set
*/
public void setReceiver(String receiver) {
this.receiver = receiver;
}
/**
* #return the message
*/
public String getMessage() {
return message;
}
/**
* #param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
What should be the required structure of NotificationQueue?

I suggest to not reinvent the wheel again. The interface Queue, already in the Java run-time library, defines operations which a queue should have. Here a brief tutorial for the Queue interface and the Queue JavaDoc. Well, here also a example of using Queue implementations.
You can create a Notification queue object like this:
Queue<NotificationEvent> eventQueue = new LinkedList<NotificationEvent>;
or, if you insist on having your own type for the queue:
public class extends LinkedList<NotificationEvent> {
/**
* Constructs an empty list.
*/
public NotificationQueue() {
}
/**
* Constructs a list containing the elements of the specified collection,
* in the order they are returned by the
* collection's iterator.
* #param c the collection whose elements are to be placed into this list
* #throws NullPointerException if the specified collection is null
*/
public NotificationQueue(Collection<? extends NotificationEvent> c) {
super(c);
}
}
...
NotificationQueue eventQueue == new NotificationQueue();
Note:
LinkedList is not the only available implementation of the Queue interface, see the Queue JavaDoc for other implementations already available in the Java run-time libs. Of course, you could also write your own implementation of the Queue interface.

Related

How to construct addToFront method

I have a IUArrayList class which implements IndexedUnsortedList interface and I have some constructors written but I need help writing the addToFront method. I have the addToRear method written and some other constructors done but I'm not sure about how to do addToFront. If you need to see more code let me know but this arraylist also uses an iterator which I keep track of with the modCount variable.
public class IUArrayList<T> implements IndexedUnsortedList<T> {
private static final int DEFAULT_CAPACITY = 10;
private static final int NOT_FOUND = -1;
private T[] array;
private int rear;
private int modCount;
/** Creates an empty list with default initial capacity */
public IUArrayList() {
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty list with the given initial capacity
* #param initialCapacity
*/
#SuppressWarnings("unchecked")
public IUArrayList(int initialCapacity) {
array = (T[])(new Object[initialCapacity]);
rear = 0;
modCount = 0;
}
/** Double the capacity of array */
private void expandCapacity() {
array = Arrays.copyOf(array, array.length*2);
}
#Override
public void addToFront(T element) {
// TODO
}
#Override
public void addToRear(T element) {
expandCapacity();
array[rear] = element;
rear++;
modCount++;
}
Below is the Interface that it implements.
public interface IndexedUnsortedList<T> extends Iterable<T>
{
/**
* Adds the specified element to the front of this list.
*
* #param element the element to be added to the front of this list
*/
public void addToFront(T element);
/**
* Adds the specified element to the rear of this list.
*
* #param element the element to be added to the rear of this list
*/
public void addToRear(T element);
If you use LinkedList instead of Array. You would be able to utilize addFirst and addLast methods of LinkedList to achieve what you want to achieve.

Calling a parent from an instantiated child fails strict standards

I am trying to call a parent method from its child which has the same method name. Doing so results in a strict standards error. There's an easy solution of renaming the child method. However, is there a way to keep the names of the two methods identical without a standards warning? Thanks.
Strict standards: Declaration of Child::getContentFromDb() should be compatible with Parent::getContentFromDb($id) in /foo/Child.class.php on line xxx
Pseudo-code example:
class Parent {
protected function getInfoFromDb($id) {
return $infoFromDb;
}
}
class Child extends Parent {
public static $id = xx;
public $info = array();
public function __construct() {
$this->info = $this->getInfoFromDb();
}
public function getInfoFromDb() {
// the line below causes the problem
return parent::getInfoFromDb(self::$id);
}
}
Your method override should take the same parameter list as the one you are overriding.
e.g.
class ParentClass {
protected function getInfoFromDb($id) {
return "INFO FROM DB:" . $id;
}
}
class Child extends ParentClass {
public static $id = "xx";
public $info = array();
public function __construct() {
$this->info = $this->getInfoFromDb();
}
/**
* #param specific ID, or do not set for default action.
* #return string
*/
public function getInfoFromDb($id = false) {
return parent::getInfoFromDb(self::$id);
}
}

When I use a function that I append to the class Controller, it does not work in Yii

I appended a xxx function to the class Controller, then I touched a file named 'VideoController'. It's extends Controller.
When I execute the VideoController, the xxx function can't be called, why?
the function ajaxReturn :
class Controller extends CController
{
/**
* #var string the default layout for the controller view. Defaults to '//layouts/column1',
* meaning using a single column layout. See 'protected/views/layouts/column1.php'.
*/
public $layout='//layouts/column1';
/**
* #var array context menu items. This property will be assigned to {#link CMenu::items}.
*/
public $menu=array();
/**
* #var array the breadcrumbs of the current page. The value of this property will
* be assigned to {#link CBreadcrumbs::links}. Please refer to {#link CBreadcrumbs::links}
* for more details on how to specify this property.
*/
public $breadcrumbs=array();
/**
* zhoumengkang
* 从Thinkphp里拖过来的
*/
protected function ajaxReturn($data,$info='',$status=1,$type='JSON') {
$result = array();
$result['status'] = $status;
$result['info'] = $info;
$result['data'] = $data;
if(strtoupper($type)=='JSON') {
header("Content-Type:text/html; charset=utf-8");
exit(json_encode($result));
}elseif(strtoupper($type)=='XML'){
header("Content-Type:text/xml; charset=utf-8");
exit(xml_encode($result));
}elseif(strtoupper($type)=='EVAL'){
header("Content-Type:text/html; charset=utf-8");
exit($data);
}else{
// TODO
}
}
}
but it can't by called in
class VideoController extends Controller {
public function actionTest() {
$this->ajaxReturn(true,'test',1);
}
}
You have to import your controller before extend.
Yii::import('application.controllers.Controller');
class VideoController extends Controller {
public function actionTest() {
$this->ajaxReturn(true,'test',1);
}
}
Better change your controller name from Controller to someothername.

How to initialize an object and override a method in objective c?

Like Other Language, We can create a object and override a method in the object during initialization. Please help me How can i do?
For Example:
public class DemoInitAndOverride {
public void handleMessage(){}
}
And in another class
public class SampleClass {
public void doSomeThing(){
DemoInitAndOverride demo = new DemoInitAndOverride(){
#Override
public void handleMessage() {
// TODO Auto-generated method stub
super.handleMessage();
}
};
}
}
****EDIT:****
Thanks everyone for possible solutions and suggestion. I think now it is important for me provide some details about the requirement which could help you in providing the solution.
The handler concept is some thing similar to the Android Framework where handlers are used to pass messages between 2 threads or 2 methods. Please see the code demonstration below:
UI Class (Here the user clicks a button, a request is dispatched to the processor class using handler)
This is the demo handler
/**
*
* Used for thread to thread communication.
* Used for non UI to UI Thread communication.
*
*/
public class DemoHandler {
public void handleMessage(Messages message){}
final public void sendMessage(final Messages message){
//Calling thread is platform dependent and shall change based on the platform
new Thread(new Runnable() {
#Override
public void run() {
synchronized (this) {
handleMessage(message);
}
}
});
}
}
This is simple message class
public class Messages {
public Object myObject;
//other hash map (key, values) and get data put data etc
}
This is simple user interface class demo code:
public class UIClass {
public UIClass(){
//INIT
}
void onClick(int id){
//Some Button is clicked:
//if id == sendParcel
//do
TransactionProcessor.getInstance().sendParcel(handler, "Objects");
}
DemoHandler handler = new DemoHandler(){
public void handleMessage(Messages message) {
//Inform the UI and Perform UI changes
//data is present in the messages
};
};
}
This is sample transaction processor class
public class TransactionProcessor {
public static TransactionProcessor getInstance(){
return new TransactionProcessor(); //for demonstration
}
//Various Transaction Methods which requires calling server using HTTP and process there responses:
public void sendParcel(final DemoHandler uiHander, String otherdetailsForParcel){
//INIT Code and logical code
//Logical Variables and URL generation
String computedURL = "abc.com/?blah";
DemoHandler serverConnectionHandler = new DemoHandler(){
#Override
public void handleMessage(Messages message) {
super.handleMessage(message);
//Process server response:
//create a new message for the UI thread and dispatch
Messages response = new Messages();
//add details to messages
//dispatch
uiHander.sendMessage(response );
}
};
new Thread(new ServerConnection(computedURL, serverConnectionHandler));
}
public void sendEmail(final DemoHandler uiHander, String otherdetailsForEmail){
//SAME AS SEND PARCEL WITH DIFFERENT URL CREATION AND RESPONSE VALIDATIONS
}
public void sendNotification(final DemoHandler uiHander, String otherdetailsForNotifications){
//SAME AS SEND PARCEL WITH DIFFERENT URL CREATION AND RESPONSE VALIDATIONS
}
}
This is a nasty one, and I recommend creating a subclass or something else.
Here's your answer, which is essentially the same, but at runtime. Proceed at your own risk:
Import this:
#import <objc/runtime.h>
And add this code to wherever:
- (void)methodName {
// whatever you want to do in there
}
And in your function:
Class subclass;
// Verifiy that you haven't created it already
subclass = objc_getClass("SampleClassSubclass");
if (!subclass) {
// Generate a new class, which will be subclass of your SampleClass
subclass = objc_allocateClassPair(subclass, "SampleClassSubclass", 0);
// Obtain the implementation of the method you want to overwrite
IMP methodImplementation = [self methodForSelector:#selector(methodName)];
// With that implementation, replace the method
class_replaceMethod(subclass, #selector(methodName), methodImplementation, "##:");
// Register the class you just generated
objc_registerClassPair(subclass);
}
SampleClass *obj = [[subclass alloc] init];
Not so easy to do in Objective-C, but this should work. It replaces the doSomething method of DemoInitAndOverride with its own implementation and returns a new instance of the class. Note however that once this has been done the new implementation remains in place for all new instances of the class, not just a single instance.
- (void)doSomething
{
NSLog(#"self doSomething called");
}
- (DemoInitAndOverride *)createObj
{
DemoInitAndOverride *obj = [[DemoInitAndOverride alloc] init];
SEL sel = #selector(doSomething);
Method theirMethod = class_getInstanceMethod([DemoInitAndOverride class], sel);
Method myMethod = class_getInstanceMethod([self class], sel);
theirMethod->method_imp = myMethod->method_imp;
return obj;
}

Why is this BeanPostProcessor needed in addition to a UserDetailsService in this Spring 3.0 authentication example?

I'm trying to understand a Spring 3.0 application which contains the following BeanPostProcessor implementation. What is this code needed for? I thought the UserDetailsService was sufficient for getting and setting the User account information.
#Service
public class UserPassAuthFilterBeanPostProcessor implements BeanPostProcessor
{
/**
* The username parameter.
*/
private String usernameParameter;
/**
* The password parameter.
*/
private String passwordParameter;
#Override
public final Object postProcessAfterInitialization(final Object bean, final String beanName)
{
return bean;
}
#Override
public final Object postProcessBeforeInitialization(final Object bean, final String beanName)
{
if (bean instanceof UsernamePasswordAuthenticationFilter)
{
final UsernamePasswordAuthenticationFilter filter = (UsernamePasswordAuthenticationFilter) bean;
filter.setUsernameParameter(getUsernameParameter());
filter.setPasswordParameter(getPasswordParameter());
}
return bean;
}
/**
* Sets the username parameter.
*
* #param usernameParameter
* the username parameter
*/
public final void setUsernameParameter(final String usernameParameter)
{
this.usernameParameter = usernameParameter;
}
/**
* Gets the username parameter.
*
* #return the username parameter
*/
public final String getUsernameParameter()
{
return usernameParameter;
}
/**
* Sets the password parameter.
*
* #param passwordParameter
* the password parameter
*/
public final void setPasswordParameter(final String passwordParameter)
{
this.passwordParameter = passwordParameter;
}
/**
* Gets the password parameter.
*
* #return the password parameter
*/
public final String getPasswordParameter()
{
return passwordParameter;
}
}
Yes, UserDetailsService is sufficient.
This BeanPostProcessor changes the names of username and password parameters in login request (i.e. names of fields in login form) - these properties can't be configured via namespace configuration, and using BeanPostProcessorss in order to customize such properties is an ugly but quite common practice.
This postProcessBeforeInitialization() method is implemented from BeanPostProcessor interface which automatically executes after your getter and setter methods finish executing
and once the postProcessBeforeInitialization() method finish execution, objects are initialized and then postProcessAfterInitialization() will execute.
These are something like life cycle methods.