How to Create a Restful service for already available site - java

I have some API web site which will generate some JSON data but I can't access that data directly with that URL (if I try to access it says oauth error) so for that I have a secret key and lib file which throws that exception.
So I want to create a Restful web service for that ,...
without the restful service, I am accessing the data from a class file which invoked in main() method and if I run it as java application I am getting data at console,.. hence it has main method,..
but I need to build a Restful web service,. and retrieve the data in mobile windows/iPhone/android
I know what is Restful service But I don't know how get that data java file data,.. which is at console,...to Restful service

Try this
you have code the below stuff in your webservice method
public String myMethos(){
String urlString="http://example.com/WS/StaticExample.php?method=sayHello&name=World";
URL url=new URL(urlString);
URLConnection connection=url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.close();
JSONObject jsonobj = null;
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodedString="",URLstrJson="";
while ((decodedString = in.readLine()) != null) {
URLstrJson+=decodedString;
}
Say your value of URLstrJson is as shown below
{
"worldpopulation":
[
{
"rank":1,
"country":"China",
"population":"1,354,040,000",
"flag":"http://www.androidbegin.com/tutorial/flag/china.png"
}
]
}
Then,
jsonobj=new JSONObject(URLstrJson);
System.out.println(jsonobj.toString());
return jsonobj.toString();
}

With what I percieve from your problem, you can write a wrapper REST class which calls your current methods and send back the response to user. Elaborating it, say your current class is A and its method is getData(), which is currently called from main method. Now you create a REST class with a method say data() and within this function you are just doing return A.getData().
Other configurations like annotations, param types etc. you can add as per you needs.

Related

How to read, and store API calls/responses in Java

I'm trying to create a Java program, that will allow users to record and store API calls and responses in a NoSQL database. Basically, I want to take in the call name, the parameters, and the response and store that in the database. The intention here is to let users re-use the calls w/ the same parameters by accessing the data from the database, as opposed to making a live API call. Is there a way to listen to API calls on a specific URL using Java, and if so how can it be done?
I'm not sure if I completely understand the reason for doing it. But the answer to this question is tightly dependent on the technology you want to use for HTTP client, type of request/response and the NoSQL database and strategy you want to use.
As a suggestion, you can create two data classes, RequestDummy and ResponseDummy with all the required fields you need and use something like gson to serialize or deserialize them and store them as JSON file with the database to be more readable. Ex:
class RequestDummy {
String url;
String method; // (GET|HEAD|POST|PUT|PATCH|DELETE)
Map<String, String> headers;
String payload; // For (POST|PUT|PATCH) use Base64 to encode the binary to String
}
class ResponseDummy {
Map<String, String> headers;
int statusCode;
String body; // use Base64 to encode the binary to String
}
And use them during the HTTP call (briefly to just explain the idea):
// Initialize RequestDummy
RequestDummy req ...
HttpURLConnection con = (HttpURLConnection) new URL(req.url).openConnection();
// optional default is GET
con.setRequestMethod(req.method);
req.headers.entrySet().forEach(e -> con.setRequestProperty(e.getKey(), e.getValue()));
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader());
byte[] data = con.getInputStream().readAllBytes() // Java9
// Initialize ResponseDummy
RequestDummy req ...
in.close();
In 99% storing request and response is a bad design. As a suggestion, it's not a good idea to store HTTP request and response for any usage. They are just for communication, you must store the requested data which the HTTP request built based on, and the generated data from the HTTP response.

How to get and set cookie when consuming ASMX service from Java

I'm new to Java, what I'm trying to accomplish is to provide some sort of "session" between Java client and ASMX web-service.
Using wsimport.exe and wsdl I managed to generate a bunch of classes for proxy interaction, web methods are called, and I can get response as predifined class "WebResponse".
I pass Login and Password parameters in SOAP, the service returns OK status from login method. But when I invoke other methods, I get access denied. When I do the same in chrome, it works fine.
I guess I have to extract cookies from generated inherited objects like "Provider"(service), "ProviderSoap" somehow and set it again for next request.
Any advice would be helpful, thank you in advance.
You check the SOAP response of the login operation. What are all the values you are getting in the response? You need to see what the the contains and what contains. Because the service may use a token in the soap header.
I made it work with this code.
ProviderService service = new ProviderService ();
ProviderSoap soap = service.getPort(ProviderSoap.class);
soap.login("Administrator", "");
Map<String, List<String>> map = (Map<String, List<String>>)
((BindingProvider)soap).getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS);
String cookieParams = "";
List<String> cookies = map.get("Set-Cookie");
if (cookies != null) {
StringBuffer strBuf = new StringBuffer();
for (String type : cookies) {
strBuf.append(type);
}
cookieParams = strBuf.toString();
}
((BindingProvider)soap).getRequestContext().put(
MessageContext.HTTP_REQUEST_HEADERS,
Collections.singletonMap("Cookie", Collections.singletonList(cookieParams)
)
);
response = soap.isSessionEstablished();
this.Context.Request.Cookies works for me in a class that inherits from System.Web.Services.WebService

How to create API that accepts InputStream as a parameter?

My grails 2.2.4 app needs to support accepting files over HTTP from a third party application and sending the file, after making some tweaks to it, back out as a response to the third party application.
I want to convert the data sent by the third party application to a file using InputStream and then send the file back out using OutputStream
So I built this code:
API Classes
class ApiResponse {
ApiMeta meta
ApiObject apiObj
}
class ApiMeta {
int code
String errorType
List msgs = []
}
class ApiObject {
OutputStream os
}
//Object Marshaller
JSON.registerObjectMarshaller( ApiObject ) { ApiObject obj ->
//How can I send output stream as json?
}
Controller
//controller
def save() {
request.withFormat {
json {
ApiResponse resp
//How can I convert the JSON data in params to a file?
response.status = 201
resp = new ApiResponse(
meta: new ApiMeta(code: 201),
apiObj: new ApiObject(os: transfers))
render resp as JSON
}
multipartForm {
}
}
Question
How can I convert JSON payload sent by the third party service into a file?
Is it ok to put OutputStream in my ApiObject class so that I can send the JSON payload back to the service?
My grails 2.2.4 app needs to support accepting InputStream over HTTP
from a third party application and sending OutputStream as a response
back.
That does not really make sense. Third party apps can't really send an InputStream to your app and your app can't really send an OutputStream back. The third party app can send you data in the body of the request and you can read the body by retrieving an InputStream from the request, and the same sort of thing could happen when you put data in the response. At first read I thought maybe you were just wording things in a way that doesn't make sense but then when I saw your domain class, that suggests that maybe you really are confused about how this works.
class Request {
InputStream instream
OutputStream outstream
static constraints = {
instream nullable: false, blank: false
}
}
You can't do that. You cannot persist an InputStream or an OutputStream to the database.
EDIT:
If you have a controller like this:
class MyController {
def someAction(Widget w) {
// do whatever you need to do with the Widget
}
}
class Widget {
String name
String category
}
And you send a request to that controller action with a JSON body which looks like this...
{"name":"Robert","category":"Prog Rocker"}
Grails will automatically read the body of the request and do the corresponding binding. You would never have to directly interact with any input stream to make that happen. Is that the sort of thing you are looking for?

How to call a URL with params and get back response in servlet?

I have a situation where a intermediate servlet needs to be introduced which will handle requests from existing project and redirect the manipulated response to either existing project or the new one. This servlet will act as an interface to login into the new project from some other application.
So currently I use the following code to get back response in jsp as an xml.
var jqxhr =$.post("http://abhishek:15070/abc/login.action",
{ emailaddress: "ars#gmail.com",
projectid: "123" },
function(xml)
{
if($(xml).find('isSuccess').text()=="true")
{
sessiontoken=$(xml).find('sessiontoken').text();
setCookie("abcsessionid", sessiontoken , 1);
setCookie("abcusername",e_add,1);
}
}
)
.error(function() {
if(jqxhr.responseText == 'INVALID_SESSION') {
alert("Your Session has been timed out");
window.location.replace("http://abhishek:15070/abc/index.html");
}else {
alert( jqxhr.responseText);
}
});
xml content
<Response>
<sessiontoken>334465683124</sessiontoken>
<isSuccess>true</isSuccess>
</Response>
but now I want the same thing to be done using servlet, is it possible?
String emailid=(String) request.getParameter("emailaddress");
String projectid=(String) request.getParameter("projectid");
Update
I just came up with something.
Is it possible to return back a html page with form (from servlet), whose on body load it will submit a form and on submission of this form it will receive the response xml which will get processed.
Use java.net.URLConnection or Apache HttpComponents Client. Then, parse the returned HTTP response with a XML tool like as JAXB or something.
Kickoff example:
String emailaddress = request.getParameter("emailaddress");
String projectid = request.getParameter("projectid");
String charset = "UTF-8";
String query = String.format("emailaddress=%s&projectid=%s",
URLEncoder.encode(emailaddress, charset),
URLEncoder.encode(projectid, charset));
URLConnection connection = new URL("http://abhishek:15070/abc/login.action").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try {
connection.getOutputStream().write(query.getBytes(charset));
}
finally {
connection.getOutputStream().close();
}
InputStream response = connection.getInputStream();
// ...
See also:
Using java.net.URLConnection to fire and handle HTTP requests
HttpClient tutorial and examples
Actually, what you probably want is not an intermediate servlet at all. What you probably want is called a servlet filter and writing one is not particularly hard. I've written one in the past and I just started on a new one yesterday.
An article like this one or this one lays out pretty simply how you can use a servlet filter to intercept calls to specific URLs and then redirect or reject from there. If the incoming URL matches the pattern for the filter, it will get a shot at the request and response and it can then make a choice whether or not to pass it on to the next filter in line.
I don't know if all third party security solutions do it like this, but at least CAS seemed to be implemented that way.

JSON Proxy in Java / Play! Framework

I have a Play! application and from the JavaScript we now have run in to the Same Origin Policy Problem.
What I want is that JavaScript ajax calls go to our own server and that this server again route the json call to the external REST API.
My JavaScript use ajax to this url:
$.getJSON("http://mydomain.com/users", function(users) {
//callback
});
How can I easly make the server route to lets say:
public void getUsers(){
// result = call www.otherdomain.org/api/users.json What to do here?
renderJson(result);
}
and the return the response?
Or can it be done dynamically somewhere by directly rerouting?
here comes an example for doing async http calls (e.g. to facebook api)
WSRequest req = WS.url("https://graph.facebook.com/100001789213579");
Promise<HttpResponse> respAsync = req.getAsync();
HttpResponse resp = await(respAsync);
JsonElement jsonResp = resp.getJson();
JsonObject jsonObj = new JsonObject();
jsonObj.add("facebook-response", jsonResp);
renderJSON(jsonObj);
You can use the WS class to call another URL as a web service and retrieve the answer.
See an example here

Categories