Twilio voice application error occurred - angularjs

I am trying to integrate Twilio to my AngularJS and spring MVC application. After following Twilio documentation I set up at front end device setup and calling etc. In Java class I am generating a token, and passing that token while making the call. In java the code is:
#RequestMapping(value = "/phoneCalling", method {
RequestMethod.GET, RequestMethod.POST
})
public #ResponseBody Phone phoneCalling(HttpServletRequest request, HttpServletResponse response, #RequestParam String leadPhone) {
try {
Number number = new Number.Builder(leadPhone).build();
Dial dial = new Dial.Builder().number(number).build();
VoiceResponse responseVR = new VoiceResponse.Builder().dial(dial).build();
System.out.println(responseVR.toXml());
} catch (TwiMLException e) {
e.printStackTrace();
}
return null;
}
At twilio TwiML, I set request URL as:
https://865c048b.ngrok.io/ZingyCRM/phoneCalling/
As I am testing locally, so used ngrok. But after clicking on make a call, it gives me voice message as application error occurred. I believe the TwiML request URL I might be setting wrong, can some one help here?

Related

Customizing LockedException of spring security to send new status code to angular.js

I am using spring 4 + hibernate 4 + spring security (RESTFull Webservice API) and angular at front. (Very new to this all).
My failure handler is as follows:
#Component
public class AuthFailure extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
If my request fails I get 401 response which is as expected. Now I want to add AccountLocked and CredentialsExpiredException functionality. I am setting "false" appropriately when I return "User". Again I do get response with status as 401.
return new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, AuthorityUtils.NO_AUTHORITIES);
As I always get 401 and I do not get any user object inside response(Or may be don't know how to get it), at front end I am unable to find whether it's due to bad credentials or account locked or credentials expired as I want to redirect to another page. I also tried to catch exceptions and tried to forward different statuses but does not seems to hit this code. I always get 401.
#ExceptionHandler(LockedException.class)
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ModelAndView handleLockedException(Exception e) {
logger.error("Exception occurred => " + e.getMessage());
return new ErrorResponse(HttpStatus.BAD_REQUEST.value(), e.getMessage(), "Spring security exception").asModelAndView();
}
Please help me - how shall I handle at angular end so that I can redirect to appropriate page?
I think solution was very simple, just did not pay attention to AuthFailure method parameters. Modified my AuthFailuar as follows:
#Component
public class AuthFailure extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
if (exception instanceof LockedException) {
response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
}else if {
....
} else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
Now as I have given different status codes I can easily differentiate at the front. Hope for somebody this would be helpful.

How to use REST API for sending messages to Azure Notification Hub from Java/GAE

I have successfully implemented calling GAE -> Azure Mobile Services -> Azure Notification HUB.
But I want to skip the Mobile Services step and call the notification HUB directly and I can't figure out how to send the authorization token. The returned error is:
Returned response: <Error><Code>401</Code><Detail>MissingAudience: The provided token does not
specify the 'Audience'..TrackingId:6a9a452d-c3bf-4fed-b0b0-975210f7a13c_G14,TimeStamp:11/26/2013 12:47:40 PM</Detail></Error>
Here is my code:
URL url = new URL("https://myapp-ns.servicebus.windows.net/myhubbie/messages/?api-version=2013-08");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(60000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.setRequestProperty("Authorization","WRAP access_token=\"mytoken_taken_from_azure_portal=\"");
connection.setRequestProperty("ServiceBusNotification-Tags", tag);
byte[] notificationMessage = new byte[0];
try
{
notificationMessage = json.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
log.warning("Error encoding toast message to UTF8! Error=" + e.getMessage());
}
connection.setRequestProperty("Content-Length", String.valueOf(notificationMessage.length));
OutputStream ostream = connection.getOutputStream();
ostream.write(notificationMessage);
ostream.flush();
ostream.close();
int responseCode = connection.getResponseCode();
The authorization header has to contain a token specially crafted for each individual request. The data you are using is the key you have to use to generate such a token.
Please follow the instructions on : http://msdn.microsoft.com/en-us/library/dn495627.aspx to create a token for your requests.
Final note, if you are using Java, you can use the code in this public repo https://github.com/fsautomata/notificationhubs-rest-java. It contains a fully functional REST wrapper for Notification Hubs. It is not Microsoft official but works and implements the above specs.

Apache Camel: Response is get lost when reached explicitly on route

I am getting a strange situation at the code below which simply routes request to Google and returns response.
It works well but when I activate the line commented out as "//Activating this line causes empty response on browser" to print out returned response from http endpoint (Google), response is disappear, nothing is displayed on browser. I thought it might be related with input stream of http response which can be consumed only once and I activated Stream Caching on context but nothing changed.
Apache Camel version is 2.11.0
Any suggestions are greatly appreciated, thanks in advance.
public class GoogleCaller {
public static void main(String[] args) throws Exception {
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
public void configure() {
from("jetty:http://0.0.0.0:8081/myapp/")
.to("jetty://http://www.google.com?bridgeEndpoint=true&throwExceptionOnFailure=false")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("Response received from Google, is streamCaching = " + exchange.getContext().isStreamCaching());
System.out.println("----------------------------------------------IN MESSAGE--------------------------------------------------------------");
System.out.println(exchange.getIn().getBody(String.class));
System.out.println("----------------------------------------------OUT MESSAGE--------------------------------------------------------------");
//System.out.println(exchange.getOut().getBody(String.class)); //Activating this line causes empty response on browser
}
});
}
});
context.setTracing(true);
context.setStreamCaching(true);
context.start();
}
}
As you use a custom processor to process the message, you should keep it in mind the in message of the exchange has response message from the google, if you are using exchange.getOut(), camel will create a new empty out message for you and treat it as response message.
Because you don't set the out message body in the processor, it makes sense that you get the empty response in the browser.

NoClassDefFoundError: javax.naming.directory.InitialDirContext is a restricted class. Using CCS (GCM) in Google App Engine

Im trying to implement google's Cloud Connection Server with Google App Engine following this tutorial -
Implementing an XMPP-based App Server. I copied latest smack jars from http://www.igniterealtime.org/projects/smack/ (smack.jar and smackx.jar), put them in WEB-INF/lib and added them to the classpath (im using eclipse).
In the code sample in the first link i posted, the XMPPConnection is initiated in a 'main' method. Since this is not really suitable to GAE i created a ServletContextListener and added it to web.xml.
public class GCMContextListener implements ServletContextListener {
private static final String GCM_SENDER_ID = "*GCM_SENDER_ID*";
private static final String API_KEY = "*API_KEY*";
private SmackCcsClient ccsClient;
public GCMContextListener() {
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
final String userName = GCM_SENDER_ID + "#gcm.googleapis.com";
final String password = API_KEY;
ccsClient = new SmackCcsClient();
try {
ccsClient.connect(userName, password);
} catch (XMPPException e) {
e.printStackTrace();
}
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
try {
ccsClient.disconnect();
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
web.xml
<web-app>
<listener>
<listener-class>com.myserver.bootstrap.GCMContextListener</listener-class>
</listener>
</web-app>
Now, when i start the GAE server i get the following exception :
java.lang.NoClassDefFoundError: javax.naming.directory.InitialDirContext is a restricted class. Please see the Google App Engine developer's guide for more details.
i searched the "Google App Engine developer's guide for more details" but couldnt find anything about this. can you please help me ?
Google App Engine restricts access to certain JRE classes. In fact they published a whitelist that shows you which classes are useable. It seems to me that the Smack library might require some reference to a directory context (maybe to create the XMPP messages?) and that is why your servlet causes this exception. The javax.naming.directory is not in the whitelist.
I'm currently working on setting up a GCM Server as well. It seems to me that you need to read through the example and see what that main method is doing. What I see is a connection to the GCM server:
try {
ccsClient.connect(userName, password);
} catch (XMPPException e) {
e.printStackTrace();
}
Then a downstream message being sent to a device:
// Send a sample hello downstream message to a device.
String toRegId = "RegistrationIdOfTheTargetDevice";
String messageId = ccsClient.getRandomMessageId();
Map<String, String> payload = new HashMap<String, String>();
payload.put("Hello", "World");
payload.put("CCS", "Dummy Message");
payload.put("EmbeddedMessageId", messageId);
String collapseKey = "sample";
Long timeToLive = 10000L;
Boolean delayWhileIdle = true;
ccsClient.send(createJsonMessage(toRegId, messageId, payload, collapseKey,
timeToLive, delayWhileIdle));
}
These operations would be completed at some point during your application's lifecycle, so your servlet should support them by providing the methods the example is implementing, such as the connect method that appears in the first piece of code that I pasted here. It's implementation is in the example at line 235 if I'm not mistaken.
As the documentation says, the 3rd party application server, which is what you're trying to implement using GAE, should be:
Able to communicate with your client.
Able to fire off properly formatted requests to the GCM server.
Able to handle requests and resend them as needed, using exponential back-off.
Able to store the API key and client registration IDs. The API key is included in the header of POST requests that send messages.
Able to store the API key and client registration IDs.
Able to generate message IDs to uniquely identify each message it sends.

GWT RPC method name at App Engine server log

our project runs on GWT and Java App Engine and we use the standard GWT RPC mechanism.
App engine adds log trace for each RPC call, but it just logs the servlet URL and not the called method.
We would like to add the method name to the log URL.
We have tried extending RpcRequestBuilder class, overriding doCreate and adding the method name to the URL, but the problem is that at this point the method name is unknown - it's known later at doSetRequestData (as part of the data string).
Thanks
Itzik
In each rpc implementation you can override one of readContent and processCall and add logging.
#Override
public String processCall(String payload) throws SerializationException {
// TODO Auto-generated method stub
String processCall = super.processCall(payload);
Logger.getLogger("").info(processCall);
return processCall;
}
#Override
protected String readContent(HttpServletRequest request)
throws ServletException, IOException {
// TODO Auto-generated method stub
String readContent = super.readContent(request);
Logger.getLogger("").info(readContent);
return readContent;
}
Log Line
6|0|4|http://127.0.0.1:8888/_4021625/|35C4974968FC8F8A9A7EA4881FD49F57|com.bitdual.client.LogMeService|logmemethod|1|2|3|4|0|

Resources