Currently working on server sent events of html5 now. I made a servlet and set the
response.setContentType("text/event-stream");
as this. Now I get the update from this servlet on my client side and my client side code is as follows:
<script >
if(typeof(EventSource)!=="undefined")
{
var url = 'http://localhost:8080/KnockOut/DateFeed.jsp';
eventSource = new EventSource(url);
eventSource.onmessage = function (event) {
var theParagraph = document.createElement('p');
theParagraph.innerHTML = event.data.toString();
document.body.appendChild(theParagraph);
}
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
But when I change the url to call a rest full webservice written in java, it shows some error and I am note able to get the updated output.
The REST webservice code is:
#GET
public String getXml(#Context HttpHeaders header, #Context HttpServletResponse response) {
response.setHeader("cache-control", "no-cache");
response.setContentType("text/event-stream");
return "dataas: " + (new java.util.Date()).toString() + "x\n\n";
}
please help me.
Here i got the answer
import java.io.PrintWriter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.enterprise.context.RequestScoped;
import org.glassfish.jersey.media.sse.EventOutput;
import org.glassfish.jersey.media.sse.OutboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
/**
* REST Web Service
*
* #author Irshad kk
*/
#Path("WS")
#RequestScoped
public class SSEResource {
#Context
private UriInfo context;
/**
* Creates a new instance of SSEResource
*/
public SSEResource() {
}
#GET
#Produces(SseFeature.SERVER_SENT_EVENTS)
public String getServerSentEvents() {
System.out.println("haii" + System.currentTimeMillis());
return "data: " + "irshad" + System.currentTimeMillis() + "\n\n";
}
}
Related
I have seen this issue being addressed in many other posts but none of them has solved my problem. I have a front-end Vue.js application and a spring boot Java application.
I am using the vue-google-oauth to prompt the Google sign in from my front end application to get the auth code, then I wanted to use my backend server to get user details and handle logic there.
On Google Cloud Platform I defined an Authorized redirect URI:
and I am using this very same uri when I am sending my auth code in the front end
import api from "#/assets/js/api";
import AdminNavigation from "./AdminNavigation";
import { mapGetters } from "vuex";
import Axios from "axios";
export default {
name: "Dashboard",
computed: {
...mapGetters(["IsSignedIn"]),
},
data() {
return {
title: "Christopher s' portfolio admin",
appDescription:
"Here you can add contents for the front end portfolio website.",
isInit: false,
};
},
components: {
AdminNavigation,
},
methods: {
signIn: async function () {
try {
const authCode = await this.$gAuth.getAuthCode();
Axios.post("http://localhost:8080/authenticate", {
code: authCode,
redirect_uri: "http://localhost:3000/admin/dashboard",
});
} catch (err) {
console.log(err);
}
},
},
mounted() {
let that = this;
let checkGauthLoad = setInterval(function () {
that.isInit = that.$gAuth.isInit;
if (!this.IsSignedIn) {
that.signIn();
}
if (that.isInit) clearInterval(checkGauthLoad);
}, 1000);
},
};
My backend server receives the auth code and the redirect_uri which is identical to what was defined on Google Cloud Platform.
package com.salay.christophersalayportfolio.controllers;
import com.google.api.client.auth.oauth2.TokenResponseException;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.salay.christophersalayportfolio.general.ConstantVariables;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;
#Controller
public class AdminController {
#CrossOrigin(origins = "http://localhost:3000")
#RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
#ResponseBody
public String authentication(HttpEntity<String> data) throws IOException, ParseException {
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(data.getBody());
String authCode = json.get("code").toString();
String redirect_uri = json.get("redirect_uri").toString();
try {
GoogleTokenResponse response =
new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),
ConstantVariables.GOOGLE_CLIENT_ID,
ConstantVariables.GOOGLE_CLIENT_SECRET,
authCode, redirect_uri).execute();
System.out.println("Access token: " + response.getAccessToken());
} catch (TokenResponseException e) {
if (e.getDetails() != null) {
System.err.println("Error: " + e.getDetails().getError());
if (e.getDetails().getErrorDescription() != null) {
System.err.println(e.getDetails().getErrorDescription());
}
if (e.getDetails().getErrorUri() != null) {
System.err.println(e.getDetails().getErrorUri());
}
} else {
System.err.println(e.getMessage());
}
}
return "";
}
}
But I get the following error:
400 Bad Request redirect_uri_mismatch
I kept looking at a lot of stack overflow questions and no solution worked for me so far... any ideas?
Sounds like you are not sending the OAuth details you think you are. Have you captured HTTPS messages to the Authorization Server from your Spring Boot back end - and can you post details here?
If it helps, this blog post of mine includes some notes on configuring an HTTP proxy in Java.
I have worked on small xml body request less than 20 lines and I created key value pairs for it in java.
But I have to use acord xml as payload request to get a response which is more than 250 lines. I tried using form-data to provide as .xml file which is not working.
contentType is xml format and response is received in xml format.
Can somebody please guide me in the right direction, on how to achieve this if coded in a framework?
#Test
public void xmlPostRequest_Test() {
RestAssured.baseURI = "http://localhost:8006";
String requestBody = "<client>\r\n" +
" <clientNo>100</clientNo>\r\n" +
" <name>Tom Cruise</name>\r\n" +
" <ssn>124-542-5555</ssn>\r\n" +
"</client>";
Response response = null;
response = given().
contentType(ContentType.XML)
.accept(ContentType.XML)
.body(requestBody)
.when()
.post("/addClient");
System.out.println("Post Response :" + response.asString());
System.out.println("Status Code :" + response.getStatusCode());
System.out.println("Does Reponse contains '100 Tom Cruise 124-542-5555'? :" + response.asString().contains("100 Tom Cruise 124-542-5555"));
}
You should use a file to pass the xml payload .
Please see the below code and provide a feedback . It's been tested and working .
import static io.restassured.RestAssured.given;
import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.is;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.filter.session.SessionFilter;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;
public class XmlExample {
//#Test
public void postComplexXML() throws IOException {
String FilePath="path\\to\\xml.xml";
String XMLBodyToPost=generateStringFromResource(FilePath);
RestAssured.baseURI="http://services.groupkt.com/state/get/IND/UP";
Response res= given().queryParam("key", "value").body(XMLBodyToPost).when().post().then().statusCode(201).and().
contentType(ContentType.XML).extract().response();
//Pass the RrstAssured Response to convert to XML
XmlPath x=rawToXML(res);
//Get country value from response
String country=x.get("RestResponse.result.country");
int size=x.get("result()");
}
public static Response validateXmlResponse() throws IOException {
// Navigate to xml file path attached in project
String FilePath = "c\downloads\filepath;
String XMLBodyToPost = new String(Files.readAllBytes(Paths.get(FilePath)));
// Call the baseUrl to test the request
RestAssured.baseURI = TestURL;
// Getting a reponse for submitted POST request
Response res = given().auth().basic(userName, password).body(XMLBodyToPost).
when().post()
.then()
.statusCode(200).and().contentType(ContentType.HTML).extract().response();
String response = res.asString();
// System.out.println("Returning response as string format:" + " " + response);
return res;
}
I have a webservice that I'm trying to invoke with the following client-side code:
import com.test.wsdl.CxfAdd;
import com.test.wsdl.CxfAddService;
import java.util.Map;
import javax.xml.ws.BindingProvider;
import org.apache.cxf.ws.addressing.AddressingProperties;
import org.apache.cxf.ws.addressing.AttributedURIType;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import org.apache.cxf.ws.addressing.JAXWSAConstants;
public class Main {
public static void main(String[] args) {
CxfAddService service = new CxfAddService();
CxfAdd client = service.getCxfAddPort();
Map<String, Object> requestContext = ((BindingProvider)client).getRequestContext();
AddressingProperties maps = new AddressingProperties();
EndpointReferenceType ref = new EndpointReferenceType();
AttributedURIType add = new AttributedURIType();
add.setValue("http://www.w3.org/2005/08/addressing/anonymous");
ref.setAddress(add);
maps.setReplyTo(ref);
maps.setFaultTo(ref);
requestContext.put(JAXWSAConstants.CLIENT_ADDRESSING_PROPERTIES, maps);
client.myMethodOneWay("Input message");
}
}
On the server-side (Tomcat), the webservice is implemented as the following:
CxfAdd.java:
package com.test.ws;
import javax.jws.Oneway;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.soap.Addressing;
#WebService(targetNamespace = "http://test.com/wsdl")
#Addressing(enabled = true, required = true)
public interface CxfAdd {
#WebResult(name = "response")
public abstract String myMethod(String message);
#WebResult(name="response")
#Oneway
public void myMethodOneWay(String message);
}
CxfAddImpl.java:
package com.test.ws;
import javax.annotation.Resource;
import javax.jws.Oneway;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.soap.Addressing;
#WebService
#Addressing
public class CxfAddImpl implements CxfAdd {
#Resource
WebServiceContext webServiceContext;
public String myMethod(String message) {
System.out.println("Invoking sayHello in " + getClass());
return "Hello " + message;
}
#Oneway
public void myMethodOneWay(String message) {
// TODO Auto-generated method stub
}
}
However, when I run the client-side code, at the server-side I get the following error:
INFO: Inbound Message
----------------------------
ID: 46
Address: http://localhost:8080/CxfAddressingServer/services/cxfadd
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml; charset=UTF-8
Headers: {Accept=[*/*], cache-control=[no-cache], connection=[keep-alive], Content-Length=[211], content-type=[text/xml; charset=UTF-8], host=[localhost:8080], pragma=[no-cache], SOAPAction=[""], user-agent=[Apache CXF 3.1.3]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:myMethodOneWay xmlns:ns2="http://test.com/wsdl"><arg0>Input message</arg0></ns2:myMethodOneWay></soap:Body></soap:Envelope>
--------------------------------------
Out 30, 2015 7:18:56 PM org.apache.cxf.ws.addressing.ContextUtils retrieveMAPs
WARNING: WS-Addressing - failed to retrieve Message Addressing Properties from context
It seems that I'm not sending the ws-addressing attributes, can anyone help me figure out what's wrong or missing in my code? Thank you.
In the client-side code, I've replaced the following:
CxfAdd client = service.getCxfAddPort();
With the following:
CxfAdd client = service.getCxfAddPort(
new org.apache.cxf.ws.addressing.WSAddressingFeature());
And it works now.
Solution was provided by someone else here:
http://www.coderanch.com/t/657413/Web-Services/java/CXF-Client-WS-Addressing-attributes
Hi I have implemanted one basic example of RESTful web services ,I am trying to implement Oauth client and Server (Provider) in my src folder of eclipse.
This is my OauthClient.java
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
import com.sun.jersey.api.client.*;
import com.sun.jersey.oauth.client.OAuthClientFilter;
import com.sun.jersey.oauth.signature.OAuthParameters;
import com.sun.jersey.oauth.signature.OAuthSecrets;
import javax.ws.rs.core.*;
#Path("/OauthClient")
#RolesAllowed({"admin"})
public class OauthClient
{
#GET
#Path("/oauth_client")
#Produces(MediaType.TEXT_PLAIN)
public String oauthClient()
{
// establish the parameters that will be used to sign the request
OAuthParameters params = new OAuthParameters().consumerKey("hoge").signatureMethod("HMAC-SHA1").timestamp().nonce().version("1.1").token("sho1get");
// establish the secrets that will be used to sign the request
OAuthSecrets secrets = new OAuthSecrets().consumerSecret("testtest").tokenSecret("testtest");
Client client = Client.create();
// OAuth test server resource
WebResource resource = client.resource("http://localhost:8080/RestfulWS/rest/OauthServer/oauth_provider");
// if parameters and secrets remain static, filter can be added to each web resource
OAuthClientFilter filter = new OAuthClientFilter(client.getProviders(), params, secrets);
// filter added at the web resource level
resource.addFilter(filter);
System.out.println("==== Client =====");
// make the request (signing it in the process)
return resource.get(String.class);
}
}
and OauthServer.java is
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
//import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.oauth.server.OAuthServerRequest;
import com.sun.jersey.oauth.signature.OAuthParameters;
import com.sun.jersey.oauth.signature.OAuthSecrets;
import com.sun.jersey.oauth.signature.OAuthSignature;
import com.sun.jersey.oauth.signature.OAuthSignatureException;
#Path("/OauthServer")
#RolesAllowed({"admin"})
public class OauthServer {
#GET
#Path("/oauth_provider")
#Produces(MediaType.TEXT_PLAIN)
public String oauthProvider(#Context HttpContext context)
{
// wrap an existing request with server request
OAuthServerRequest request = new OAuthServerRequest(context.getRequest());
// baseline OAuth parameters for access to resource
OAuthParameters params = new OAuthParameters().readRequest(request);
// OAuth secrets to access resource
OAuthSecrets secrets = new OAuthSecrets().consumerSecret("hoge").tokenSecret("testtest");
// String timestamp = params.getTimestamp();
try {
/* The error occurs here. */
if (OAuthSignature.verify(request, params, secrets)) {
return "OK";
}
} catch (OAuthSignatureException e) {
// log.warning(e.getMessage());
// } catch (UniformInterfaceException e) {
//// log.warning(e.getMessage());
// } catch (Exception e) {
// log.warning(e.getMessage());
}
return "ERROR";
}
}
how to run this to achive Oauth authentication ,do we have to write some JSP? please suggest something.
I understand that I can upload 1 file at a time to AppEngine using multipart/form POST requests. AppEngine also supports uploading multiple files but you have to do some hokey JSP stuff for it to work.
I have an app that requires me to upload some form data, 2 images and 3 fields of text. Is this possible to do via AppEngine? I've been trying to find information on this but it's tough nothing works with the flexibility I need. I will be storing the data in the blob store/data store.
I need a Java solution.
This is the signature of my POST method:
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public void post(
#Context HttpServletRequest request,
#Context HttpServletResponse response)
throws FileUploadException, IOException {}
Copy and paste of the Java Servlet if you really need it. Above is the question and relevant servlet snippets.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.fileupload.FileItemHeaders;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
#Path("/upload")
public class FileUploadServlet {
private BlobstoreService blobstoreService = BlobstoreServiceFactory
.getBlobstoreService();
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public void post(#Context HttpServletRequest request,
#Context HttpServletResponse response) throws FileUploadException,
IOException {
final ServletFileUpload upload = new ServletFileUpload();
final FileItemIterator fileIter = upload.getItemIterator(request);
while (fileIter.hasNext()) {
final FileItemStream item = fileIter.next();
String name = item.getName();
String fieldName = item.getFieldName();
String contentType = item.getContentType();
Log.d("Name = " + name);
Log.d("Field-Name = " + fieldName);
Log.d("Content-Type = " + contentType);
FileItemHeaders headers = item.getHeaders();
if(headers != null) {
Iterator<String> it = (Iterator<String>)headers.getHeaderNames();
while(it.hasNext()) {
String h = it.next();
Log.d(h + " = " + headers.getHeader(h));
}
}
if (item.isFormField()) {
// Nothing
} else {
RawImageData data = new RawImageData();
data.load(item.openStream());
// RawImageData reads the stream and stores it into a large byte[] called data.imageData
ByteBuffer bb = ByteBuffer.wrap(data.imageData);
FileService fs = FileServiceFactory.getFileService();
AppEngineFile file = fs.createNewBlobFile(contentType);
FileWriteChannel write = fs.openWriteChannel(file, true);
write.write(bb);
write.closeFinally();
String path = file.getFullPath();
Log.d(path);
// Later, read from the file using the file API
boolean lock = false; // Let other people read at the same time
FileReadChannel readChannel = fs.openReadChannel(file,
false);
// CRASHES WITH java.nio.charset.IllegalCharsetNameException: image/jpeg
// contentType = "image/jpeg"
// Again, different standard Java ways of reading from the
// channel.
BufferedReader reader = new BufferedReader(Channels.newReader(readChannel, contentType));
readChannel.close();
}
}
response.setContentType("text/html");
response.getOutputStream().write("success".getBytes());
}
}
Full Exception:
WARNING: /api/upload
java.nio.charset.IllegalCharsetNameException: image/jpeg
at java.nio.charset.Charset.checkName(Charset.java:284)
at java.nio.charset.Charset.lookup2(Charset.java:458)
at java.nio.charset.Charset.lookup(Charset.java:437)
at java.nio.charset.Charset.forName(Charset.java:502)
at java.nio.channels.Channels.newReader(Channels.java:381)
at com.futonredemption.starstarstar.FileUploadServlet.post(FileUploadServlet.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
blah blah blah
You can create you own multipart file upload handler, then save files via Blobstore FileService API.