sending POJO to save on server using RESTful webservices - web-services

I am developing a Restful web service which allow user to set all parameters in POJO and send it to server side web service, then web service will store this data and return generated Id back to client. But my POJO has parent-child relationship that contain set of POJO, So how can I do this using RESTful web service. I also written a code to fetch data from server using web service and its working fine. But for this issue please help me.
Thanks.

I am not sure if I understood your question correctly. I guess some sample code will help. If you are using RestTemplate then serializing and deserializing will be done for you automatically. RestTemplate uses Jackson to parse JSON so you don't need to worry about parent/child relationship in your POJO.
So here is an example. There are 1000's of examples out there on internet. Thats how I learnt.
RestTemplate restclient = new RestTemplate();
Product product = restclient.getForObject(url,Product.class);
System.out.println(product.getCoupons().getName());
Where as product is (I completely made this up myself),
public class Product {
#JsonProperty("id")
private String id;
#JsonProperty("coupons")
private Coupons coupons;
#JsonProperty("id")
public String getId() {
return id;
}
#JsonProperty("id")
public void setId(String id) {
this.id = id;
}
#JsonProperty("coupons")
public Coupons getCoupons() {
return coupons;
}
#JsonProperty("coupons")
public void setCoupons(Coupons coupons) {
this.coupons = coupons;
}
}
public class Coupons {
#JsonProperty("name")
private String name;
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
}
Let me know if I misunderstood your question, I can update my answer accordingly.

Related

Ksoap2 client returned failed to connect to /192.168.15.56(port 1122) after 60000ms

I wrote a webservice in .net. I publish the service in IIS and started it. I also edited its bindings to connect to the 1122. In firewall i added inbound and outbound rules to access my port 1122. At this point i was able to open the webservice page in my android phones browser. I used ksoap2 library in my android code to access the .net service. I tested the service first on emulator and it worked fine. When i tried to test the same code on the phone it throws exception
failed to connect to /192.168.15.56(port 1122) after 60000ms.
This is the part of my code that controls the ip and calls my asynctask
String inputId=editText1.getText().toString();
//String params[]=new String[]{"10.0.2.2:1122",inputId};
String params[]=new String[]{"192.169.15.56:1122",inputId};
new MyAsyncTask().execute(params);
My class to process ksoap2 looks like this:
class MyAsyncTask extends AsyncTask<String, Void, String>
{
public String SOAP_ACTION= "http://threepin.org/findUserNameById";
public String OPERATION_NAME="findUserNameById";
public String WSDL_TARGET_NAMESPACE="http://threepin.org/";
public String SOAP_ADDRESS;
private SoapObject request;
private HttpTransportSE httpTransport;
private SoapSerializationEnvelope envelope;
Object response=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
SOAP_ADDRESS="http://"+params[0]+"/myWebService.asmx";
request=new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo pi=new PropertyInfo();
pi.setName("Id");
pi.setValue(Integer.parseInt(params[1]));
pi.setType(Integer.class);
request.addProperty(pi);
pi=new PropertyInfo();
envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
httpTransport=new HttpTransportSE(SOAP_ADDRESS,60000);
try
{
httpTransport.call(SOAP_ACTION,envelope);
response=envelope.getResponse();
}
catch (Exception e)
{
response=e.getMessage();
}
return response.toString();
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
mhandler.post(new Runnable() {
#Override
public void run() {
textView1.setText(result);
progressBar.setVisibility(View.GONE);
}
});
}
Yes my pc ip is 192.168.15.56 i double checked. here is my ip
The port is 1122. I can open it in my phones browser it looked like this
but instead of localhost 192.168.15.56 was shown any help! I could get.
I solved it i added in my web.config by default these were off so before doing this i could see local host and methods of my service in the mobile browser but not able to test them. Plus while concatination this instruction SOAP_ADDRESS= SOAP_ADDRESS="http://"+params[0]+"/myWebService.asmx";was messing up even though the path was same i was not able to open it instead of this "http://"+params[0]+"/myWebService.asmx" i hardcored the path and it worked the code is fine

How to consume other application webservice from MSDynamics CRM?

We want to integrate our site with MSDynamics CRM.To get data from our site to MSDynamics CRM,we want to call webservice of our site from MSDynamics CRM.How could we do this?We would be grateful if provided some example codes.
Try this May be helpful:
http://technet.microsoft.com/en-us/library/aa613627.aspx
http://msdn.microsoft.com/en-us/library/cc150838.aspx
use the link above may be helpful
I think create a web service that your site refer and using the Dynamics CRM sdk to do operation to CRM.
Example:
WCF
[ServiceContract]
public interface IService1
{
[OperationContract]
Guid CreateContact(String firstname, String lastname, String email);
}
Implementation using CRM SDK
public class Service1 : IService1
{
readonly IOrganizationService _service = new OrganizationService("CRMConnectionStringName");
public Guid CreateContact(string firstname, string lastname, string email)
{
var contact = new Entity("contact");
contact.Attributes["firstname"] = firstname;
contact.Attributes["lastname"] = lastname;
contact.Attributes["emailaddress1"] = email;
var contactId = _service.Create(contact);
return contactId;
}
}

How to open URL in new Browser from Silverlight Application

We have MVVM Silverlight application. I am trying to open web url from button click event which happen on client side viewmodel and through invoke method needs to open web url in new browser.
I am using Process.Start method as describe below in Server side code.
var URL = #"http://SiteSelect.aspx";
SecureString secure = new SecureString();
char[] passwordChars = Properties.Settings.Default.Password.ToCharArray();
//converting string to securestring...found from internet
foreach (char c in passwordChars)
{
secure.AppendChar(c);
}
Process.Start(URL,"",Properties.Settings.Default.User,secure,"agent");
this throws an error related to user name and password. I checked user name and password is correct. Anyone have solution or any other method I can able to use?
Thanks,
You create a helper class:
public static class CommonHelper
{
private class HyperlinkButtonWrapper : HyperlinkButton
{
public void OpenURL(string navigateUri)
{
OpenURL(new Uri(navigateUri, UriKind.Absolute));
}
public void OpenURL(Uri navigateUri)
{
base.NavigateUri = navigateUri;
base.TargetName = "_blank";
base.OnClick();
}
}
public static void OpenURL(string navigateUri)
{
new HyperlinkButtonWrapper().OpenURL(navigateUri);
}
}
Usage:
CommonHelper.OpenURL(#"http://SiteSelect.aspx");
You could use this as well :
using System.Windows.Browser;
var uri = new Uri("http://foo.fr");
HtmlPage.Window.Navigate(uri, "_blank");
Easiest way to pass credentials is to put them in the URL, however it's not very secured. Ie:
http://user:password#foo.fr

ServiceStack web services security

Hi I am new to working with Servicestack and have downloaded their very comprehensive bootstrapapi example and am working with it, but am still having some issues. The issue is with security, what is happening is I am getting 405 errors when trying to access the protected services. Using the authenticate service it appears that I am authenticating correctly. Please help and explain. Here is the code:
public class Hello
{
public string Name { get; set; }
}
public class AuthHello
{
public string Name { get; set; }
}
public class RoleHello
{
public string Name { get; set; }
}
public class HelloResponse
{
public string Result { get; set; }
}
The Services:
public class HelloService : ServiceBase<Hello>
{
//Get's called by all HTTP Verbs (GET,POST,PUT,DELETE,etc) and endpoints JSON,XMl,JSV,etc
protected override object Run(Hello request)
{
return new HelloResponse { Result = "Hello, Olle är en ÖL ål " + request.Name };
}
}
[Authenticate()]
public class AuthHelloService : RestServiceBase<AuthHello>
{
public object Execute(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
[RequiredRole("Test")]
public class RoleHelloService : RestServiceBase<RoleHello>
{
public object Execute(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
Here is the AppHost:
public class HelloAppHost : AppHostBase
{
//Tell Service Stack the name of your application and where to find your web services
public HelloAppHost() : base("Hello Web Services", typeof(HelloService).Assembly) { }
public override void Configure(Container container)
{
//Register all Authentication methods you want to enable for this web app.
Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {new CustomCredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
}));
container.Register<ICacheClient>(new MemoryCacheClient() { FlushOnDispose = false });
//register user-defined REST-ful urls
Routes
.Add<Hello>("/hello")
.Add<Hello>("/hello/{Name}")
.Add<AuthHello>("/AuthHello")
.Add<RoleHello>("/RoleHello");
}
}
UPDATE
Everything works as expect if you replace : RestServiceBase with : ISevice so now the question is why.
Check the wiki documentation first
I would first go through the documentation in ServiceStack's Authentication Wiki to get a better idea about how ServiceStack's Authentication works. There's a lot of documentation in the wiki, so if you're unsure of something you should refer to that first. It's a community wiki so feel free to expand whats there if you think it can help others.
Refer to the implementation in the source code if behavior is not clear
If you're unsure of what something does you should refer to the RequiredRole source code as the master authority as how it works. RequiredRole is just a Request Filter Attribute which gets run before every service that has the attribute.
The RequiredRole attribute just calls your session.HasRole() method as seen here:
public bool HasAllRoles(IAuthSession session)
{
return this.RequiredRoles
.All(requiredRole => session != null
&& session.HasRole(requiredRole));
}
Because it just calls your session you can override the implementation of session.HasRole() if you have a custom session.
Registering and Implementing a CustomUserSession
The Social BootstrapApi project does implement its own CustomSession that it registers here but does not override the HasRole() implementation so it uses the built-in implementation in the base AuthUserSession.HasRole() which simply looks like the Roles collection to see if the user has the specified role in their Session POCO:
public virtual bool HasRole(string role)
{
return this.Roles != null && this.Roles.Contains(role);
}
Session properties populated by AuthUserRepository
The Roles property (as well as most other properties on a users Session) is populated by the AuthUserRepository that you have specified e.g. if you're using the OrmLiteAuthRepository like SocialBootstrapApi does here than the Roles attribute is persisted in the Roles column in the UserAuth RDBMS table. Depending on the AuthUserRepository you use the UserAuth / UserOAuthProvider POCOs get stored as RDBMS tables in OrmLite or as text blobs in Redis, etc.
Manage roles and permissions with AssignRoles / UnAssignRoles services
So for a user to have the required role (and authorization to pass), it should have this Role added to its UserAuth db row entry. ServiceStack's AuthFeature includes 2 services for managing users permissions and roles:
/assignroles
/unassignroles
How to initially give someone the Admin Role
These services does require a user with the Admin Role to be already authenticated.
You can do this by manually changing a specific users UserAuth.Role column to include the value "Admin". The Social Bootstrap API project instead does this by handling the OnAuthenticated() event on its CustomUserSession that simply checks to see if the authenticated username is declared in the Web.Config and if it is, calls the AssignRoles service giving that authenticated user the Admin Role:
if (AppHost.Config.AdminUserNames.Contains(session.UserAuthName)
&& !session.HasRole(RoleNames.Admin))
{
var assignRoles = authService.ResolveService<AssignRolesService>();
assignRoles.Execute(new AssignRoles {
UserName = session.UserAuthName,
Roles = { RoleNames.Admin }
});
}

How can I retrieve the session ID from within a JAX-RS webservice?

I cannot figure out how to retrieve the session ID from a given JAX-RS webservice request. I assume it is available, but I do not know how to retrieve it.
I am NOT using CXF. I would be grateful for any assistance.
You can use the #Context annotation to get the current instance of the HttpServletRequest.
#Path("/session-id.txt")
public class SessionIdResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getSessionId(#Context HttpServletRequest request) {
return request.getSession(true).getId();
}
}