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 } );
}
}
});
Related
I made a download page in Wicket. As you can see, it's a DataView where you can download a file, depending on the id column and the DropDownChoice 'version'.
So clicking 'Download' on id 160 with version 3 should download file160ver3.txt, while on id 159 with version 2 it should download file159ver2.txt. Unfortunately updating the DropDownChoice doesn't get reflected in the model. So clicking on the Download button always downloads the file in the same version. As I have defaulted to Version 2 in my DropDownChoice, it always downloads this version.
Here's my code:
DropDownChoice<Integer> choice = new DropDownChoice<>("version", new Model<Integer>(2), List.of(1, 2, 3));
choice.add(new AjaxEventBehavior("change") {
#Override
protected void onEvent(AjaxRequestTarget target) {
target.add();
System.out.println(choice.getModelObject()); // doesn't change
}
});
item.add(choice);
// The value of choice.getModelObject() doesn't change
DownloadLink download = new DownloadLink("download", getFile(p.getId(), choice.getModelObject()));
download.setOutputMarkupId(true);
item.add(download);
What is it that I'm missing? How do I update the DropDownChoice?
Update and solution (changed according to Svens suggestion):
choice.add(new AjaxFormComponentUpdatingBehavior("change") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
System.out.println(choice.getModelObject());
}
});
item.add(choice);
DownloadLink download = new DownloadLink("download", () -> {
return getFile(p.getId(), choice.getModelObject());
});
// ...
private File getFile(int id, DropDownChoice<Integer> choice) throws FileNotFoundException, IOException {
Integer version = choice.getModelObject();
Thanks.
...
And here's the complete code (Java and HTML below):
public DownloadPage(PageParameters params) {
List<PrefKey> prefKeys = db.getPrefKeys();
DataView<PrefKey> dataView = getDataView(prefKeys);
Form<Void> form = new Form<>("form");
add(form);
form.add(dataView);
}
private DataView<PrefKey> getDataView(List<PrefKey> prefKeys) {
IDataProvider<PrefKey> provider = new ListDataProvider<>(prefKeys);
DataView<PrefKey> dataView = new DataView<>("dbAsDataView", provider, 10) {
private static final long serialVersionUID = 12345L;
#Override
protected void populateItem(Item<PrefKey> item) {
PrefKey p = item.getModelObject();
item.add(new Label("tdId", p.getId()));
item.add(new Label("tdKey", p.getKey()));
try {
DropDownChoice<Integer> choice = new DropDownChoice<>("version", new Model<Integer>(2), List.of(1, 2, 3));
choice.add(new AjaxEventBehavior("change") {
#Override
protected void onEvent(AjaxRequestTarget target) {
target.add();
System.out.println(choice.getModelObject()); // doesn't change
}
});
item.add(choice);
DownloadLink download;
// The value of choice.getModelObject() doesn't change
download = new DownloadLink("download", getFile(p.getId(), choice.getModelObject()));
download.setOutputMarkupId(true);
item.add(download);
} catch (IOException e) {
e.printStackTrace();
}
}
};
return dataView;
}
<h1>Wicket Download</h1>
<form wicket:id="form" action="">
<table id="tblDataView" class="table table-striped table-hover">
<thead>
<tr>
<th>Id</th>
<th>Key</th>
<th>Version</th>
<th>Download</th>
</tr>
</thead>
<tbody>
<tr wicket:id="dbAsDataView">
<td wicket:id="tdId"></td>
<td wicket:id="tdKey"></td>
<td><select wicket:id="version"></select></td>
<td><input type="button" wicket:id="download" value="Download"></input></td>
</tr>
</tbody>
</table>
</form>
You have to use a AjaxFormComponentUpdatingBehavior to transfer the newly selected item to the Java component (and its model):
choice.add(new AjaxFormComponentUpdatingBehavior("change") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
}
});
https://ci.apache.org/projects/wicket/guide/8.x/single.html#_ajaxformcomponentupdatingbehavior
And then your downloadLink has dynamically adjust to the current selection too:
download = new DownloadLink("download", () -> {
return getFile(p.getId(), choice.getModelObject()
});
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 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 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);
}