Interface query parameter parsing? - rest

I believe this is not possible, but I just wanted to verify.
I would like to do something like...
#Path("/awesome")
public class MyRestResource {
#GET
public void coolQuery(#QueryParam("user") User) {
// ...
}
}
public interface User {
String name();
Address address();
}
(Please don't comment on the example... it's completely made-up and not my use case.)
I imagine this is not possible because Jersey/JAX-RS generally requires a static method public static T valueOf(String input) which obviously is not possible with interfaces.
That said, is there any work-around for this to have a query parameter be an interface? And if so, how do you specify the parser / parsing logic?
Thanks

According to the documentation there are more ways than just the static valueOf method:
Be a primitive type;
Have a constructor that accepts a single String argument;
Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String) and java.util.UUID.fromString(String));
Have a registered implementation of javax.ws.rs.ext.ParamConverterProvider JAX-RS extension SPI that returns a javax.ws.rs.ext.ParamConverter instance capable of a "from string" conversion for the type. or
Be List<T>, Set<T> or SortedSet<T>, where T satisfies 2 or 3 above. The resulting collection is read-only.
The solution using a ParamConverterProvider should work in this case.

Related

Microsoft Bond System.Object

I need to ensure the following class is serializable by Microsoft Bond. I am struggling to find a way to do this due to the inclusion of the object member.
public class BondRemotingRequestMessageBody : IServiceRemotingRequestMessageBody
{
public object Value;
public BondRemotingRequestMessageBody()
{
}
public BondRemotingRequestMessageBody(int parameterInfos)
{
}
public void SetParameter(int position, string paramName, object parameter)
{
Value = parameter;
}
public object GetParameter(int position, string paramName, Type paramType)
{
return Value;
}
}
Is there a way around this?
This is for an Azure Service Fabric ASR implementation.
Thanks in advance.
I don't know about the Service Fabric parts, but from a Bond perspective, all of the fields that are to be serialized must be known to Bond and must be a type (or convertible to a type) that can be serialized. In practice, this means that all of the data structures that you need to serialize is expressed in a collection of .bond files.
The closest to C#'s object would be a bonded<bond.Void> field that you later deserialize as the proper well-known derived type. You would need to include (or be able to infer/derive) the correct derived type. The polymorphic container example demonstrates this pattern; it uses an enum field in a base struct to carry the derived type information.

Get Annotation Parameter with AspectJ

I read many question in this forum but nothing works.
public #interface MyAnnotation {
String value() default "";
Class[] exceptionList;
}
#MyAnnotation(value="hello", exceptionList={TimeOutException.class})
public void method() {}
#Aspect
public class MyAspect {
#Around("#annotation(MyAnnotation)")
public Object handle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) {
System.out.println(myAnnotation.exceptionList); // should print out TimeOutException
}
}
How can I get the value and the exceptionList of the #MyAnnotation while executing the advice?
I'm using Spring 4.0.6, AspectJ 1.7.4
The solution for this is making sure the advice method's parameter name match the parameter name in AspectJ expression. In my case, the advice method should look like this:
#Aspect
public class MyAspect {
#Around("#annotation(myAnnotation)")
public Object handle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) {
System.out.println(myAnnotation.exceptionList); // should print out TimeOutException
}
}
You are already almost there. Probably.
You are using the correct way to retrieve the annotation, so you have the values available.
Your problem - if I interpret the very minimalistic problem description(!) you only provide via the comment in your code snippet(!) correctly - is the (wrong) assumption that sticking an array of the type Class into System.out.println() will print out the names of the Classes it contains. It does not. Instead it prints information about the reference:
[Ljava.lang.Class;#15db9742
If you want the names of the Classes, you will have to iterate over the elements of that array and use .getName(), .getSimpleName() or one of the other name providing methods of Class.
Further information on how to print elements of an array is here:
What's the simplest way to print a Java array?
Granted, this whole answer could be entirely besides the point if the problem is that you are getting null values from the annotation fields. But since you have not provided an adequate problem description ("nothing works" is not a problem description!), we can only guess at what your problem is.

Entity Framework Object not allowing Connection String to be passed as parameter

I am trying to initialize an Entity object (ADO.NET EF Object), but it does not allow me to choose what connection string I want to use. I need to change connection string in order to give different access levels to users.
There are no overrides in the Entities Object, just a parameterless constructor.
If anyone can give me any pointers, it is appreciated.
If you have used the designer to generate an .edmx file for you, you will have something like below:
public MyEntities() : base("name=MyEntities", "MyEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
This will by default, get the connection string from your configuration file.
What you could do in this case is set the connection string
public partial class MyEntities
{
partial void OnContextCreated()
{
//Dynamically Building a Connection String
this.Connection.ConnectionString = "myconnectionstring";
}
}
Bear in mind though that this will first use the base constructor to pull the connection string from config, then set it with your custom version, basically overriding the connection string. This is typically good when you always want a default connection string.
Another option if you want a bit more control, is pass the connection string in via the constructor as shown below:
public partial class MyEntities
{
public MyEntities(string connectionString) :
base(connectionString,"MyEntities")
{
this.OnContextCreated();
}
}
Now you are passing in the connection string down to the base class and this is the only one it will use. This does mean however that you will most often need to supply this each time.
Hope this helps...

Proper place for human-readable representation of entity-based key

First some background. We recently converted from a Zend_Db_Table-based solution to entity-based solution (Doctrine). As our application grew, the table classes grew uglier and uglier. Some of the tables used ENUM columns to store string-based keys, which were converted into human-readable strings with static methods. Something like this:
public static function getProductType($productKey)
{
if (!array_key_exists($productKey, self::$productTypes)) {
return null;
}
return self::$productTypes[$productKey];
}
public static function getProductTypes()
{
return self::$productTypes;
}
In moving to the entity-based system, I tried to avoid static methods where possible. I moved the key to value translations into a view helper and called it a day. In the end, I found that it was not sufficient, as we needed to return them in JSON objects, which occurred outside of the presentation layer (i.e. no direct access to view helpers).
Does anyone have any theories on the proper place for these types of methods? Should I create separate objects for doing the translation from key to human-readable value, implement static methods on the entity object, or something else?
Well my theory is that this should be done in the model itself. But sometimes when dealing with a complex model, I like to create a separate class that handles any special "presentation" of that model. It takes the model as an argument and encapsulates the presentation logic.
So using your example, perhaps something like this:
class Model_Product
{
public static function getAllTypes()
{
return array(/* key-value pairs */);
}
//returns non human readable value
public function getType()
{
return $this->_type;
}
}
class Model_Product_Presenter
{
protected $_model;
public function __construct(Model_Product $model)
{
$this->_model = $model;
}
//returns human readable value
public function getType()
{
$types = $this->_model->getAllTypes();
if (!array_key_exists($this->_model->type, $types)) {
return null;
}
return $types[$this->_model->type];
}
public function getDateCreated($format = "Y-m-d")
{
return date($format,$this->_model->timestamp);
}
}
You can go further and create a base presenter class to define any common tasks, i.e. converting timestamps to dates, formatting numbers, etc.
Update:
For anonymous access to a list of product types, I don't see any harm in making it the responsibility of the product model via a static method. Not all static methods are evil. In my opinion, the use of static methods for this purpose is fine, because it declares a global constant.
In a more complex scenario, I would delegate this responsibility to a separate class like Model_ProductType. Here is an example of such a complex model in production:
https://github.com/magento/magento2/blob/master/app/code/core/Mage/Catalog/Model/Product/Type.php

how can pass T dynamicaly in Ilist<T>?

i have a question.i have a method (Filter),i want to pass T dynamic.but it dosen`t accept.how can i do it?
public List<T> Filter<T>(string TypeOfCompare)
{
List<T> ReturnList2 = new List<T>();
return ReturnList2;
}
IList MakeListOfType(Type listType)
{
Type listType1 = typeof(List<>);
Type specificListType = listType.MakeGenericType(listType1);
return (IList)Activator.CreateInstance(specificListType);
}
Filter < ConstructGenericList(h) > ("s");
IList MakeListOfType(Type listType)
{
Type listType1 = typeof(List<>);
Type specificListType = listType.MakeGenericType(listType1);
return (IList)Activator.CreateInstance(specificListType);
}
It should be the other way round, you should call MakeGenericType on the generic type definition, not on the generic type argument. So the code becomes this:
IList MakeListOfType(Type elementType)
{
Type listType = typeof(List<>);
Type specificListType = listType.MakeGenericType(elementType);
return (IList)Activator.CreateInstance(specificListType);
}
(note that I changed the variables names to make the code clearer)
Generic parameters must have a type able to be determined at compile time (without resorting to something like functional type inference that some other languages have). So, you can't just stick a function between the angle brackets to get the type you want.
Edit:
Now that I know what you're trying to do, I would suggest a different approach entirely.
You mention that you are using Entity Framework, and you are trying to use one method to get a list of different types of objects. Those objects -- like Student and Teacher -- must have something in common, though, else you would not be trying to use the same method to retrieve a list of them. For example, you may just be wanting to display a name and have an ID to use as a key.
In that case, I would suggest defining an interface that has the properties common to Student, Teacher, etc. that you actually need, then returning a list of that interface type. Within the method, you would essentially be using a variant of the factory pattern.
So, you could define an interface like:
public interface INamedPerson
{
int ID { get; }
string FirstName { get; }
string LastName { get; }
}
Make your entities implement this interface. Auto-generated entities are (typically) partial classes, so in your own, new code files (not in the auto-generated code files themselves), you would do something like:
public partial class Student : INamedPerson
{
public int ID
{
get
{
return StudentId;
}
}
}
and
public partial class Teacher : INamedPerson
{
public int ID
{
get
{
return TeacherId;
}
}
}
Now, you may not even need to add the ID property if you already have it. However, if the identity property in each class is different, this adapter can be one way to implement the interface you need.
Then, for the method itself, an example would be:
public List<INamedPerson> MakeListOfType(Type type)
{
if (type == typeof(Student))
{
// Get your list of students. I'll just use a made-up
// method that returns List<Student>.
return GetStudentList().Select<Student, INamedPerson>(s => (INamedPerson)s)
.ToList<INamedPerson>();
}
if (type == typeof(Teacher))
{
return GetTeacherList().Select<Teacher, INamedPerson>(t => (INamedPerson)t)
.ToList<INamedPerson>();
}
throw new ArgumentException("Invalid type.");
}
Now, there are certainly ways to refine this pattern. If you have a lot of related classes, you may want to use some sort of dependency injection framework. Also, you may notice that there is a lot of duplication of code. You could instead pass a function (like GetStudentList or GetTeacherList) by doing something like
public List<INamedPerson> GetListFromFunction<T>(Func<IEnumerable<T>> theFunction) where T : INamedPerson
{
return theFunction().Select<T, INamedPerson>(t => (INamedPerson)t).ToList<INamedPerson>();
}
Of course, using this function requires, once again, the type passed in to be known at compile time. However, at some point, you're going to have to decide on a type, so maybe that is the appropriate time. Further, you can make your life a little simpler by leaving off the generic type at method call time; as long as you are passing in a function that takes no arguments and returns an IEnumerable of objects of the same type that implement INamedPerson, the compiler can figure out what to use for the generic type T.