Jersey : How to send /pass Custom DTO to a Service class in Jersey - rest

I am using Jersey Framework for developing my Webservices. I have a DTO object named UserInfo with setters and getters inside it. I am setting this DTO value initially when the user logs in. How can I pass this user-specific DTO to a Jersey service class?
I have tried setting them inside MultivaluedMap and Form but I was out of luck making it work.
This is my code :
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("queryTerm", "userdto");
Form f = new Form();
f.add("name", "1001D");
And this is the way I am trying to retrieve the Data.
public class HaiService {
#GET
#Produces("application/json")
#Consumes("application/json")
public String sayPlainTextHello(#Context UriInfo ui) {
MultivaluedMap queryParams=ui.getQueryParameters();
Iterator it=queryParams.keySet().iterator();
String theKey=null;
String returnString="";
while(it.hasNext()) {
theKey=(String)it.next();
System.out.println(queryParams.getFirst(theKey));
}
System.out.println("I am called");
return "Hi";
}
But I was out of luck. Typically my requirement is to store user-specific data on logon, and then retrive that inside the service class.
I am avoiding storing data in session because a user might login with multiple ID's under one browser, which produces the same session id, and there is a chance of data being overwritten for the first logged in user.

Related

Liferay 7.2 Api Rest Session parameter

I have Liferay 7.2.
I created a module rest.
It is possibile to save a variable in session ad use it in other method?
My idea of code is:
#GET
#Path("/save/paramt")
public String jsonSaveParamRequest() throws Exception {
String json = "xx";
//SAVE IN SESSION json
return "ok";
}
#GET
#Path("/get/paramt")
public String jsonGetParamRequest() throws Exception {
String xx= SESSION VARIABLE json
return xx;
}
Saving state in a HTTP session in a REST API is not recommended and should be avoided. Please refer to the discussions here SO:how-to-understand-restful-api-is-stateless.
Technically, I guess this is possible as you can inject the HttpServletRequest as a method param via #Context HttpServletRequest request to your annotated method and use getSession(). But I am not sure if you can rely on that.

Is it possible for a restful webservice to have a parameter in the url?

I was instructed to create webservices ( with Spring-Boot ). My colleague gave me the url of the webservice and it looks like this : http://172.20.40.4:8080/Oxalys_WS/stock/ITM=1559
In general we create a RestController with the url :
#RestController
#RequestMapping("stock")
public class StockController {
#Autowired
private StockService stockService;
#GetMapping(value = "/{code}", produces = "application/json")
public JsonModel getByCode(#PathVariable String code) {
JsonModel jsonModel = new JsonModel();
final Map<String, Object> data = new HashMap<>();
List<Stock> stock = stockService.getByCode(code);
data.put("stock", stock);
data.put("stockTotal", stockService.getTotal(code));
jsonModel.setDatas(data);
return jsonModel;
}
}
So is it normal to create a Restful Spring-Boot webservice with a parameter in the url ?
Spring provides parameter in two standard way.
Query Param : http://172.20.40.4:8080/Oxalys_WS/stock?ITM=1559
Path Variable : http://172.20.40.4:8080/Oxalys_WS/stock/1559
Query Param :- It is a typical old way to pass some value as QueryParam with using of some variable starts with ?(Question Mark) and value is assigned using =(equals).
PathVariable :- this is a newer pattern introduce for REST-api Services. URL must be structured such in a way that this should not look too messy if multiple parameters need to pass within a URL.
For more info Navigate this link
Yes, you can have the one in your URL
When you are required to have the path variable, you can give in the Request URL

ASP MVC EF6 Code first Multi tenant get tenant id

we keep fighting with out multi tenant application.
This is an ASP MVC EF6 Code First web application.
We initialize a list of tenants in the Application_Start, getting a pair of values:
Host
TenantId
So we can associate any host with one TenantId, and store that list in cache.
We have configured a custom filter to get the current tenant.
public class TenantActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Items.Add("TenantId", GetCurrentTenant(filterContext.HttpContext.Request.Url.Host));
base.OnActionExecuting(filterContext);
}
}
The GetCurrentTenant function just access the list in cache and get the current one based on the host passed.
Is it correct to store the current tenant in an item in the context?
After that, we have created an Interceptor to get any query and add a filter to filter by TenantId. This is done and working good, we just need to add the tenantId from the context:
The problem we have is where we get the TenantId for each request.
if (HttpContext.Current.CurrentHandler == null) return;
var clientId = Convert.ToInt32(HttpContext.Current.Items["ClientId"]);
foreach (DbParameter param in command.Parameters)
{
if (param.ParameterName != TenantAwareAttribute.TenantIdFilterParameterName)
continue;
param.Value = clientId;
}
We don't know if this is the correct approach since there is a lot of informationon the net.
Thanks.
In my experience, the persistence of the tenant Id in the HTTP context is not right, as in some cases, the HTTP context becomes null.
You can try to get the tenant Id from the claims of the current principal. Creating a static class with a tenant identifier property that reads from the claims and gives is more reliable. Assuming you are using the owin pipeline, this should be easy to do. You can take a look at the reference sample application from github here
It looks like the below block,
public static class UserContext
{
public static string TenantId
{
get
{
return Threading.Thread.CurrentPrincipal.FindFirst("tenantid");
}
}
}

Error Generating XML Document from object

I am wishing to serialize a complex object for returning from a web service request. Here are my assumptions. I need to have the serialized (deflated) object in an XML document (as opposed to a string) before returning to the calling client. I "believe" I am deserializing just fine it is just a matter of getting it loaded into the XMLDocument. However I could be wrong and the deserialization may be wrong therefore the XmlDocument blows up. Here is the code:
My Complex Object:
namespace ABCTest
{
[XmlRoot("TapRoot")]
public class UserDetails
{
[XmlElement]
public String AccountName { get; set; }
}
}
My serialization code:
FYi: UsrDtls == List<UserDetails>
XmlSerializer Obj2XML = new XmlSerializer(UsrDtls.GetType());
Stream strWriter = Stream.Null;
XmlWriter XWriter = new XmlTextWriter(strWriter, Encoding.Unicode);
XmlDocument XDoc = new XmlDocument();
Obj2XML.Serialize(XWriter, lst_Exercises);
string abc = Obj2XML.ToString(); //debugging line to attempt to browse the obj2xml object
XDoc.LoadXml(abc);
return XDoc;
I have no idea where you learned about web services in .NET. Just return the object. The web service infrastructure will take care of it.
You don't say whether you're using WCF services or the legacy ASMX services. The ASMX services should not be used for new development.
If you still have trouble when you "just return it", then please post the details of any exceptions you receive.

Dependency Injection & Model Binding (ASP MVC, Autofac), When to use what?

This is more like a conceptual question. When to use Model Binding (in ASP.NET MVC Framework) and when to inject objects using IoC (lets say Autofac here) ?
One specific scenario is like lets say, I have the following action method
public ActionResult EditProfile(string UserId)
{
// get user object from repository using the the UserId
// edit profile
// save changes
// return feedback
}
In the above scenario, is it possible to inject a user object to action method such that it automatically gets the user object using the UserId ? The resulting signature being:
public ActionResult EditProfile(UserProfile userObj) //userObj injected *somehow* to automatically retreive the object from repo using UserId ?
Sorry if it all doesn't makes sense. It`s my first time using IoC.
EDIT:
This is the way to do it > http://buildstarted.com/2010/09/12/custom-model-binders-in-mvc-3-with-imodelbinder/
You can do what you need using a custom action filter. By overriding OnActionExecuting, we have access to the route data, and the action parameters of the action that will be executed. Given:
public class BindUserProfileAttribute : ActionFilterAttribute
{
public override OnActionExecuting(FilterContext filterContext)
{
string id = (string)filterContext.RouteData.Values["UserId"];
var model = new UserProfile { Id = id };
filtextContext.ActionParameters["userObj"] = model;
}
}
This attribute allows us to create the parameters that will be passed into the action, so we can load the user object at this point.
[BindUserProfile]
public ActionResult EditProfile(UserProfile userObj)
{
}
You'll probably need to get specific with your routes:
routes.MapRoute(
"EditProfile",
"Account/EditProfile/{UserId}",
new { controller = "Account", action = "EditProfile" });
In MVC3 we get access to the new IDepedencyResolver interface, which allows us to perform IoC/SL using whatever IoC container or service locator we want, so we can push a service like a IUserProfileFactory into your filter, to then be able to create your UserProfile instance.
Hope that helps?
Model binding is used for your data. Dependency injection is used for your business logic.