calling Jersey REStfu web services by clients? - java

I have below RestFul web service method devleoped using Jersey.
#GET
#Produces ("application/xml")
public User validateAndReturn(User user) {
User als=null;
try {
als= UserService.validate(user);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return als;
}
Here User.java class is not generated from xsd and is handwritten. In this case how clients would call my web service? Do they need User.java and populate it through setters and getters?
Thanks!

You need to share User object details with your client. Choice is yours, in which way you do.
XML schema representation is used because that is language independent. It allows clients written in different technology to create their own input object confirming to the schema. Almost all the languages provide libraries to generate classes from xml these days.

Related

How can I migrate call to HttpMethodBase.setConnectionCloseForced(true) from commons-httpclient 3.x to httpcomponents-client 4.x?

I have some code that I need to migrate from commons-httpclient 3.x to httpcomponents-client 4.x (or newer). In some error handling code, there are calls to setConnectionCloseForced(true) on subclasses of HttpMethodBase, such as GetMethod or PostMethod. What would be the equivalent in httpcomponents-client 4.x?
HttpMethodBase httpMethod = /* some value */;
try {
// do something
} catch (Exception e) {
// handle error
} finally {
// how to convert this?
httpMethod.setConnectionCloseForced(true);
}

How do I create an Alfresco site programmatically from a repository webscript?

I've implemented an Alfresco repository webscript (in Java) to programmatically create a new site.
I notice that there's a SiteService interface which I thought could be used to do this -
SiteInfo site = siteService.createSite("site-dashboard", "mySite",
"mySite", "", SiteVisibility.PUBLIC);
However, this results in the creation of a non-functional site, and although it's visible within the Alfresco Share dashboard, I'm not able to use it.
I then came across this code sample, which is doing exactly what I want. BUT the code includes a section to do authentication, involving sending the user's login and password details to a dologin web service. Don't really want to do this.
But as the user has already logged in via Alfresco Share, they should already be authenticated.
If I call the create-site webscript from my code, as shown in the example (without the initial call to dologin), I'm getting a 401 (unauthorised) return code.
So my question is, how do I tell the create-site webscript about my authentication?
I read about using an authentication ticket here. Is this ticket stored in the session, and if so, how do I access it within my Java code? If I could get the ticket, then this would be sufficient to invoke the create-site webscript.
Update: I've added the alf_ticket parameter as suggested by the comment, but I'm still getting a 401 response.
My current code is:
public NodeRef createServiceChange(String serviceChangeName) {
HttpClient client = new HttpClient();
String ticket = authService.getCurrentTicket();
PostMethod createSitePost = new PostMethod("http://localhost:8081/share/service/modules/create-site");
JSONObject siteObject = new JSONObject();
try {
siteObject.put("shortName", serviceChangeName);
siteObject.put("visiblity", "Public");
siteObject.put("sitePreset", "site-dashboard");
siteObject.put("title", serviceChangeName);
siteObject.put("description", serviceChangeName);
siteObject.put("alf_ticket", ticket);
createSitePost.setRequestHeader("Content-Type", "application/json");
createSitePost.setRequestHeader("Accept", "application/json");
createSitePost.setRequestEntity(new StringRequestEntity(siteObject.toString(), "application/json", "UTF-8"));
int status = client.executeMethod(createSitePost);
System.out.println("create a site script status :: " + status);
if (status == HttpStatus.SC_OK) {
System.out.println("Site created OK");
}
else{
System.out.println("There is error in site creation");
}
} catch (JSONException err) {
err.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
So I've managed to successfully create a site, programmatically, and here's what I did:
First, forget about writing a repository (platform) webscript. Creation of sites in Alfresco is done by invoking a Share module, so you'll need to implement either a page, or custom menu item to create a site. I was also getting a lot of problems with authentication, but if you log in to the system via Alfresco Share, and in your Javascript, use the provided Alfresco Ajax request, then authentication shouldn't be a problem.
Here are the components I used:-
Create a Share page to create your site. In the Freemarker template (.ftl) add a form to collect the site details.
Attach a button on the form to the following Javascript function. Note that I cobbled this together from various code fragments on the web, so it could use some cleaning up. But it basically works for me -
function create_site()
{
var sc_form = document.forms.namedItem('sc_form');
var name = sc_form.elements.namedItem('name').value;
var url = Alfresco.constants.URL_CONTEXT + "service/modules/create-site";
Alfresco.util.Ajax.request({
method : Alfresco.util.Ajax.POST,
url : url,
dataObj: {
sitePreset: "site-dashboard",
visibility: "PUBLIC",
title: name,
shortName: name,
description: name
},
requestContentType: Alfresco.util.Ajax.JSON,
successCallback:
{
fn: function(res){
alert("success");
alert(res.responseText);
},
scope: this
},
failureCallback:
{
fn: function(response)
{
Alfresco.util.PopupManager.displayPrompt(
{
title: Alfresco.util.message("message.failure", this.name),
text: "search failed"
});
},
scope: this
}
});
}

How to use SOAP web service in User Interface?

I am doing web service now, and already succeed installing SOAP in my web service..
It is working perfectly when i "run as java application".. (I use eclipse as my environment)
Here is my client method:
public static void main(String[] args) {
LogbookSOAPServiceLocator locator = new LogbookSOAPServiceLocator();
try {
LogbookSOAP logbookSOAP = locator.getLogbookSOAPPort();
System.out.println(logbookSOAP.fetchLog("21").getDriverName());
} catch (ServiceException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
This succesfully work in console, can i use it anywhre in my user interface? like .jsp file?
Thanks!
Sure you can. At first you need to install web container to deploy your application. Then create web project. Step by step tutorial by Oracle based on Oracle WebLogic Server but you can use other one.
The simpliest way to using JSP Scriptlets and put all our logic in JSP page.
<%#page import="your imports here"%>
........
<%
LogbookSOAPServiceLocator locator = new LogbookSOAPServiceLocator();
try {
LogbookSOAP logbookSOAP = locator.getLogbookSOAPPort();
System.out.println(logbookSOAP.fetchLog("21").getDriverName());
} catch (ServiceException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
%>
But it is not really good way because as your know best practice is to avod code logic in JSP pages especially Scriptets JSP coding conventions. Better code it in java wrapper class which you can call from JSP and after executing it will return result to the page.

Java Google Youtube Data API:: Unauthorized

I wanted to upload a video on youtube using Java Google Data API. I got the following cod from the Google Data Api documentation to upload a video.The only thing i need to change in this code in Client ID and Porduct key. i am using followinf method to authenticate
YouTubeService service = new YouTubeService(clientID, developer_key);
Client key is my Google Email id , tried with with wasy,
only provided Username e,g. "sampleuser"
or complete Gmail id e.g. "sampleuser#gmail.com" or "smapleuser#googlemail.com"
i got developer key by logging my Google mail id as mentioned "smapleuser#googlemail.com"
but i always got following exception
com.google.gdata.util.AuthenticationException: Unauthorized
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:600)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:552)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
at com.google.gdata.client.media.MediaService.insert(MediaService.java:400)
at YouTube.videoUpload(YouTube.java:115)
at YouTube.main(YouTube.java:43)
here is my code for video Upload
YouTubeService service = new YouTubeService("sampleuser#gmail.com",
"fakegoogleapplicationidjsuttoshowthatimgivingidhere");
// YouTubeService service = new YouTubeService("My Application");
VideoEntry newEntry = new VideoEntry();
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent("My Test Movie");
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Autos"));
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("cars");
mg.getKeywords().addKeyword("funny");
mg.setDescription(new MediaDescription());
mg.getDescription().setPlainTextContent("My description");
mg.setPrivate(false);
mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "mydevtag"));
mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "anotherdevtag"));
newEntry.setGeoCoordinates(new GeoRssWhere(37.0,-122.0));
// alternatively, one could specify just a descriptive string
// newEntry.setLocation("Mountain View, CA");
MediaFileSource ms = new MediaFileSource(new File("D:\\maths.mp4")
, "video/quicktime");
newEntry.setMediaSource(ms);
// "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
String uploadUrl =
"http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
try {
VideoEntry createdEntry = service.insert(new URL(uploadUrl), newEntry);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
please help , unable to find solution. thank you so much..looking for response
Try to add
service.setUserCredentials("email_here", "password_here");

Using the content handler API (JSR 211) to open applications

I want to be able to launch native and J2ME applications through my application using the content handler API (JSR 211) on a Nokia 6212.
At the moment, I am unable to do so, as it always states that there is "No Content Handler Found" and throws a javax.microedition.content.ContentHandlerException.
At the moment, I am trying to get the phone to launch its browser and go to a certain website, just to test that I can use the framework. I have tried many different Invocation objects:
//throw exceptions
new Invocation("http://www.somesite.com/index.html",
"application/internet-shortcut");
new Invocation("http://www.google.co.uk","text/html");
// a long shot, I know
new Invocation("http://www.somesite.com/text.txt","text/plain");
// massive long shot
new Invocation("http://www.google.co.uk","application/browser");
//appears to download the link and content (and definitely does in the Nokia
// emulator) and then throws an exception
new Invocation("http://www.google.co.uk");
new Invocation("http://www.somesite.com/index.html");
Below is the code that I have been using, please bear in mind the parameters often changed to generate the different Invocation objects.
/*
* Invokes an application using the Content Handler API
*/
public void doInvoke(String url, String mime, String payload){
Registry register = Registry.getRegistry(this.getClass().getName());
Invocation invoke = new Invocation(url, mime, null, false,
ContentHandler.ACTION_OPEN);
boolean mustQuit = false;
try {
mustQuit = register.invoke(invoke);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (ContentHandlerException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(mustQuit){
this.quit();
}
}
Try this:
Registry register = Registry.getRegistry(this.getClass().getName());
You must call Registry.getRegistry for the MIDlet inheritor. Just use your MIDlet for getting the class name.

Categories