Wednesday 28 August 2013

Top Most Twitter Contact Import source code in Java


package contactimport.action;

import static net.oauth.OAuth.HMAC_SHA1;
import static net.oauth.OAuth.OAUTH_SIGNATURE_METHOD;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthMessage;
import net.oauth.OAuthProblemException;
import net.oauth.ParameterStyle;
import net.oauth.client.OAuthResponseMessage;
import net.oauth.example.consumer.webapp.CookieConsumer;
import net.oauth.http.HttpMessage;
import net.oauth.http.HttpResponseMessage;

/**
 * A trivial consumer of the 'friends_timeline' service at Twitter.
 *
 *  */
public class TwitterConsumer extends HttpServlet {
private static final String forwardTo = "/twitterContactsScreenName.jsp";
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
       
        OAuthConsumer consumer = null;
        try {
            consumer = CookieConsumer.getConsumer("twitter", getServletContext());
            OAuthAccessor accessor = CookieConsumer.getAccessor(request, response, consumer);
            accessor.consumer.setProperty(OAUTH_SIGNATURE_METHOD, HMAC_SHA1);
            OAuthResponseMessage result = CookieConsumer.CLIENT.access(accessor.newRequestMessage(OAuthMessage.GET,
                    "http://api.twitter.com/1/statuses/followers.xml", null), ParameterStyle.AUTHORIZATION_HEADER);
           
           
            int status = result.getHttpResponse().getStatusCode();
            System.out.println(status);
            if (status != HttpResponseMessage.STATUS_OK) {
                OAuthProblemException problem = result.toOAuthProblemException();
                if (problem.getProblem() != null) {
                    throw problem;
                }
                Map<String, Object> dump = problem.getParameters();
                response.setContentType("text/plain");
                PrintWriter out = response.getWriter();
               
                out.println(dump.get(HttpMessage.REQUEST));
                out.println("----------------------");
                out.println(dump.get(HttpMessage.RESPONSE));
            } else {
                // Simply pass the data through to the browser:
            response.setContentType(result.getHeader("Content-Type"));
                InputStream in = result.getBodyAsStream();
                //CookieConsumer.copyResponse(result, response);
                try{
               DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
               DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
               Document doc = dBuilder.parse(in);
               doc.getDocumentElement().normalize();
               NodeList nList = doc.getElementsByTagName("user");
               System.out.println("-----------------------");
               List<String> contactScreenName=new ArrayList();
               List<String> contactScreenStatus=new ArrayList();
               HttpSession session =request.getSession(true);
               for (int temp = 0; temp < nList.getLength(); temp++) {
                  Node nNode = nList.item(temp);
                  if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                     Element eElement = (Element) nNode;
                     Element msg= (Element) eElement.getElementsByTagName("screen_name").item(0);
                     contactScreenName.add(msg.getNodeValue());
                     NodeList statusData =  eElement.getElementsByTagName("status");
                     for(int i=0;i<statusData.getLength();i++){
                     Node statusNode = statusData.item(i);
                     if (statusNode.getNodeType() == Node.ELEMENT_NODE) {
                     Element statusElement = (Element)statusNode;
                     Element text= (Element) statusElement.getElementsByTagName("text").item(0);
                     contactScreenStatus.add(text.getNodeValue());
                     }
                     }
                   
                   }
                   System.out.println("-----------------------");
               }
               session.setAttribute("contactScreenName",contactScreenName);
               request.getRequestDispatcher(forwardTo).forward(request, response);
                }catch (Exception e) {
                e.printStackTrace();
                }
            }
        } catch (Exception e) {
            CookieConsumer.handleException(e, request, response, consumer);
        }
    }
    private static String getTagValue(String sTag, Element eElement){
        NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);
        return nValue.getNodeValue();
    }
    private static final long serialVersionUID = 1L;

}

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt