I tried to send HTML form data to a Java Vertx Verticle but I get null as value.
Here is my code:
public void start(Future<Void> startFuture) throws Exception {
Router router = Router.router(vertx);
router.route("/html/*").handler(StaticHandler.create().setWebRoot("html/"));
router.route("/html/*").handler(StaticHandler.create().setWebRoot("web/html"));
router.route("/js/*").handler(StaticHandler.create().setWebRoot("web/js"));
router.route("/css/*").handler(StaticHandler.create().setWebRoot("web/css"));
router.route("/fonts/*").handler(StaticHandler.create().setWebRoot("web/fonts"));
Route route = router.route(HttpMethod.POST, "/crypt/testForm/");
route.handler(routingContext -> {
String productType = routingContext.request().getParam("test");
System.out.println(productType);
});
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(8085, "localhost", res -> {
if (res.succeeded()) {
startFuture.complete();
} else {
startFuture.fail(res.cause());
}
});
}
And for my html file:
<form action="/crypt/testForm" method="post">
<input type ="text" id="test" name ="test"/>
<input type="submit"/>
</form>
Regards.
Here is my solution, maybe it help,
public void start() throws Exception {
Router router = Router.router(vertx);
router.route("/html/*").handler(StaticHandler.create().setWebRoot("html/"));
router.route("/html/*").handler(StaticHandler.create().setWebRoot("web/html"));
router.route("/js/*").handler(StaticHandler.create().setWebRoot("web/js"));
router.route("/css/*").handler(StaticHandler.create().setWebRoot("web/css"));
router.route("/fonts/*").handler(StaticHandler.create().setWebRoot("web/fonts"));
router.route("/crypt/test").handler(BodyHandler.create());
router.post("/crypt/test").handler(ctx -> {
ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
JsonArray js = new JsonArray();
js.add(1);
js.add(5);
js.add(3);
ctx.response().end(js.toString());
});
vertx.createHttpServer().requestHandler(router::accept).listen(8085);
}
Related
I'm messing with Blazor + SignalR connection. I'd want to Authorize calls to SignalR by using JWT.
Basically I want to attach to SignalR calls the JWT
Here's my Blazor WASM SignalR Code
#page "/"
#using Microsoft.AspNetCore.SignalR.Client
#inject NavigationManager NavigationManager
#implements IDisposable
<div class="form-group">
<label>
User:
<input #bind="userInput" />
</label>
</div>
<div class="form-group">
<label>
Message:
<input #bind="messageInput" size="50" />
</label>
</div>
<button #onclick="Send" disabled="#(!IsConnected)">Send</button>
<hr>
<ul id="messagesList">
#foreach (var message in messages)
{
<li>#message</li>
}
</ul>
#code {
private HubConnection hubConnection;
private List<string> messages = new List<string>();
private string userInput;
private string messageInput;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
var encodedMsg = $"{user}: {message}";
messages.Add(encodedMsg);
StateHasChanged();
});
await hubConnection.StartAsync();
}
Task Send() =>
hubConnection.SendAsync("SendMessage", userInput, messageInput);
public bool IsConnected =>
hubConnection.State == HubConnectionState.Connected;
public void Dispose()
{
_ = hubConnection.DisposeAsync();
}
}
But I'm not sure how to attach JWT to this
I've seen this in Js version in section
Bearer token authentication in
this.connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/chat", { accessTokenFactory: () => this.loginToken })
.build();
https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1#authenticate-users-connecting-to-a-signalr-hub
What's Blazor's way of doing this?
I tried this:
var token = "eyJhb(...)";
hubConnection = new HubConnectionBuilder()
.WithUrl($"{Configuration["Url"]}/chathub", (HttpConnectionOptions x) =>
{
x.Headers.Add("Authorization", $"Bearer: {token}");
})
.Build();
But it threw error:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: The format of value 'Bearer: eyJh' is invalid.
System.FormatException: The format of value 'Bearer: eyJhbG' is invalid.
The solution was... to read the docs
var token = "eyJ";
hubConnection = new HubConnectionBuilder()
.WithUrl($"{Configuration["Url"]}/chathub?access_token={token}")
.Build();
Token is provided at connection estabilishing via url
We need to modify startup.cs to support OnMessageReceived
docs url:
https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1#authenticate-users-connecting-to-a-signalr-hub
services.AddAuthentication(options =>
{
// Identity made Cookie authentication the default.
// However, we want JWT Bearer Auth to be the default.
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
// Configure the Authority to the expected value for your authentication provider
// This ensures the token is appropriately validated
options.Authority = /* TODO: Insert Authority URL here */;
// We have to hook the OnMessageReceived event in order to
// allow the JWT authentication handler to read the access
// token from the query string when a WebSocket or
// Server-Sent Events request comes in.
// Sending the access token in the query string is required due to
// a limitation in Browser APIs. We restrict it to only calls to the
// SignalR hub in this code.
// See https://learn.microsoft.com/aspnet/core/signalr/security#access-token-logging
// for more information about security considerations when using
// the query string to transmit the access token.
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/hubs/chat")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
I am new to vertx and am trying to execute a function1 using vertx.executeBlocking from ABCHandler.java
public class ABCHandler implements Handler<RoutingContext> {
public ABCHandler( Vertx vertx)
{this.vertx =vertx;}
#Override
public void handle(RoutingContext routingContext) {
vertx.executeBlocking(future -> {
function1(routingContext, as ->
{
if (as.failed()) {
future.fail(as.cause());
} else {
future.complete(as.result());
}
});
}, rs -> {
if (rs.failed()) {
routingContext.response().putHeader(CONTENT_TYPE,
"application/json").setStatusCode(Integer.valueOf(401)).end("error");
} else {
routingContext.put("key_1", rs.result());
routingContext.next();
}
});
}
}
ABCHandler is meant to validate some data before request is routed to actual URI. But after routingContext.next(); I am getting 500 (Internal server error).
WebClientCreator.getWebClient(vertx);
Router router = Router.router(vertx);
router.route().handler(new ABCHandler(vertx));
router.post(AgentBindingConstants.AGENT_ENROLLMENT_URI).handler(
BodyHandler.create().setBodyLimit(10000));
router.post("/abc").handler(routingContext -> {
//some code
});
Also, when I run same code as non blocking it works.
Any help here is much appreciated.
I am trying to save my data to DB using Spring Restful web services.
I am continuously getting unsupported media type error when I run this code in Postman.
I have edited my code with front end JSP code and Repository class..
I have also added jackson dependency in pom.xml file. I am not able to figure out what's wrong with my code as I am a newbie towards Restful web services.
Controller::
#RequestMapping(value="/insp_rep/{id}",method=RequestMethod.POST, headers = "Accept=application/json" )
ResponseEntity <Void> addRepo(#RequestBody PC_Repo report, #PathVariable("id") int id){
this.pmService.addRep(report);
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
JSP Code along with AngularJS script
<html data-ng-app="formSubmit">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController',[ '$scope', '$http', function($scope, $http) {
$scope.list = [];
$scope.headerText = 'Inspection Report';
$scope.submit = function() {
var formData = {
"ins_id": $scope.ins_id,
"date_insp": $scope.date_insp,
"bedrooms":$scope.bedrooms,
"balcony":$scope.balcony,
"kitchen":$scope.kitchen,
"bath_toilet":$scope.bath_toilet,
"parking_gar":$scope.parking_gar,
"garden":$scope.garden,
"others":$scope.others,
"action":$scope.action
};
var response = $http.post('/PM/insp_rep/{id}', formData);
response.success(function(data, status, headers, config) {
$scope.list.push(data);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
//Empty list data after process
$scope.list = [];
};
}]);
</script>
Repository Class
#Entity
#JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
#Table(name="abc")
public class abc implements Serializable {
private java.sql.Date date_insp;
private String bedrooms;
private String balcony;
private String kitchen;
private String bath_toilet;
private String parking_gar;
private String garden;
private String others;
private String title;
private byte[]photo;
As per explained above in the comments section, obj consists of all the form parameters submitted and passed to the controller.
JSP HTML Tag:
<input type="text" ng-model="obj.balcony" />
<input type"text" ng-model="obj.address" />
And in controller, try debugging the object value using alert and to convert the object in String use 'JSON.Stringify(obj)'.
Controller JS:
$scope.submit = function() {
var formData = $scope.obj;
alert(JSON.stringify($scope.obj));
var response = $http.post('/PM/insp_rep/{id}', JSON.Stringify(obj));
response.success(function(data, status, headers, config) {
$scope.list.push(data);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
//Empty list data after process
$scope.list = [];
};
}]);
</script>
i will have few multipart forms in jsp and have to process them using servlet. All work fine with the first form, but if i try to add switch in servlet's doPost method, it stops to recognize fields value: userName cannot be null.
jsp form:
<form action="ServletMultipartForm" method="post" name="Form" enctype="multipart/form-data">
<br>
<label>NAME</label><br>
<input type="text" name="instrName">
<label>IMAGE</label><br>
<input type="file" name="instrImage">
<input type="submit" value="Submit Instructor" name="action">
</form>
ServletMultipartForm.java
#MultipartConfig
public class ServletMultipartForm extends HttpServlet {
private final String UPLOAD_DIRECTORY = "F:/OLD/JAVAJSP - Copy/PROGRAMMING_ASSIGNMENT3/ASpace/web/img/instructors";
String userImage = null;
String userName = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<FileItem> items = null;
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(ServletMultipartForm.class.getName()).log(Level.SEVERE, null, ex);
}
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
if (fieldname.equalsIgnoreCase("instrName")) {
userName = fieldvalue;
}
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List<FileItem> multiparts = upload.parseRequest(request);
userImage = new File(item.getName()).getName();
item.write(new File(UPLOAD_DIRECTORY + File.separator + userImage));
System.out.println("User Image Name " + userImage);
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
} catch (Exception ex) {
Logger.getLogger(ServletMultipartForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
User in=new User(userName, userImage);
UserDB.insert(in);
String FeedbackMessage = "New Instructor " + in.getUserName()+" was added";
request.setAttribute("FeedbackMessage", FeedbackMessage);
getServletContext()
.getRequestDispatcher("/adminPanel.jsp")
.forward(request, response);
gotoPage("/adminPanel.jsp", request, response);
}
private void gotoPage(String address, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
I have tried to add switch statement depending on "action", smth:
String selection = request.getParameter("action");
but then start to get that error: userName cannot be null.
Thanks for any advice.
I got stuck with an issue in iOS application using PhoneGap framework. I have a web services URL. I need to get JSON response from the web services URL. I had build up some code, but it is not working.
Here is my code:
<div data-role="content" data-theme="a" style="background: Black">
<div data-theme="a">
<span style="font-size: x-large; color: Orange;">Secure Log In</span></div>
<div data-theme="a">
<div data-theme="a">
<input type="password" placeholder="PASSWORD" id="txtPassword" style="background-color: gray;" /></div>
<div data-theme="a" align="right">
<a href="#" data-role="button" onclick="callWebService()" data-corners="false"
data-theme="a" id="clcik" cursor="pointer" style="width: 150px; border-radius: 5px 5px 5px 5px"
data-clickload="show" data-transition="slidefade"><span style="color: Green">Log In</span>
</a>
</div>
function callWebService(){
var query = 'Ocean';
var url = 'http://66.171.142.16/Accountservice/Security/ValidateAccess?accesscode=abcd&type=1';
alert(url);
$.getJSON(url,function(response){
alert('Here!');
});
};
How can I get the JSON response from the url?
I used .Net web Service to access Web Service, Also I have created a Plugin to call .Net web Service. in Java script I used to call web service method as described below.
in script.js
$(".CategoryNavbar").click(function(e){
e.preventDefault();
window.plugins.webservice.GetFlights("service",function(r){printResult(r)},function(e){console.log(e)});
return false;
});
function printResult(fileInfo){
var innerHtmlText=getHtml(fileInfo);
$.mobile.changePage('#CategoryPage',{transition:'slide'});
$('#CategoryPageContent').html(innerHtmlText);
$("#CategoryList").listview();
$("#CategoryList").listview('refresh');
}
function getHtml(fileInfo){
var htmlText='<ul data-role="listview" id="CategoryList" data-theme="c" data-filter="true" data-filter-placeholder="Search">';
for(var index=0;index<fileInfo.Flights.length;index++){
htmlText=htmlText+'<li> '+ fileInfo.Flights[index] +'</li>';
}
htmlText=htmlText+"</ul>";
return htmlText;
}
in Plugin File
/**
* Constructor
*/
function WebService() {
}
/**
* #param methodn The method name for which we want the webService
* #param successCallback The callback which will be called when directory listing is successful
* #param failureCallback The callback which will be called when directory listing encouters an error
*/
WebService.prototype.GetFlights = function(args, successCallback,
failureCallback) {
return cordova.exec(successCallback, failureCallback, 'WebService',
'GetFlights', [ args ]);
};
if (!window.plugins) {
window.plugins = {};
}
if (!window.plugins.webservice) {
window.plugins.webservice = new WebService();
}
Hi Sudheer please check the below code to get the response from web service using Ksoap
public class AndroidWebService extends Activity {
private final String NAMESPACE = "http://www.webserviceX.NET/";
private final String URL = "http://www.webservicex.net/ConvertWeight.asmx";
private final String SOAP_ACTION = "http://www.webserviceX.NET/ConvertWeight";
private final String METHOD_NAME = "ConvertWeight";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String weight = "3700";
String fromUnit = "Grams";
String toUnit = "Kilograms";
PropertyInfo weightProp =new PropertyInfo();
weightProp.setName("Weight");
weightProp.setValue(weight);
weightProp.setType(double.class);
request.addProperty(weightProp);
PropertyInfo fromProp =new PropertyInfo();
fromProp.setName("FromUnit");
fromProp.setValue(fromUnit);
fromProp.setType(String.class);
request.addProperty(fromProp);
PropertyInfo toProp =new PropertyInfo();
toProp.setName("ToUnit");
toProp.setValue(toUnit);
toProp.setType(String.class);
request.addProperty(toProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.i("myApp", response.toString());
TextView tv = new TextView(this);
tv.setText(weight+" "+fromUnit+" equal "+response.toString()+ " "+toUnit);
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
}
And here is an sample code for getting response using JSON in jquery mobile check the code below
$.ajax({
cache: false,
url: wcfServiceUrl + "Authenticate?CompanyID=" + escape(comp) + "&UserName=" + user + "&Password=" + escape(pass) + "&Auth=" + ipaddress+"",
data: "{}",
type: "GET",
contentType: "application/javascript",
dataType: "jsonp",
beforeSend: function (XMLHttpRequest) {
$.mobile.loadingMessageTextVisible = true;
$.mobile.loadingMessage = "Loading Please Wait";
$.mobile.showPageLoadingMsg();
},
complete: function (XMLHttpRequest, textStatus) {
$.mobile.hidePageLoadingMsg();
},
error: function (xmlHttpRequest, status, err) {
$.mobile.loadingMessageTextVisible = true;
$.mobile.loadingMessage = "Web service is not responding. Try again";
$.mobile.showPageLoadingMsg();
var wait = setTimeout(function(){
$.mobile.hidePageLoadingMsg();
},400);
},
error: function () {
jAlert("list failed!",alertmessage);
},
success: function (list) {
var rar = list.split(";");
if(rar[0]=="Error")
{
jAlert(rar[1],alertmessage);
}
else if(rar[0]=="Success")
{
localStorage.setItem( "CompanyID", comp);
localStorage.setItem( "Username", user);
localStorage.setItem( "UserID", rar[1]);
$.mobile.changePage( '#home', { transition: "pop", reverse: false } );
}
else if(rar[0]=="FirstLogin")
{
localStorage.setItem( "CompanyID", comp);
localStorage.setItem( "Username", user);
localStorage.setItem( "UserID", rar[1]);
$.mobile.changePage( '#change-pass', { transition: "slide", reverse: false } );
}
}
});