browser call - Twilio.js in Struts2 (Java) - java

New to Struts2 and Twilio.js (api sdk) here needing guidance.
I have double checked my twilio credentials, created access token and got it accepted on my browser, "[Device]: Stream is ready" on the console log. When I try to dial a number using the Twilio.Device.connect(~), console log shows {code: 31002, message: "Connection Declined", connection: a}. I don't know what to look for on the logs. I have setup the voice URL of TwiML app on the twilio account and test connection with ngrok https.
//ACTIVATE CALL START
var connection = null;
$("#activate-calls").click(function(){
$("#answer").hide();
$("#hangup").hide();
$("#reject").hide();
$.getJSON('activateCalls').done(
function (data) {
// log('Got a token.');
console.log('Token: ' + data.data.token);
// Setup Twilio.Device
Twilio.Device.setup(data.data.token, {debug: true});
Twilio.Device.ready(function (device) {
$("#log").text("Ready");
});
Twilio.Device.error(function (error) {
$("#log").text("Error: " + error.message);
});
Twilio.Device.connect(function (conn) {
$("#log").text("Successfully established call");
$("#call").hide();
$("#reject").hide();
$("#hangup").show();
});
Twilio.Device.disconnect(function (conn) {
$("#log").text("Call ended. Ready for new incoming/ outgoing calls.");
$("#hangup").hide();
$("#call").show();
});
Twilio.Device.incoming(function(conn) {
// Set the reference to the current
// connection when we receive an
// incoming call
alert("ringring");
connection = conn;
$("#log").text("Incoming call from " + conn.parameters.From);
$("#answer").show();
$("#call").hide();
$("#reject").show();
// Clear the reference to the
// connection when disconnected.
connection.disconnect(function() {
connection = null;
})
});
Twilio.Device.cancel(function(conn) {
$("#log").text("Ready");
$("#answer").hide();
$("#reject").hide();
$("#call").show();
});
$("#reject").click(function() {
$("#log").text("Incoming call is rejected. Ready for new incoming/ outgoing calls.");
connection.reject();
$("#answer").hide();
$("#reject").hide();
$("#call").show();
});
$("#answer").click(function() {
// If there's no pending connection,
// there's nothing to do.
if (!connection) { return; }
// Update the interface
$("#answer").hide();
$("#call").show();
$("#log").text("Call accepted");
// Accept the current connection.
connection.accept();
});
$("#call").click(function() {
// get the phone number to connect the call to
params = {"PhoneNumber": $("#number").val()};
Twilio.Device.connect(params);
});
$("#hangup").click(function() {
Twilio.Device.disconnectAll();
$("#log").text("Ready");
});
}
);
});
//ACTIVATE CALL END
The jsp/html looks like this..
<div align="center">
<div class="form-inline">
<div class="input-group">
<div class="input-group-addon"><img src="https://www.twilio.com/bundles/favicons/img/Twilio_16.png" /></div>
<input type="text" class="form-control" id="number" name="number">
</div>
<button class="btn btn-success" id="answer">Accept</button>
<button class="btn btn-success" id="call">Call</button>
<button class="btn btn-danger" id="hangup">Hangup</button>
<button class="btn btn-danger" id="reject">Reject</button>
</div>
<br>
<div id="log" class="alert-info" style="width: 347px; font-size: large;"></div>
</div>
My action class on activeCalls to create token is this:
public String execute(){
logger.debug("MCI> ActivateCallsAction.execute");
String identity = "johnny";
List<Scope> scopes = new ArrayList<>();
scopes.add(new IncomingClientScope(identity));
scopes.add(new OutgoingClientScope.Builder(APP_SID).build());
Jwt jwt = new ClientCapability.Builder(ACCOUNT_SID, AUTH_TOKEN).scopes(scopes).build();
String token = jwt.toJwt();
logger.debug("token: " + token);
HashMap<String, String> json = new HashMap<>();
json.put("identity", identity);
json.put("token", token);
data = json;
logger.debug(json.get("token") + "-" + json.get("identity"));
return "success";
}
I can post the complete error from the console logs if needed. TIA!

Related

session create using spring security registration

I am working with the registration processing using the spring security following the article of building https://github.com/Baeldung/spring-security-registration. As per this article, the HTML pages take the input and insert it into the database.
I am working with a Flutter application on the front-end. I want that when the user requests to reset password a link is sent to the email of a user and when the user clicks on the verification link it will create a session and redirect to the UI Page on the app to write the New Password. When the user enters the New Password it will update the password of that user.
updatePassword.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"/>
<style>
.password-verdict{
color:#000;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script th:src="#{/resources/pwstrength.js}"></script>
<title th:text="#{message.updatePassword}">update password</title>
</head>
<body>
<div sec:authorize="hasAuthority('CHANGE_PASSWORD_PRIVILEGE')">
<div class="container">
<div class="row">
<h1 th:text="#{message.resetYourPassword}">reset</h1>
<form>
<br/>
<label class="col-sm-2" th:text="#{label.user.password}">password</label>
<span class="col-sm-5"><input class="form-control" id="password" name="newPassword" type="password"
value=""/></span>
<div class="col-sm-12"></div>
<br/><br/>
<label class="col-sm-2" th:text="#{label.user.confirmPass}">confirm</label>
<span class="col-sm-5"><input class="form-control" id="matchPassword" type="password" value=""/></span>
<div id="globalError" class="col-sm-12 alert alert-danger" style="display:none"
th:text="#{PasswordMatches.user}">error
</div>
<div class="col-sm-12">
<br/><br/>
<button class="btn btn-primary" type="submit" onclick="savePass()"
th:text="#{message.updatePassword}">submit
</button>
</div>
</form>
</div>
</div>
<script th:inline="javascript">
var serverContext = [[#{/}]];
$(document).ready(function () {
$('form').submit(function(event) {
savePass(event);
});
$(":password").keyup(function(){
if($("#password").val() != $("#matchPassword").val()){
$("#globalError").show().html(/*[[#{PasswordMatches.user}]]*/);
}else{
$("#globalError").html("").hide();
}
});
options = {
common: {minChar:6},
ui: {
showVerdictsInsideProgressBar:true,
showErrors:true,
errorMessages:{
wordLength: /*[[#{error.wordLength}]]*/,
}
}
};
$('#password').pwstrength(options);
});
function savePass(event){
event.preventDefault();
$(".alert").html("").hide();
$(".error-list").html("");
if($("#password").val() != $("#matchPassword").val()){
$("#globalError").show().html(/*[[#{PasswordMatches.user}]]*/);
return;
}
var formData= $('form').serialize();
$.post(serverContext + "user/savePassword",formData ,function(data){
window.location.href = serverContext + "login?message="+data.message;
})
.fail(function(data) {
if(data.responseJSON.error.indexOf("InternalError") > -1){
window.location.href = serverContext + "login?message=" + data.responseJSON.message;
}
else{
var errors = $.parseJSON(data.responseJSON.message);
$.each( errors, function( index,item ){
$("#globalError").show().html(item.defaultMessage);
});
errors = $.parseJSON(data.responseJSON.error);
$.each( errors, function( index,item ){
$("#globalError").show().append(item.defaultMessage+"<br/>");
});
}
});
}
</script>
</div>
</body>
</html>
This will create the session and update the password perfectly.
But I want to send a post request and a newPassword to store in the database. But unable to create the session.
Controller.java
#RequestMapping(value = "/user/savePassword", method = RequestMethod.POST)
#ResponseBody
public String savePassword(#RequestParam("newPassword") String newPassword) {
final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
userService.changeUserPassword(user, newPassword);
return "Password has been changed successfully. ";
}
This
final User user = (User)
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
is not creating the session of the user when I directly hit the URL from UI App.
Please tell me the way to do so.
it's hard to understand what happened wrong. If I understood correctly, and you follow this example https://www.baeldung.com/spring-security-registration-i-forgot-my-password is impeccable, then at the time of checking the token from the letter, you should have been authorized.
I guess, it should be here
public String validatePasswordResetToken(long id, String token) {
PasswordResetToken passToken =
passwordTokenRepository.findByToken(token);
if ((passToken == null) || (passToken.getUser()
.getId() != id)) {
return "invalidToken";
}
Calendar cal = Calendar.getInstance();
if ((passToken.getExpiryDate()
.getTime() - cal.getTime()
.getTime()) <= 0) {
return "expired";
}
User user = passToken.getUser();
Authentication auth = new UsernamePasswordAuthenticationToken(
user, null, Arrays.asList(
new SimpleGrantedAuthority("CHANGE_PASSWORD_PRIVILEGE")));
SecurityContextHolder.getContext().setAuthentication(auth); // authorization after validation of reset token
return null;
}
Please, give some more about your situation. Give me a full example of this. Or you just what to save a password directly?

POST not supported exception while invoking REST api via SpringBoot

I have a REST API defined in a SpringBoot application and I'm trying to access this via POST using a different application deployed on a Tomcat 8 server. Upon doing a POST from the other application, I get the following error in the SpringBoot logs:
Request method 'POST' not supported.
Here is my Rest Controller class:
#Controller
public class RestApiController {
#RequestMapping(value="/cancel", method=RequestMethod.GET)
public #ResponseBody String CancelJobEndPointInfo() {
return "A job can be cancelled by POSTing to this URL";
}
#RequestMapping(value="/cancel", method=RequestMethod.POST)
public #ResponseBody DataPost CancelJobEndPoint(#RequestParam("username") String name,
#RequestParam(name = "passPhrase", defaultValue = "null") String passPhrase,
#RequestParam("jobnumber") String jobNumber, #RequestParam("file") MultipartFile file){
UserDetails userObject = new UserDetails();
CancelJob job = new CancelJob();
DataPost dpc = new DataPost();
if (!file.isEmpty()) {
try {
/*
* Write private key
*/
byte[] ppkBytes = file.getBytes();
BufferedOutputStream ppkStream =
new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
ppkStream.write(ppkBytes);
ppkStream.close();
userObject.setKeyPath(file.getOriginalFilename());
userObject.setUserName(name);
userObject.setPassphrase(passPhrase);
job.getCancelJob(userObject, jobNumber);
dpc.setMessage("Job:" + jobNumber + " Cancelled successfully");
return dpc;
} catch (IOException e) {
dpc.setMessage("Could not cancel the job:" + jobNumber + " ERROR => " + e.getMessage());
return dpc;
// return "Could not cancel the job:" + jobNumber + " ERROR => " + e.getMessage();
} catch (JSchException e){
// return "Could not cancel the job:" + jobNumber + " ERROR => " + e.getMessage();
dpc.setMessage("Could not cancel the job:" + jobNumber + " ERROR => " + e.getMessage());
return dpc;
}
} else {
dpc.setMessage("Private Key file for user: " + name + " is empty");
return dpc;
// return "Private Key file for user: " + name + " is empty";
}
}
I could see that a GET request is going through successfully, but I'm not sure what is wrong with the PUT request.
Also, I am able to invoke the API via POST by using html files within the application that has the REST methods.
I am facing this issue while trying to invoke it from a different application.
Following is the form that I am using:
<form action="http://localhost:8080/cancel" enctype="multipart/form-data"
method="post" accept-charset="utf-8" id="jobCancelForm"
name="job">
<h4 class="section-heading">User Details:</h4>
<fieldset class="form-group">
<label for="UserID">User Name</label> <input type="username"
class="form-control" id="canceluser"
placeholder="Enter SSH User ID" name="username">
</fieldset>
<fieldset class="form-group">
<label for="passPhrase">PassPhrase :</label> <input
type="password" class="form-control" id="cancelpass"
placeholder="Private Key PassPhrase" name="passPhrase">
</fieldset>
<fieldset class="form-group">
<label for="PrivateKeyFileInput">Private Key File</label> <input
type="file" class="form-control-file"
id="cancelPrivateKeyFileInput" name="cFile"> <small
class="text-muted">Select the pre-configured private
key file to be used for SSH authentication.</small>
</fieldset>
<a role="separator" class="divider"></a>
<hr>
<h4 class="section-heading">Job Details:</h4>
<fieldset class="form-group">
<label for="jobID">Job ID :</label> <input type="number"
class="form-control" id="canceljobID"
placeholder="Enter the job ID Ex: 1242254" name="jobNumber">
</fieldset>
<button type="submit" class="btn btn-primary"
id="jobMonitorButton">Cancel Job</button>
</form>
<a role="separator" class="divider"></a>
<!-- response div -->
<div style="word-wrap: break-word;" id="cancelResponse"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal" id="jobCancelFormCloseButton">Close</button>
</div>
</div>
Any pointers please?
It seems to me the same issue for what the solution is provided here
Add #RequestMapping("YOUR-CONTEXT-VALUE") on the controller's class and remove value from #RestController annotation.

how can i set and display another filed in local database?

i am trying the example todo app,i download that example in ionic and i tried that it is working, and i trued to add another filed inside newTask.html and add in local database as same as previous value,but it is not working can you please help me how can i add another filed in the local database and get results in list html file....
NewTask.html
------------
<div class="modal" ng-controller="newTaskCtrl">
<ion-header-bar class="bar-stable">
<h1 class="title">Add New Task</h1>
<button class="button button-clear button-positive" ng-click="closeNewTask()">Cancel</button>
</ion-header-bar>
<ion-content>
<form ng-submit="createTask(task)">
<div class="list">
<!--label class="item item-input">
<input type="text" placeholder="Title What do you need to do?" ng-model="task.title">
</label-->
<label class="item item-input item-stacked-label">
<span class="input-label">Title</span>
<input type="text" placeholder="What do you need to do?" ng-model="task.title">
<span class="input-label">Lasr Name</span>
<input type="text" placeholder="Firstname?" ng-model="task.firstname">
</label>
<!--div class="row">
<label class="col">
<input type="" ng-model="time">
</label>
<label class="col">
<input type="text" placeholder="End?" >
</label>
</div-->
</div>
<div class="padding">
<button type="submit" class="button button-block button-positive">Create Task</button>
</div>
</form>
</ion-content>
</div>
NewTaskCtrl.js
-------------------
todoApp.controller('newTaskCtrl', function($scope, $ionicModal, $ionicPopup, SQLService) {
// Called when the form is submitted
$scope.createTask = function(task) {
SQLService.set(task.title,task.firstname);
$scope.loadTask();
$scope.taskModal.hide();
task.title = "";
task.firstname = "";
};
SQLService.js
------------------
todoApp.factory("SQLService", function ($q) {
var db;
var task='';
var deltask;
function createDB() {
try {
db = window.openDatabase("todoDB", "1.0", "ToDoApp", 10*1024*1024);
db.transaction(function(tx){
tx.executeSql("CREATE TABLE IF NOT EXISTS tasks (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title VARCHAR(100), firstname VARCHAR(100) )",[]);
});
} catch (err) {
alert("Error processing SQL: " + err);
}
console.log('database created');
}
function setTasks(title,firstname){
return promisedQuery("INSERT INTO tasks(title,firstname) VALUES ('" + title + "','" + firstname + "')", defaultResultHandler, defaultErrorHandler);
}
function getTasks(){
return promisedQuery('SELECT * FROM tasks', defaultResultHandler, defaultErrorHandler);
}
function defaultResultHandler(deferred) {
return function(tx, results) {
var len = results.rows.length;
var output_results = [];
for (var i=0; i<len; i++){
var t = {'id':results.rows.item(i).id,'title':results.rows.item(i).title,'firstname':results.rows.item(i).firstname};
output_results.push(t);
}
deferred.resolve(output_results);
}
}
function defaultErrorHandler(deferred) {
return function(tx, results) {
var len = 0;
var output_results = '';
deferred.resolve(output_results);
}
}
function promisedQuery(query, successCB, errorCB) {
var deferred = $q.defer();
db.transaction(function(tx){
tx.executeSql(query, [], successCB(deferred), errorCB(deferred));
}, errorCB);
return deferred.promise;
}
return {
setup: function() {
return createDB();
},
set: function(title,firstname) {
return setTasks(title,firstname);
},
all: function() {
return getTasks();
}
}
});
PLease see the SQL Service and help me,is it correct what i add the filed name in "setTasks function.."
Ok, so you had tried the example that you had downloaded, now you have added another field in NewTask.html. But the new field that you added is not getting added to the table right??
Did you try to change the version of the DB opened??
db = window.openDatabase("todoDB", "1.0", "ToDoApp", 10*1024*1024);
to
db = window.openDatabase("todoDB", "2.0", "ToDoApp", 10*1024*1024);

javascript not firing onmessage / onopen methods for websocket connection

I am trying to implement a basic server client communication through web sockets. I have console prints in my server to tell me when a conection opeened and when a message is recieved. As soon as i press send button on my client, i get an "something recieved" console print from the server but the onopen function of client (pasted below) is not fired. Same happens with other functions as well. What am i doing wrong ?
Here is my code :
Client Side code for html age:
<script type="text/javascript">
document.getElementById("msg").value = "Website Opened";
var ws = new WebSocket("ws://localhost:8080/PushServlet/echo");
ws.onopen = function ()
{
document.getElementById("msgArea").textContent += "Connection Opened \n";
};
function connect()
{
ws = new WebSocket("ws://localhost:8080/PushServlet/echo");
var wss = "ws = " + ws.toString();
document.getElementById("msgArea").textContent += wss;
};
ws.onmessage = function(message)
{
document.getElementById("msgArea").textContent += message.data;
};
function postToServer()
{
if(ws == null)
{
document.getElementById("msgArea").textContent += "Connection Null \n";
}
ws.send(document.getElementById("msg").value);
document.getElementById("msg").value = "";
};
ws.onclose = function(evt)
{
document.getElementById("msgArea").textContent += "closed";
};
function updateTextBox()
{
document.getElementById("msg").value = "Blah Blah Blah";
};
function closeConnect()
{
document.getElementById("msg").value = "Blah Blah Blah";
ws.close();
};
</script>
</head>
<body>
<div>
<textarea rows="4" cols="100" id="msgArea" readonly></textarea>
</div>
<div>
<input id="msg" type="text" value="Website Opened 1" />
<button type="submit" id="sendButton" onclick="postToServer()">Send</button>
<button type="submit" id="update_button" onclick="connect()" > Update </button>
</div>
</body>
</html>
Server Side code for websocket connection:
package com.servlet.pushServlet;
import java.io.IOException;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class EchoEndpoint {
#OnMessage
public void onMessage(Session session, String msg) {
try {
session.getBasicRemote().sendText("Send something");
System.out.println("Some thing recieved");
session.close();
} catch (IOException e) { }
}
}

Uploading large files with HttpClient

I want to upload large video files (>=1Gb) with HttpClient to a servlet but I couldn't find any real examples.
Could you give me some useful code examples?
I'd like to see both the HttpClient and FileUpload demo codes (as a one project). And it is quite interesting can I use FileUpload lib to download large files?
It is interesting to have upload bound like this applet -> servlet
Here's an example of HttpClient and file upload:
http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload
I'm not sure that you mean by "real". It's real enough, even if it doesn't precisely match your situation.
1GB? You're likely to have file size limitation issues. Try it locally and see. If it fails, at least you'll have some real code and more exact conditions to post here.
I am able to upload large files >200mb , Please look into below jsp to spring controller code .
Jsp code :
<script src="../lib/app/configurator.data.ajax.js" type="text/javascript"></script>
<script src="../lib/ui/jquery.fileupload.js"></script>
<html>
<script language="Javascript">
var varb = '';
var test = 0;
var count = 1;
$(function () {
var maxChunkSize = 30000000; //SET CHUNK SIZE HERE
var your_global_var_for_form_submit = '';
var params = {
year: threeDSelectedYear,
series: threeDSelectedSeries
};
/*File upload bind with form, 'fileupload' is my form id. As sumit triggers
for file ulaod will submit my form*/
/* replaceFileInput: true, */
$('#fileupload').fileupload({
maxChunkSize: maxChunkSize,
url: efccustom.getEfcContext()+'upload/uploadZip?year='+threeDSelectedYear+'&series='+threeDSelectedSeries, //URL WHERE FILE TO BE UPLOADED
error: function (jqXHR, textStatus, errorThrown) {
// Called for each failed chunk upload
$(".fileupload-loading").html("");
$('.ANALYZE_DIALOG').dialog("close");
},
success: function (data, textStatus, jqXHR) {
/*This event will be called on success of upload*/
count = parseInt($('#counter').val()) + 1;
$('#counter').val(count);
$('#ttk').val(count);
data.ttk = 7;
console.log(" count ",count , data);
},
submit: function (e, data) {
/*This event will be called on submit here i am
adding variable to form*/
//console.log($('#zip_uploaded_file').val());
//console.log(data.originalFiles[0].name);
test = data.originalFiles[0];
$('#fname').val(data.originalFiles[0].name);
$('#trequests').val(Math.ceil(data.originalFiles[0].size/maxChunkSize));
$('#counter').val('1');
},
progress: function (e, data) {
/*PROGRESS BAR CODE WILL BE HERE */
$(".fileupload-loading").html('<img src="../public/themeroller/images/throbber.gif" alt="Uploading Please Wait..." title="Uploading Please Wait...." />');
},
add: function (e, data) {
$('.browsedFileName').html(data.originalFiles[0].name);
your_global_var_for_form_submit = data;
},
done: function (e, data) {
ajaxcall.Data._get('upload/extractZipNCreateJson',params,function(data2) {
alert("file upload success ");
$(".fileupload-loading").html("");
$('.ANALYZE_DIALOG').dialog("close");
});
}
});
/*This is my button click event on which i am submitting my form*/
$('#button').click(function(){
your_global_var_for_form_submit.submit();
});
});
</script>
<html>
<body>
<form id="fileupload" enctype="multipart/form-data">
<div class="row fileupload-buttonbar">
<div class="span7">
<!--<input type="file" name="files" id="file" /> -->
<input type="file" id="zip_uploaded_file" name="zip_uploaded_file" />
<input type="hidden" name="counter" id="counter" value="1" />
<input type="hidden" name="fname" id="fname" value="" />
<input type="hidden" name="trequests" id="trequests" value="1" />
<input type="hidden" name="ttk" id="ttk" value="1" />
<input type="button" id="button" name="button" value="submit" />
<span class='browsedFileName'></span>
</div>
</div>
<!-- The loading indicator is shown during file processing -->
<div class="fileupload-loading"></div>
</form>
</body>
Controller COde :
#RequestMapping(value = "/uploadZip", method = RequestMethod.POST, consumes = "multipart/form-data")
#ResponseBody
public ResponseEntity<String>
uploadZip(HttpServletRequest request, HttpServletResponse response)
throws IOException, IllegalArgumentException {
try {
String year = request.getParameter("year");
String series = request.getParameter("series");
log.info(" year " + year + " series " + series);
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
HttpSession session = request.getSession();
UserContext userContext = (UserContext) session
.getAttribute(ApplicationConstant.USER_CONTEXT);
String userName = userContext.getUser();
String workSpaceInUse = userContext.getCurrentWorkSpace();
FileItem item = null;
boolean fileNotExistFlag;
String fileExtension;
while (iterator.hasNext()) {
item = (FileItem) iterator.next();
String content = item.getContentType();
log.info(" content "+content);
log.info(" File Type Getting Uploaded :"+content);
if (!item.isFormField()) {
/* Here in IOUtils the Third Parameter true tells that the small chunks of data that comes need to be added to the same File */
IOUtils.copy(fileItem.getInputStream(), new FileOutputStream(new File(threeDPath+"/"+year+"/"+series+"/"+uploadZipFileName),true));
}
}
return null;
}
}
catch(Exception e) {
return handleError(new RuntimeException("Unexpected error while uploading ZIP", e));
}
return null;
}

Categories