Restler not requiring required properties - restler

I have this for my object class and API class. I'm able to call post without sending a task_list_id or display_order. As long as I just pass title it's calling the method.
class BaseTaskObj
{
/// #var int $task_list_id The SQL ident of the Task List to use for the Task. {#min 1}{#required true}
public $task_list_id;
}
class PostTaskObj extends BaseTaskObj
{
/// #var int $assigned_id The SQL ident of the Person who this task is assigned to {#min 1}{#required false}
public $assigned_id;
}
class MyTaskAPI {
/**
* Creates a new Task associated with an existing task list.
*
* #param PostTaskObj $info The details of the Task object to create. {#required title, display_order}
*
* #status 201
*
* #return int The SQL ident of the newly created Task
*/
function post(PostTaskObj $info) {
}
}

task_list_id and assigned_id currently do not have valid phpdoc comments. They do not have any assigned value as well. This makes them the required parameters for the api call.
But then you have {#required title, display_order} which overwrites the required list with invalid parameters thus making them not required

Related

In my service integration, I found a NullPointerException when instantiating class of another service

I cannot seem to figure out in my service integration why my instantiation of the class of another service returns null even when I can see the class in the jar in the library.
Please see my code here:
public class OAuthFacadeClientImpl implements OAuthFacadeClient {
/**
* oauth facade
*/
private OAuthFacade supergwOauthFacade;
/** LOGGER */
private static final Logger LOGGER = LoggerFactory.getLogger(OAuthFacadeClientImpl.class);
#Override
public AccessTokenRevokeResult revokeToken(String merchantId, String userId,
String scope) {
AccessTokenRevokeRequest revokeRequest = new AccessTokenRevokeRequest();
revokeRequest.setAccessToken(userId);
revokeRequest.setClientId(merchantId);
revokeRequest.setExtRequestId(scope);
LogUtil.info(LOGGER, "revokeRequest value = " + revokeRequest);
AccessTokenRevokeResult revokeResult = supergwOauthFacade
.revokeToken(revokeRequest.getClientId(), revokeRequest.getAccessToken(),
revokeRequest.getExtRequestId());
SALResultChecker.checkAndAssert(revokeResult);
return revokeResult;
}
/**
* Setter method for property <tt>oAuthFacade</tt>.
*
* #param oAuthFacade value to be assigned to property miniAppQueryFacade
*/
public void setOAuthFacade(OAuthFacade oAuthFacade) {
this.supergwOauthFacade = oAuthFacade;
}
}
Breakpoints of my code upon debugging
You basically need to instantiate an object of type OAuthFacade prior to using this method revokeToken(...) and feed that reference using your setter method (e.i., setOAuthFacade(...)) so that supergwOauthFacade will not point to nothing and avoid getting NullPointerException. Good LUCK

Querying user profile repository ATG

I have added few custom properties on top of ATG's profile. When i want to read the profile values in jsp, i am just importing ATG profile and then accessing the property as profile.name.
I am facing one scenario where i need to return profile.lastName for one type of users and profile.firstName for other type of users. This is based on say profile.userType property.
Is it possible to add the userType check in repository so that when i read profile.name it should return either firstName or lastName.
Since name is referred in many places (1000) i cannot add the user type check everywhere and display name accordingly. So if possible, we can handle this in repo.
Yes you can. Simply use a RepositoryPropertyDescriptor. I hastily cobbled together a version below (not tested but should be enough to get you going):
import atg.repository.RepositoryItem;
import atg.repository.RepositoryItemImpl;
import atg.repository.RepositoryPropertyDescriptor;
public class AcmeRealUserName extends RepositoryPropertyDescriptor{
#Override
public Object getPropertyValue(RepositoryItemImpl profile, Object pValue) {
String userType = (String) profile.getPropertyValue("userType");
String lastName = (String) profile.getPropertyValue("lastName");
String firstName = (String) profile.getPropertyValue("firstName");
if ("firstNameUser".equals(userType)) {
return firstName;
} else {
return lastName;
}
}
#Override
public void setValue(String pAttributeName, Object pValue) {
//Probably Do Nothing since this is a derived property
}
/**
* A class specific logDebug method to output log messages. Unfortunately
* using System.out as the mechanism.
*
* #param pMessage
*/
protected void logDebug(String pMessage) {
System.out.println("### DEBUG(:" + getClass().getName() + getName() + ")" + pMessage);
}
}
You then refer to this new property in your userprofiling.xml as follow:
<property name="name" property-type="com.acme.propertydescriptor.AcmeRealUserName" item-type="string" writable="false" readable="true" />

How to synchronize “Check” Direct Menu Item’s selected state with preference in e4?

I have a “Check” Direct Menu Item contributed in my fragment.e4xmi. It’s selected state should reflect the value of a boolean preference. Setting the preference in the #Execute method works fine:
#Execute
public void execute(MMenuItem item, #Preference IEclipsePreferences preferences) {
preferences.putBoolean("selected", item.isSelected());
}
But initializing the DirectMenuItem’s selected state from the preference doesn’t work:
#PostConstruct
public void init(MMenuItem item, #Preference("selected") boolean selected) {
item.setSelected(selected);
}
When the #PostConstruct method is called, the MMenuItem linked with the handler is not yet present in the current context.
Also, moving the setSelected call into #CanExecute doesn’t seem to work; the change made there is not reflected in the UI.
So, how to solve this issue (linking the selected state of a menu item with a boolean preference) in e4?
Doing this in #CanExecute works when using a Handled Menu Item rather than Direct Menu Item. Some UI things don't seem to work well in Direct handlers.
Following up to your question and the discussion in https://dev.eclipse.org/mhonarc/lists/e4-dev/msg09498.html I implemented the following solution for a DirectToolItem.
#Inject
public void initialize(EModelService modelService, MPart part){
MUIElement toolItem = modelService
.find("a.b.c.d.toolitemId", part.getToolbar());
isActive = ((MDirectToolItem) toolItem).isSelected();
}
The #Inject method gets called once, and I know the location of the MDirectToolItem resp. I can inject the part. This seems to suffice to synchronize the e4 application model and my model.
For the record, I've come up with the following add-on:
/**
* The basis for an add-on which synchronizes the {#linkplain MItem#isSelected()
* selection state} of {#link MItem}s tagged with one of the tags passed to
* {#link ItemSelectionSynchronizationAddonBase#ItemSelectionSynchronizationAddonBase(String...)}
* with some external source.
* <p>
* Subclasses need to implement {#link #getSelection(String)} to retrieve the
* desired selection state for a given tag.
*/
public abstract class ItemSelectionSynchronizationAddonBase {
private EModelService modelService;
private MApplication application;
private final List<String> tags;
public ItemSelectionSynchronizationAddonBase(String... tags) {
this.tags = new ArrayList<>(asList(tags));
}
/**
* Injects all objects necessary to work with the E4 Application Model. Not done
* in the constructor simply to keep subclasses unburdened by the knowledge
* about the exact objects needed.
*/
#PostConstruct
public void injectUiModel(EModelService modelService, MApplication application) {
this.modelService = modelService;
this.application = application;
}
/**
* Synchronizes the selection state of all {#link MItem}s found in the
* Application Model when startup is complete. This does <strong>not</strong>
* include items that exist only in part descriptors, but no concrete parts yet.
* These items will be synchronized when the part gets created and
* {#link #partActivated(Event)}.
*/
#Inject
#Optional
public void applicationStartupComplete(
#EventTopic(UIEvents.UILifeCycle.APP_STARTUP_COMPLETE) #SuppressWarnings("unused") Event event) {
synchronizeSelections(application, tags,
EModelService.ANYWHERE | EModelService.IN_MAIN_MENU | EModelService.IN_PART);
}
/**
* Synchronizes the selection state of all {#link MItem}s found in the
* Application Model for the part that was just activated.
*/
#Inject
#Optional
public void partActivated(#EventTopic(UIEvents.UILifeCycle.ACTIVATE) Event event) {
MPart part = (MPart) event.getProperty(UIEvents.EventTags.ELEMENT);
synchronizeSelections(part, tags, EModelService.IN_PART);
}
/**
* Synchronizes the selection state of all {#link MItem}s with the given tags.
* Should be called by the subclass when the value changes in the external
* source.
*/
protected void synchronizeSelections(List<String> tags) {
synchronizeSelections(application, tags,
EModelService.ANYWHERE | EModelService.IN_MAIN_MENU | EModelService.IN_PART);
}
private void synchronizeSelections(MUIElement searchScope, List<String> tags, int searchFlags) {
List<MItem> items = modelService.findElements(searchScope, null, MItem.class, tags, searchFlags);
for (MItem item : items) {
for (String tag : tags) {
if (item.getTags().contains(tag)) {
item.setSelected(getSelection(tag));
}
}
}
}
/** Gets the current selection state associated with the given tag. */
protected abstract boolean getSelection(String tag);
}
Subclasses can then override getSelection to, e.g., use the tag as a basis for retrieving a preference or (as is done in my code) getting the value from a Java bean. Just note that getSelection takes only care of one sync direction (pull). The subclass will also need to call synchronizeSelections whenever an event occurs that necessitates a UI update (push, e.g., caused by a PropertyChangeEvent).

Exception : Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL

I am not able to authenticate in symfony2 with the 'Employee' entity as it contains many mapping with other entities in my project. some of my mapping is as follows:
/**
* #var EmployeeDesignation
*
* #ORM\ManyToOne(targetEntity="EmployeeDesignation")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="employee_designation_id", referencedColumnName="id")
* })
*/
private $employeeDesignation;
/**
* #var EmployeeDesignation
*
* #ORM\ManyToOne(targetEntity="EmployeeType")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="employee_type_id", referencedColumnName="id")
* })
*/
private $employeeType;
Authentication works fine without any mapping. I have tried with 'Serialize()' and 'Unserialize()' methods in it like below:
class Employee implements AdvancedUserInterface, \Serializable {
/**
* serialize the username
* #return serialize
*/
public function serialize() {
return serialize($this->emailOfficial);
}
/**
* unserialize
* #param $data
*/
public function unserialize($data) {
$this->em = unserialize($data);
}
}
I am getting the following error after doing the above method:
You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine.
I have tried this way so as to get rid of the previous error, which is as follows:
Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL
So, can anybody please suggest a way to overcome from this problem?
I have encountered something similar, and after some research, I tried the same things as you did.
But at some point, I found out that by setting the __sleep method, every thing worked fine.
class User implements PlayerInterface
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
...
public function __sleep()
{
return array('id');
}
...
Make sure that the field which is defined as #ORM\Id is part of the returned array.
Make sure to drop the browser cookie, since it uses the session.
I don't know exactly why it causes this when setting up a new association (mine was a ManyToMany), but It probably originate from this place:
// see Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse()
...
$event->getRequest()
->getSession()
->set('_security_'.$this->contextKey, serialize($token));
...
Hope this could help someone.
Edit:
References:
http://forum.symfony-project.org/viewtopic.php?f=23&t=35764
http://translate.google.com/translate?hl=en&sl=es&u=http://jonsegador.com/2012/03/error-con-symfony2-you-cannot-refresh-a-user-from-the-entityuserprovider-that-does-not-contain-an-identifier/
For me only this worked:
class User implements UserInterface
to
class User implements UserInterface, \Serializable
and I needed to add following methods to User class:
public function serialize() {
return serialize($this->username);
}
public function unserialize($data) {
$this->username = unserialize($data);
}
There is another possibility to solve this issue. You have to make the visibility of all properties of the entities which are associated with your user to 'protected'
See: http://www.metod.si/symfony2-error-usernamepasswordtokenserialize-must-return-a-string-or-null/
You should put "protected" in every variable of your user class. At least for me that work :)

Design choices to remove if-is statements

Say i have a class hierarchy of domain objects with one base class and a couple of child classes, one level.
Let say I have a list of those objects (list of the base class) and I want to apply some logic to the classes that I feel don't really belong to the classes (eg. design/UI specific code).
What are my alternatives ?
If-is statement. Personally this one shouldn't even be considered as an alternative but i write it anyway.
Polymorphism. This one is actually an alternative in some cases but with my example above, I don't want my classes to contain any UI specifics.
Resolving some logic method via reflection/IoC container based on the type of the object.
Eg C#. Type type = typeof(ILogic<>).MakeGenericType(domainObject.GetType());
I really like this one, I don't get any compile time checks though if an implementation is missing for a sub class, or is that possible somehow?
Visitor pattern. Will work but seemes kind of overkill to apply on a structure thats only one level deep.
Anyone has any other tips or tricks to solve these kinds of problems?
Great question. Problem is that there are many solutions and most of them will work.
I work with MVC a lot, similar situation happens quite often. Especially in the view, when similar rendering needs to happen across some views... but does not really belong to the view.
Let's say we have child class ChildList that extends BaseList.
Add a property uiHandler in the child class. Overload the rendering function, let's say toString(), and use the uiHandler with your specific UI/Design things.
I wrote a little something, it is in PHP... but you should be able to get an idea. It gives you freedom to chose how your objects will be displayed and flexibility to use specific UIs for specific objects.
Look at the code below, it seems like a lot but int's not that bad.
BaseList - your base class
BaseListUIExtended - base class that uses UI, takes optional UI class as constructor parameter. In C# 4 you can use optional, otherwise use 2 constructors.
UIBase - interface for UI classes...
UIChildSpecific - UI class
ChildList - child class that can use UI or not, because of BaseListUIExtended optional constructor parameter.
Define interface
/**
* Base UI interface
*/
interface IUIBase {
/**
* Renders the Base Class
*
* #param UIBase $obj
* #return string
*/
public function render($obj);
}
Define base classes, child class
//**************************************************************
// Define Base Classes
//**************************************************************
/**
* Base Class
*/
class BaseList {
/**
* List of items
* #var array
*/
protected $_items = array();
/**
* Gets collection of items
*
* #return array
*/
public function getItems() {
return $this->_items;
}
/**
* Adds new item to the list
* #param object $item
*/
public function add($item) {
$this->_items[] = $item;
}
/**
* Displays object
*/
public function display() {
echo $this->toString();
}
/**
* To String
*/
public function __toString() {
// Will output list of elements separated by space
echo implode(' ', $this->_items);
}
}
/**
* Extended BaseList, has UI handler
* This way your base class stays the same. And you
* can chose how you create your childer, with UI or without
*/
class BaseListUIExtended extends BaseList {
/**
* UI Handler
* #var UIBase
*/
protected $_uiHandler;
/**
* Default Constructor
*
* #param UIBase Optional UI parameter
*/
public function __construct($ui = null) {
// Set the UI Handler
$this->_uiHandler = $ui;
}
/**
* Display object
*/
public function display() {
if ($this->_uiHandler) {
// Render with UI Render
$this->_uiHandler->render($this);
} else {
// Executes default BaseList display() method
// in C# you'll have base:display()
parent::display();
}
}
}
//**************************************************************
// Define UI Classe
//**************************************************************
/**
* Child Specific UI
*/
class UIChildSpecific implements UIBase {
/**
* Overload Render method
*
* Outputs the following
* <strong>Elem 1</strong><br/>
* <strong>Elem 2</strong><br/>
* <strong>Elem 3</strong><br/>
*
* #param ChildList $obj
* #return string
*/
public function render($obj) {
// Output array for data
$renderedOutput = array();
// Scan through all items in the list
foreach ($obj->getItems() as $text) {
// render item
$text = "<strong>" . strtoupper(trim($text)) . "</strong>";
// Add it to output array
$renderedOutput[] = $text;
}
// Convert array to string. With elements separated by <br />
return implode('<br />', $renderedOutput);
}
}
//**************************************************************
// Defining Children classes
//**************************************************************
/**
* Child Class
*/
class ChildList extends BaseListUIExtended {
// Implement's logic
}
Testing...
//**************************************************************
// TESTING
//**************************************************************
// Test # 1
$plainChild = new ChildList();
$plainChild->add("hairy");
$plainChild->add("girl");
// Display the object, will use BaseList::display() method
$plainChild->display();
// Output: hairy girl
// Test # 2
$uiChild = new ChildList(new UIChildSpecific());
$uiChild->add("hairy");
$uiChild->add("girl");
// Display the object, will use BaseListUIExtended::display() method
$uiChild->display();
// Output: <strong>hairy</strong><br /><strong>girl</strong>