I have developed an app in phonegap (html5, JQuery, JS) and I want to develop a plugin to print to a BT printer.
I download printer manufacturer's SDK and I imported the appropriate .jar file to my project with all the methods I will need in my project.
I create the below plugin, following an internet tutorial, in order to call from JS the JAVA methods from printer manufacturers SDK.
JS
var HelloPlugin = {
callNativeFunction: function (success, fail, resultType) {
return cordova.exec(success, fail, "com.tricedesigns.HelloPlugin", "nativeAction", [resultType]);
}
};
JAVA
package com.tricedesigns;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import com.starmicronics.stario.StarIOPort;
import com.starmicronics.stario.StarIOPortException;
import com.starmicronics.stario.StarPrinterStatus;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.util.Log;
public class HelloPlugin extends Plugin {
public static final String NATIVE_ACTION_STRING="nativeAction";
public static final String SUCCESS_PARAMETER="success";
#Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
if (NATIVE_ACTION_STRING.equals(action)) {
this.ctx.runOnUiThread(new Runnable()
{
public void run()
{
String resultType = null;
StarIOPort port = null;
String message = null;
String portName = "bt:";
String portSettings = "mini";
byte[] texttoprint = new byte[]{0x1b, 0x40, 0x1b,0x74,0x0D,(byte) 0x91,(byte) 0x92,(byte) 0x93,(byte) 0x94,(byte) 0x95,(byte) 0x96,(byte) 0x97,(byte) 0x98,(byte) 0x99,0x0A,0x0A,0x0A,0x0A,0x0A};
try
{
port = StarIOPort.getPort(portName, portSettings, 10000);
try
{
Thread.sleep(500);
}
catch(InterruptedException e) {}
}
catch (StarIOPortException e)
{
Builder dialog = new AlertDialog.Builder((Context)ctx);
dialog.setNegativeButton("Ok", null);
AlertDialog alert = dialog.create();
alert.setTitle("Failure");
alert.setMessage("Failed to connect to printer");
alert.show();
}
finally
{
if(port != null)
{
try
{
StarIOPort.releasePort(port);
} catch (StarIOPortException e) {}
}
}
}
});
}
return null;
}
}
Printer command manual say:
GetPort is what you will be using to “open” the port to the printer. Using one of the valid
inputs for portName and portSettings as mentioned previously before this, you can pass your
connection string into the StarIO class so that it will correctly set its private variables.
//The following would be an actual usage of getPort:
StarIOPort port = null;
try
{
port = StarIOPort.getPort(portName, portSettings, 10000);
}
catch (StarIOPortException e)
{
//There was an error opening the port
}
StarIOPort is a part of StarIO and this will allow you to create a “port” handle. The
above example shows the port being created and set to null then being assigned the actual
port hook on the following line that contains getPort.
Always use a try, catch when using getPort. If the port cannot be opened
because of connection problems, your program will crash unless you use a
try, catch like the above example.
Is the above syntax of plugin correct or is there something i missed?
When I run my app always i receive "Failed to connect to printer" even if the printer is on and connected to my device.
try this:
public PluginResult execute(String action, JSONArray data, String callbackId) {
PluginResult result = null;
if (PRINT_ACTION.equals(action))
{
JSONObject printerStatusJSON = new JSONObject();
try {
Boolean prtStatus = false;
String msg ="Failed to connect to printer";
String portName = "";
ArrayList<PortInfo> dvss = PrinterFunctions.getDevices();//BTPortList = StarIOPort.searchPrinter("BT:");
if (Looper.myLooper() == null) {
Looper.prepare();
}
for(PortInfo dvs : dvss) {
Map<String, String> st = PrinterFunctions.CheckStatus(dvs.getPortName(), "mini");//port = StarIOPort.getPort(portName, portSettings, 1000);
if(st.get("status") == "true") {
prtStatus = true;
portName = st.get("portName");
break;
}
msg = st.get("message");
}
if(!portName.isEmpty()) {
PrinterFunctions.PrintSomething(portName, data);//MiniPrinterFunctions.PrintSampleReceipt(String portName, JSONArray data);
}
printerStatusJSON.put("prtStatus", prtStatus);
printerStatusJSON.put("message", msg);
result = new PluginResult(Status.OK, printerStatusJSON);
}
catch (Exception jsonEx) {
Log.e("YourApplicationName", "Got JSON Exception " + jsonEx.getMessage());
jsonEx.printStackTrace();
result = new PluginResult(Status.JSON_EXCEPTION);
}
}
else {
result = new PluginResult(Status.INVALID_ACTION);
Log.e(TAG, "Invalid action : " + action);
}
return result;
}
Related
I am testing nv-websocket-client on Android using Android Studio 2.2.3/JRE1.8.0_76.
My code is basically the same as the echo sample application in the README.md file. The class runs fine under Java 8 Update 111, but fails under Android Studio. I walked the code in debug mode and it failed at:
Source:com/neovisionaries/ws/client/Address.java:36
InetSocketAddress toInetSocketAddress()
{
return new InetSocketAddress(mHost, mPort);// mHost = "echo.websocket.org", mPort = 80.
}
Error message in Android Studio:
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate java.net.InetSocketAddress.toString()
Any idea what I did wrong here?
My Test Class:
public class TestWS {
private String m_msg;
private String m_uriStr; // = "ws://echo.websocket.org";
private static final int TIMEOUT = 5000;
public TestWS(String uriStr) {
m_uriStr = uriStr;
m_msg = "";
}
public void RunTest() {
try {
// Connect to the echo server.
WebSocket ws = connect();
ws.sendText("This is a test");
Thread.sleep(1000); // Make sure m_msg is updated before function return.
ws.disconnect();
}
catch(Exception ex)
{
m_msg += "Exception: " + ex.getMessage(); // getMessage() returns null.
}
}
private WebSocket connect() throws IOException, WebSocketException
{
return new WebSocketFactory()
.setConnectionTimeout(TIMEOUT)
.createSocket(m_uriStr)
.addListener(new WebSocketAdapter() {
// A text message arrived from the server.
#Override
public void onTextMessage(WebSocket websocket, String message) {
m_msg += "Echo: " + message;
}
})
.addExtension(WebSocketExtension.PERMESSAGE_DEFLATE)
.connect(); // <= failed in this function.
}
public String GetMsg(){
return m_msg;
}
}
Can you please tell me how to use SubethaSmtp library? I just want to retrieve the mails from my Gmail inbox and display them or one of them in console window.
I studied most of the API doc but I'm not being able to put the pieces together to get the things working.
Can you please tell me about a working example?
I wrote this code to build a grails application. You may find some bad code habits but it's okey for a sample application.
Here is the code in src/groovy folder :
class MessageHandlerFactoryImpl implements MessageHandlerFactory {
#Override
MessageHandler create(MessageContext ctx) {
return new MessageHandlerImpl(ctx)
}
}
class MessageHandlerImpl implements MessageHandler {
MessageContext context
MessageHandlerImpl(MessageContext context) {
this.context = context
}
#Override
void from(String from) {
println "FROM: ${from}"
}
#Override
void recipient(String recipient) {
println "RECIPIENT: ${recipient}"
}
#Override
void data(InputStream data) {
println "DATA"
println "-------------------"
BufferedReader reader = new BufferedReader(new InputStreamReader(data))
StringBuilder builder = new StringBuilder()
String line
while ((line = reader.readLine()) != null) {
builder.append(line + "\n")
}
println builder.toString()
}
#Override
void done() {
println "DONE"
}
}
class SimpleMessageListenerImpl implements SimpleMessageListener {
#Override
boolean accept(String from, String recipient) {
println "accept: ${from} \n>> ${recipient}"
return false
}
#Override
void deliver(String from, String recipient, InputStream data) {
try {
println "deliver: ${from} \n>> ${recipient} \n>>> ${data.read()}"
} catch (TooMuchDataException e) {
println "TooMuchDataException: ${e.message}"
} catch (IOException e) {
println "IOException: ${e.message}"
}
}
}
class UsernamePasswordValidatorImpl implements UsernamePasswordValidator {
#Override
void login(String username, String password) {
try {
println "LOGIN:::::::"
} catch(LoginFailedException e) {
println "LoginFailedException: ${e.message}"
}
}
}
And here is my controller code.
class SubethaController {
SMTPServer server
def index() {
MessageHandlerFactoryImpl factory = new MessageHandlerFactoryImpl()
server = new SMTPServer(factory)
server.hostName = "imap.gmail.com"
server.port = 993
server.authenticationHandlerFactory = new EasyAuthenticationHandlerFactory(new UsernamePasswordValidatorImpl())
server.start()
}
def stop() {
server?.stop()
}
Wiser wiser
def wiser() {
server = new SMTPServer(new SimpleMessageListenerAdapter(new SimpleMessageListenerImpl()))
server.start()
wiser = new Wiser()
wiser.setPort(25001)
wiser.start()
for (WiserMessage message : wiser.getMessages())
{
String eSender = message.getEnvelopeSender()
String eReceiver = message.getEnvelopeReceiver()
println ">>>>>>>message.getMimeMessage ${message.getMimeMessage()}"
}
}
def wiserS() {
wiser?.stop()
}
}
Thanks.
Okey... I found the answer... The code is well written and is working fine. I just didn't know how to send messages to listening smtp server on the port. I just used telnet program and sent emails to the smtp server running on localhost. Now I will create DNS mapping to make it work on the Internet.
Thanks Nicolás for showing your interest.
Based on this tutorial and another tutorial that unfortunately I can't get my hands on right now, I've created my Client-Server application but instead of sending string messages, the client asks for data(using Object Input/Output Streams) from the server using a custom class "Message".
First I created, the basic concept of it, using simple Java and tested both the server and the client on my computer, and displayed the data my client received in the console output. Everything worked out great, so I started to make the transition to Android(for the client). Trying to use the AsycTask, as show in the linked tutorial, I've managed so far to establish the connection between the client and the server. But I'm having a problem getting my server to read my "Message" object. Here are my classes:
Server:
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class T_Server extends Thread {
private static int port = 4444;
private ServerSocket srvSock = null;
private Socket clntSock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
private OnMessageReceived msgListener;
private Message msgIn;
private Object objSend;
public static void main(String[] args) {
OnMessageReceived _msgListener=new OnMessageReceived();
T_Server server=new T_Server(_msgListener);
server.start();
}
public T_Server(OnMessageReceived _msgListener) {
this.msgListener = _msgListener;
}
public void send(Object _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
} catch (IOException ex) {
Logger.getLogger(T_Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public void run() {
running = true;
try {
srvSock = new ServerSocket(port);
System.out.println("Server startet. IP : " + InetAddress.getLocalHost() + ", Port : " + srvSock.getLocalPort());
System.out.println("\nWaiting for a client ...");
clntSock = srvSock.accept();
System.out.println("\nClient accepted: " + clntSock);
try {
out = new ObjectOutputStream(clntSock.getOutputStream());
in = new ObjectInputStream(clntSock.getInputStream());
while (running) {
msgIn = (Message) in.readObject();
System.out.println(msgIn.toString());
objSend = msgListener.messageReceived(msgIn);
send(objSend);
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
clntSock.close();
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}
}
I use the same Message class both on the Server and on the Client
Message Class:
import java.io.Serializable;
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
public String sender, content, type;
public Message(String sender, String type, String content){
this.sender = sender; this.type=type; this.content = content;
}
#Override
public String toString(){
return "{type='"+type+"', sender='"+sender+"', content='"+content+"'}";
}
}
I have also created a class to handle the Messages, on the server side, called OnMessageReceived.
P.S. In this class there are fields and some options that have to do with my backend database.
OnMessageReceived:
import java.sql.SQLException;
import java.util.regex.Pattern;
public class OnMessageReceived {
public Object messageReceived(Message message) throws SQLException {
Message _msg = message;
Database db = new Database();
Object objReturn;
String strResult;
boolean addResult;
final Pattern pattern = Pattern.compile("\\[.*?&");
final String[] result;
if (_msg.type.equals("getUsers")) {
objReturn = db.getUsers();
return objReturn;
} else if (_msg.type.equals("getFriends")) {
objReturn = db.getFriends(_msg.sender);
return objReturn;
} else if (_msg.type.equals("addFriend")) {
String _UserName, _UserNameFriend;
_UserName = _msg.sender;
_UserNameFriend = _msg.content;
addResult = db.addFriend(_UserName, _UserNameFriend);
if (addResult) {
strResult = "Add was successfull";
return strResult;
} else if (!addResult) {
strResult = "Add failed";
return strResult;
}
System.out.println(addResult);
} else if (_msg.type.equals("addUser")) {
String _UserName, _Password, _Phone;
result = pattern.split(_msg.content);
_UserName = _msg.sender;
_Password = result[0];
_Phone = result[1];
addResult = db.addUser(_UserName, _Password, _Phone);
if (addResult) {
strResult = "Add was successfull";
return strResult;
} else if (!addResult) {
strResult = "Add failed";
return strResult;
}
System.out.println(addResult);
} else if (_msg.type.equals("Login")) {
boolean isUser;
String _UserName;
_UserName = _msg.sender;
isUser = db.isUser(_UserName);
if (isUser) {
strResult = "Login Successfull";
return strResult;
} else if (!isUser) {
strResult = "Login failed";
return strResult;
}
}
return null;
}
}
For the client side(on the Android) it's very simillar to the one in the linked tutorial.
The difference is that I only have 2 buttons, one to connect to the server and one to send my message, which is an instance of my Message class.
Client:
import java.io.*;
import java.net.*;
import android.util.Log;
public class T_Client {
private static final String TAG = "MyActivity";
private static String serverIP = "192.168.1.11";
private static int port = 4444;
private InetAddress serverAddr = null;
private Socket sock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
private OnMessageReceived msgListener;
Object objIn, objReceived;
public T_Client(OnMessageReceived _msgListener){
this.msgListener=_msgListener;
}
public void send(Message _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
Log.i(TAG,"Outgoing : " + _msg.toString());
} catch (IOException ex) {
Log.e(TAG,ex.toString());
}
}
}
public void stopClient(){
running = false;
}
public void run(){
running = true;
try {
//here you must put your computer's IP address.
serverAddr = InetAddress.getByName(serverIP);
Log.i("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
sock = new Socket(serverAddr, port);
try {
//send the message to the server
out =new ObjectOutputStream(sock.getOutputStream());
//receive the message which the server sends back
in =new ObjectInputStream(sock.getInputStream());
Log.i("TCP Client", "C: Connected.");
//in this while the client listens for the messages sent by the server
while (running) {
objIn = in.readObject();
if (objIn != null && msgListener != null) {
//call the method messageReceived from MyActivity class
msgListener.messageReceived(objIn);
}
objIn = null;
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + objIn + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
sock.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
public interface OnMessageReceived {
public void messageReceived(Object objReceived);
}
}
Main Activity:
import java.io.IOException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
private static final String TAG = "MyActivity";
private T_Client client;
private Message msgSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connect(View v) throws IOException {
new connectTask().execute("");
}
public void btnSend(View v) throws IOException {
msgSend=new Message("Setlios", "getUsers", "");
if(client!=null){
client.send(msgSend);
}
}
public class connectTask extends AsyncTask<Object,Object,T_Client> {
#Override
protected T_Client doInBackground(Object... objIn) {
//we create a TCPClient object and
client = new T_Client(new T_Client.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(Object objIn) {
//this method calls the onProgressUpdate
publishProgress(objIn);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
Log.i(TAG,values.getClass().getName().toString());
}
}
}
When I hit the "Send" button I get this error on the server console which points me to the point where I read the object read from the ObjectInputStream and pass it an instance of the Message class but I can't understand what the problem is. I also noticed that it shows this "in.neverhide.connect" which is the package name of the project for my android client
java.lang.ClassNotFoundException: in.neverhide.connect.Message
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:622)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1593)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1750)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at Objects_WORKING.T_Server.run(T_Server.java:61)
Ok after searching around I found this post and the answer from Akinsola 'mys Tunmise. I've made the Message class into a jar and used it as an external reference in both the client and the server.
When I execute a CalendarService.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer()); I get an OAuthException 401 Error Unknown authorization header.
I'm using GWT+GAE I don't know why I'm receiving this error, oauthParameters seem to be OK.
I get user login on
loginService.login
I check if I have
the authentication already on
oauthService.checkOauthTokenSecret
If not, I'll do a redirect to Google
Aproval page for GCalendar
permission
I get querystring
returned by Google and I get Access
Token and Access Token Secret and
set it to the user entity for later
use on oauthService.upgradeLogin.
And trying to get calendars on
oauthService.getPublicCalendars.
I'm using MVP pattern with mvp4g framework, sorry if is a bit confusing 0:-)
Any idea why I'm receiving 401 error? I think is something about I'm going up & down through client and server and external pages... and something is missing :-( but all parameters seem to be correctly fullfilled.
Client side
public void onStart(){
GWT.log("onStart");
loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {
#Override
public void onSuccess(LoginInfo result) {
Common.loginInfo = result;
if(Common.loginInfo.isLoggedIn()) {
oauthService.checkOauthTokenSecret(new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
if (result == null){
eventBus.OauthLogin();
}else{
oauthService.upgradeLogin(Window.Location.getQueryString(),Common.loginInfo, new AsyncCallback<LoginInfo>() {
#Override
public void onSuccess(LoginInfo result) {
Common.loginInfo = result;
getCitas();
}
#Override public void onFailure(Throwable caught) {
Common.handleError(caught);
}
});
}
}
#Override public void onFailure(Throwable caught) {
Common.handleError(caught);
}
});
}else{
eventBus.LoadLogin();
}
}
#Override public void onFailure(Throwable caught) {
Common.handleError(caught);
}
});
}
Server Side
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthParameters;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.util.ServiceException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.rdt.citas.client.OAuthoritzationService;
import com.rdt.citas.client.shared.LoginInfo;
public class OAuthoritzationServiceImpl extends RemoteServiceServlet
implements OAuthoritzationService {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(OAuthoritzationServiceImpl.class.getName());
private static String KEY_PARAM = "oauth_consumer_key";
private static String SECRET_PARAM = "oauth_consumer_secret";
private static String SCOPE_PARAM = "scope_calendars";
private static String CALLBACK_PARAM = "oauth_callback";
public String checkOauthTokenSecret(){
ServletContext context = this.getServletContext();
getOauthParams(context);
return (String) this.getThreadLocalRequest().getSession().getAttribute("oauthTokenSecret");;
}
public String getApprovalOAuthPageURL() throws IOException{
ServletContext context = this.getServletContext();
getOauthParams(context);
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(getFromSession(KEY_PARAM));
oauthParameters.setOAuthConsumerSecret(getFromSession(SECRET_PARAM));
oauthParameters.setScope(getFromSession(SCOPE_PARAM));
oauthParameters.setOAuthCallback(getFromSession(CALLBACK_PARAM));
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
try {
oauthHelper.getUnauthorizedRequestToken(oauthParameters);
String approvalPageUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
String oauthTokenSecret = oauthParameters.getOAuthTokenSecret();
this.getThreadLocalRequest().getSession().setAttribute("oauthTokenSecret", oauthTokenSecret);
return approvalPageUrl;
} catch (OAuthException e) {
log.log(Level.WARNING,e.toString());
return "";
} finally{
}
}
public LoginInfo upgradeLogin(String queryString, LoginInfo login){
// receiving '?key1=value1&key2=value2
queryString = queryString.substring(1, queryString.length());
String k = getFromSession(KEY_PARAM);
String s = getFromSession(SECRET_PARAM);
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(k);
oauthParameters.setOAuthConsumerSecret(s);
String oauthTS = (String) this.getThreadLocalRequest().getSession().getAttribute("oauthTokenSecret");//oauthParameters.getOAuthTokenSecret();
oauthParameters.setOAuthTokenSecret(oauthTS);
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
oauthHelper.getOAuthParametersFromCallback(queryString,oauthParameters);
login.setQueryStringTokens(queryString);
login.setAccessTokenSecret(oauthTS);
try {
String accesToken = oauthHelper.getAccessToken(oauthParameters);
login.setTokenSecret(accesToken);
} catch (OAuthException e) {
log.log(Level.WARNING,e.toString());
}
return login;
}
public ArrayList<String> getPublicCalendars(String accessToken, String accessTokenSecret){
ArrayList<String> result = new ArrayList<String>();
CalendarFeed calendarResultFeed = null;
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(getFromSession(KEY_PARAM));
oauthParameters.setOAuthConsumerSecret(getFromSession(SECRET_PARAM));
oauthParameters.setOAuthToken(accessToken);
oauthParameters.setOAuthTokenSecret(accessTokenSecret);
oauthParameters.setOAuthType(OAuthParameters.OAuthType.THREE_LEGGED_OAUTH);
oauthParameters.setScope(getFromSession(SCOPE_PARAM));
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
try {
myService.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
URL calendarFeedUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");
calendarResultFeed = myService.getFeed(calendarFeedUrl, CalendarFeed.class);
} catch (OAuthException e) {
log.info("OAuthException");
log.log(Level.WARNING,e.toString());
e.printStackTrace();
} catch (MalformedURLException e) {
log.info("MalformedURLException");
log.log(Level.WARNING,e.toString());
e.printStackTrace();
} catch (IOException e) {
log.info("IOException");
log.log(Level.WARNING,e.toString());
e.printStackTrace();
} catch (ServiceException e) {
log.info("ServiceException");
log.log(Level.WARNING,e.toString());
e.printStackTrace();
}
if (calendarResultFeed != null && calendarResultFeed.getEntries() != null) {
for (int i = 0; i < calendarResultFeed.getEntries().size(); i++) {
CalendarEntry entry = calendarResultFeed.getEntries().get(i);
result.add(entry.getTitle().getPlainText());
}
}
return result;
}
private void getOauthParams(ServletContext context) {
this.getThreadLocalRequest().getSession()
.setAttribute(KEY_PARAM, context.getInitParameter(KEY_PARAM));
this.getThreadLocalRequest().getSession()
.setAttribute(SECRET_PARAM, context.getInitParameter(SECRET_PARAM));
this.getThreadLocalRequest().getSession()
.setAttribute(SCOPE_PARAM, context.getInitParameter(SCOPE_PARAM));
this.getThreadLocalRequest().getSession()
.setAttribute(CALLBACK_PARAM, context.getInitParameter(CALLBACK_PARAM));
}
private String getFromSession(String param){
return (String) this.getThreadLocalRequest().getSession().getAttribute(param);
}
}
I have recently been working with oAuth. Inside upgradeLogin(...) when you are upgrading to an access token you are not fetching the respective access token secret.
The access token secret following the getAccessToken() request is different to the access token secret before the request. You are currently setting the access token secret (via login.setAccessTokenSecret(oauthTS)), it is the pre-updated access token secret value you are using. You need to set it to the access token secret value returned after the update request:
String accesToken = oauthHelper.getAccessToken(oauthParameters);
String accesTokenSecret = oauthParameters.getOAuthTokenSecret();
login.setTokenSecret(accesToken);
login.setAccessTokenSecret(accesTokenSecret);
You also probably want to store this updated token/secret pair somewhere. It is this value of access token secret that should then to be used inside getPublicCalendars(...) in the line:
oauthParameters.setOAuthTokenSecret(accessTokenSecret);
The post update access token/secret pair is long-lived and can therefore be re-used (without needing to update it again) until such time as it is revoked.
Incidentally I found the oAuth Playground Tool useful in diagnosing my problems.
I hope this helps,
I am really not clear on explaining this requirement but what I need basically is a JSP page that connects to a Unix server and gets the word count of a file and displays on the JSP page. I have looked on various questions here but nothing helped. A sample code would be of much help. Thanks
Kavin, I guess you must have found some other solution or moved on by now. However, I just came across a requirement that led me to this page.
I looked through the somewhat smuckish responses on this page and many others but could not find a simple to use Telnet client at all.
I spent a little bit of time and wrote a simple client on top of Commons Net's solution. Please forgive the System.out and System.err in the code, I got it to barely work.
public static void main(String[] args) throws Exception {
SimpleTelnetClient client = new SimpleTelnetClient("localhost", 2323);
client.connect();
String result = client.waitFor("login:");
System.out.println("Got " + result);
client.send("username");
result = client.waitFor("Password:");
System.out.println("Got " + result);
client.send("password");
client.waitFor("#");
client.send("ls -al");
result = client.waitFor("#");
System.out.println("Got " + result);
client.send("exit");
}
Not sure if it will help you anymore, but perhaps it could be a starting point for others.
import java.io.InputStream;
import java.io.PrintStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
public class SimpleTelnetClient {
static class Responder extends Thread {
private StringBuilder builder = new StringBuilder();
private final SimpleTelnetClient checker;
private CountDownLatch latch;
private String waitFor = null;
private boolean isKeepRunning = true;
Responder(SimpleTelnetClient checker) {
this.checker = checker;
}
boolean foundWaitFor(String waitFor) {
return builder.toString().contains(waitFor);
}
public synchronized String getAndClearBuffer() {
String result = builder.toString();
builder = new StringBuilder();
return result;
}
#Override
public void run() {
while (isKeepRunning) {
String s;
try {
s = checker.messageQueue.take();
} catch (InterruptedException e) {
break;
}
synchronized (Responder.class) {
builder.append(s);
}
if (waitFor != null && latch != null && foundWaitFor(waitFor)) {
latch.countDown();
}
}
}
public String waitFor(String waitFor) {
synchronized (Responder.class) {
if (foundWaitFor(waitFor)) {
return getAndClearBuffer();
}
}
this.waitFor = waitFor;
latch = new CountDownLatch(1);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
String result = null;
synchronized (Responder.class) {
result = builder.toString();
builder = new StringBuilder();
}
return result;
}
}
static class TelnetReader extends Thread {
private final SimpleTelnetClient checker;
private final TelnetClient tc;
TelnetReader(SimpleTelnetClient checker, TelnetClient tc) {
this.checker = checker;
this.tc = tc;
}
#Override
public void run() {
InputStream instr = tc.getInputStream();
try {
byte[] buff = new byte[1024];
int ret_read = 0;
do {
ret_read = instr.read(buff);
if (ret_read > 0) {
checker.sendForResponse(new String(buff, 0, ret_read));
}
} while (ret_read >= 0);
} catch (Exception e) {
System.err.println("Exception while reading socket:" + e.getMessage());
}
try {
tc.disconnect();
checker.stop();
System.out.println("Disconnected.");
} catch (Exception e) {
System.err.println("Exception while closing telnet:" + e.getMessage());
}
}
}
private String host;
private BlockingQueue<String> messageQueue = new LinkedBlockingQueue<String>();
private int port;
private TelnetReader reader;
private Responder responder;
private TelnetClient tc;
public SimpleTelnetClient(String host, int port) {
this.host = host;
this.port = port;
}
protected void stop() {
responder.isKeepRunning = false;
responder.interrupt();
}
public void send(String command) {
PrintStream ps = new PrintStream(tc.getOutputStream());
ps.println(command);
ps.flush();
}
public void sendForResponse(String s) {
messageQueue.add(s);
}
public void connect() throws Exception {
tc = new TelnetClient();
TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
try {
tc.addOptionHandler(ttopt);
tc.addOptionHandler(echoopt);
tc.addOptionHandler(gaopt);
} catch (InvalidTelnetOptionException e) {
System.err.println("Error registering option handlers: " + e.getMessage());
}
tc.connect(host, port);
reader = new TelnetReader(this, tc);
reader.start();
responder = new Responder(this);
responder.start();
}
public String waitFor(String s) {
return responder.waitFor(s);
}
}
Why wouldn't you just use an open source telnet client. There is bound to be several to choose from. Google lists many.