Error while fetching connection to linkedin - java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
final LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(CONSUMER_KEY, CONSUMER_KEY_SECRET);
try {
StringBuffer callbackURL = request.getRequestURL();
int index = callbackURL.lastIndexOf("/");
callbackURL.replace(index, callbackURL.length(), "").append("/LinkedInCallbackServlet");
LinkedInRequestToken requestToken = oauthService.getOAuthRequestToken(callbackURL.toString());
request.getSession().setAttribute("requestToken", requestToken);
System.out.println("token:"+requestToken);
System.out.println("Success");
String path=callbackURL.toString();
String verifier = request.getParameter("oauth_verifier");
System.out.println("----"+verifier);
response.sendRedirect(requestToken.getAuthorizationUrl());
} catch (LinkedInApiClientException e) {
throw new ServletException(e);
}
}
/** * #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stubss
}
When it run this code then shows error:
HTTP Status 500 - oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Server returned HTTP response code: 403 for URL: https://api.linkedin.com/uas/oauth/requestToken

Related

HttpServletresponse after response reset for new get data

I use the doGet method to get the parameter and then process it. When the reply is sent, it contains the status data. Also, when the second client connects, the answer contains the data from frist client.
I want the send new the data after the second client is connected. Reset buffer and send new data to second client the data, or after restoring the page send new data.
Its not working. The client retrieves the page again and sends me a old and new data. I need only new data to be sent to client.
class HttpTest extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HttpTest() {
super();
// TODO Auto-generated constructor stub
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
System.out.println(request.getQueryString());
String[] parameters = request.getQueryString().split(";");
String out_data="";
/*
* algorithm for generate out data
*/
out.println(out_data);
out.flush();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
try this might help
private void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
try (PrintWriter writer = response.getWriter()) {
System.out.println(request.getQueryString());
String[] parms = request.getQueryString().split(";");
String outData = "";
/*
* algorithm for generate out data
*/
writer.println(outData);
}
}

java.lang.ClassNotFoundException: com.csvreader.CsvReader

I'm developing an application for sending bulk emails from multiple senders in a continuous loop. Sender email-ID's are stored in a csv file and I am reading that in ReadFile class and calling it in servlet class where I am also calling an email utility class which have email sending functions.
ReadFile.java
CsvReader senders;
public List<String> read(){
ArrayList<String> al=new ArrayList<String>();
try {
senders = new CsvReader("C:/Users/dc/Documents/Senderlist.csv");
senders.readHeaders();
while (senders.readRecord()) {
String SenderID = senders.get("SenderID");
// perform program logic here
System.out.println("Sender ID is: "+SenderID );
al.add(SenderID);
}
senders.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return al;
}
Servlet.java:
public class MailController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String ExchangeIP;
private String port;
ReadFile rf;
/**
* #throws IOException
* #see HttpServlet#HttpServlet()
*/
public MailController() throws IOException {
rf=new ReadFile();
}
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
ExchangeIP = context.getInitParameter("ExchangeIP");
port = context.getInitParameter("port");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// read from field
List<File> uploadedFiles= saveUploadedFiles(request);
String sender=request.getParameter("sender");// reading from the form page
String recipient=request.getParameter("recipient");
String subject=request.getParameter("subject");
String content=request.getParameter("content");
String resultMessage = ""; //null
try {
List sendersInput = rf.read();
// print all the elements in the list
Iterator itr = sendersInput.iterator();
while(itr.hasNext()) {
EmailUtility.sendEmail(ExchangeIP, port, itr.next(), recipient, subject, content, uploadedFiles);
resultMessage = "The e-mail has been sent successfully";
}
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
request.setAttribute("Message", resultMessage);
getServletContext()
.getRequestDispatcher("/Result.jsp")
.forward(request, response);
}
}
}
While running this I am getting an error:
java.lang.ClassNotFoundException: com.csvreader.CsvReader
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at com.project.util.ReadFile.read(ReadFile.java:20)
at com.project.controller.MailController.doPost(MailController.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
How to resolve this error.
You're missing the opencsv.jar library.
Specify it in your java command with
java -cp opencsv.jar:...
By adding servlet-api.jar from apache tomcat library in to projects->properties->java build path, Solved the error.

java servlet submit button doesn't work

I'm been writing a small login servlet. The login part works just fine, but when I press logout submit button - nothing happens.
Servlet code down bellow:
public class LoginServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 7638796169158385551L;
private Database database = Database.getInstance();
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.write("<html><head><title>Login form</title></head>");
if (!database.connected) {
outLoginForm(out);
} else {
out.write("Hello " + database.getLoginName() + "!");
outLogoutForm(out);
}
out.write("</body></html>");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (request.getParameter("loginsub") != null) {
if (isParameterEmpty(request, "login")
|| isParameterEmpty(request, "pass")) {
response.getWriter().write("Some fields are empty");
doGet(request, response);
}
try {
database.connect(request.getParameter("login"),
request.getParameter("pass"));
} catch (ExceptionInInitializerError ex) {
response.getWriter().write("Login or password is incorrect");
}
} else if (request.getParameter("logoutsub") != null) {
database.disconnect();
}
doGet(request, response);
}
private boolean isParameterEmpty(HttpServletRequest request,
String parameter) {
if (request.getParameter(parameter).isEmpty())
return true;
return false;
}
protected void outLoginForm(PrintWriter out) {
out.write("<FORM method =\"POST\">");
out.write("Login:<input type=\"text\"name=\"login\"><br>");
out.write("Password:<input type=\"password\"name=\"pass\"><br>");
out.write("<input type=\"submit\"name=\"loginsub\" value=\"Login\"/><br>");
out.write("</FORM><br>");
}
protected void outLogoutForm(PrintWriter out) {
out.write("<FORM method =\"POST>\">");
out.write("<input type=\"submit\"name=\"logoutsub\" value=\"Logout\"/><br>");
out.write("</FORM><br>");
}
}
Can anyone help me find out what's wrong? I'm new to JSP and java servlets.
There is one problem is below line (one extra > after POST
out.write("<FORM method =\"POST>\">");
replace it with
out.write("<FORM method =\"POST\">");

Null Pointer Exception while communicating between servlets

I have login code in one servlet:LoginGtalkServlet..
XMPPConnection connection;
//#see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(userName);
System.out.println(password);
//ProxyInfo proxyInfo = new
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com",5222,"gmail.com");
connection = new XMPPConnection(config);
config.setSASLAuthenticationEnabled(false);
try {
connection.connect();
} catch (XMPPException e) {
e.printStackTrace();
}
try {
connection.login(userName, password);
} catch (XMPPException e) {
e.printStackTrace();
}
boolean status=connection.isAuthenticated();
if(status==true)
{
System.out.println("Success");
response.sendRedirect("GetRoster");
}
else
{
response.sendRedirect("Loginfailed.html");
}
And my GetRosterServlet has the code for retreving the roster list
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry r : entries) {
String user = r.getUser();
String name = r.getName();
System.out.println(name + user);
}
roster.addRosterListener(new RosterListener() {
// Ignored events public void entriesAdded(Collection<String>
// addresses) {}
public void entriesDeleted(Collection<String> addresses) {
}
public void entriesUpdated(Collection<String> addresses) {
}
public void presenceChanged(Presence presence) {
System.out.println("Presence changed: " + presence.getFrom()
+ " " + presence);
}
#Override
public void entriesAdded(Collection<String> arg0) {
}
});
}
Now the isssue is my GetRosterServlet is not informed that I haved logged into Gtalk..i.e LoginGtalkServlet is not communicating with GetRosterServlet and hence connection.getRoster() is throwing Null pointer exception...
How do I let the roster servlet know that the user is logged into gtalk and hence get the friends list
Note that I'm not familiar with XMPP/GTalk.
When you log in to it in LoginGtalkServlet, is it possible for you to be handed back some sort of session ID? If so, you could put that into the redirect URL as a query parameter or in a POST body and then GetRosterServlet could extract the session ID from request and use it to Gtalk via that session ID.
(Note: the edit I just made was just to fix some bad grammar. No substantive changes.)
You can save the connection object in the session attribute.
session .setAttribute("connection", connectionObj);
And can get by using session.getAttribute("connection");

Can I implement HttpSessionListener this way?

I'm trying to tracking valid user Ids in my Java servlet, can I implement HttpSessionListener this way ?
public class my_Servlet extends HttpServlet implements HttpSessionListener
{
String User_Id;
static Vector<String> Valid_User_Id_Vector=new Vector<String>();
private static int activeSessions=0;
public void sessionCreated(HttpSessionEvent se)
{
// associate User_Id with session Id;
// add User_Id to Valid_User_Id_Vector
Out(" sessionCreated : "+se.getSession().getId());
activeSessions++;
}
public void sessionDestroyed(HttpSessionEvent se)
{
if (activeSessions>0)
{
// remove User_Id from Valid_User_Id_Vector by identifing it's session Id
Out(" sessionDestroyed : "+se.getSession().getId());
activeSessions--;
}
}
public static int getActiveSessions()
{
return activeSessions;
}
public void init(ServletConfig config) throws ServletException
{
}
public void destroy()
{
}
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
User_Id=request.getParameter("User_Id");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
public String getServletInfo()
{
return "Short description";
}
}
How to get the listener notified when a session ends ? I'm trying to bypass "/WEB-INF.web.xml" all together, is it doable ? Or does it make sense ?
This won't bypass /WEB-INF/web.xml. Furthermore, you'll end up with 2 instances of this class, not 1 performing both functions. I suggest you put this Vector in the ServletContext and have 2 separate classes.
In the servlet, you get to it via getServletContext(). In the listener, you'll do something like this:
public void sessionCreated(HttpSessionEvent se) {
Vector ids = (Vector) se.getSession().getServletContext().getAttribute("currentUserIds");
//manipulate ids
}

Categories