Example usage for java.io ObjectInputStream ObjectInputStream

List of usage examples for java.io ObjectInputStream ObjectInputStream

Introduction

In this page you can find the example usage for java.io ObjectInputStream ObjectInputStream.

Prototype

public ObjectInputStream(InputStream in) throws IOException 

Source Link

Document

Creates an ObjectInputStream that reads from the specified InputStream.

Usage

From source file:ObjectStreams.java

public static void main(String[] args) throws IOException, ClassNotFoundException {

    ObjectOutputStream out = null;
    try {//from  ww  w .  j  av a  2 s. c  o  m
        out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));

        out.writeObject(Calendar.getInstance());
        for (int i = 0; i < prices.length; i++) {
            out.writeObject(prices[i]);
            out.writeInt(units[i]);
            out.writeUTF(descs[i]);
        }
    } finally {
        out.close();
    }

    ObjectInputStream in = null;
    try {
        in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dataFile)));

        Calendar date = null;
        BigDecimal price;
        int unit;
        String desc;
        BigDecimal total = new BigDecimal(0);

        date = (Calendar) in.readObject();

        System.out.format("On %tA, %<tB %<te, %<tY:%n", date);

        try {
            while (true) {
                price = (BigDecimal) in.readObject();
                unit = in.readInt();
                desc = in.readUTF();
                System.out.format("You ordered %d units of %s at $%.2f%n", unit, desc, price);
                total = total.add(price.multiply(new BigDecimal(unit)));
            }
        } catch (EOFException e) {
        }
        System.out.format("For a TOTAL of: $%.2f%n", total);
    } finally {
        in.close();
    }
}

From source file:com.nabla.project.application.tool.runner.ServiceRunner.java

/**
 * DOCUMENT ME!/*from   w  ww .j av a2  s.  c  om*/
 * 
 * @param args DOCUMENT ME!
 * @throws Exception DOCUMENT ME!
 * @throws RuntimeException DOCUMENT ME!
 */
public static void main(String args[]) throws Exception {

    ObjectInputStream ois = new ObjectInputStream(System.in);
    Object methodArgs[] = (Object[]) ois.readObject();

    if (args.length < 3) {

        throw new RuntimeException(
                "Error : usage : java com.nabla.project.application.tool.runner.ServiceRunner configFileName beanName methodName");

    }

    String configFileName = args[0];
    String beanName = args[1];
    String methodName = args[2];
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { configFileName });
    Object service = context.getBean(beanName);
    Method serviceMethod = null;
    Method methods[] = service.getClass().getMethods();

    for (Method method : methods) {

        if (method.getName().equals(methodName)) {

            serviceMethod = method;

        }

    }

    if (serviceMethod == null) {

        throw new RuntimeException("Method " + methodName + " not found in class " + service.getClass());

    }

    serviceMethod.invoke(service, methodArgs);

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String WRITE_OBJECT_SQL = "BEGIN " + "  INSERT INTO java_objects(object_id, object_name, object_value) "
            + "  VALUES (?, ?, empty_blob()) " + "  RETURN object_value INTO ?; " + "END;";
    String READ_OBJECT_SQL = "SELECT object_value FROM java_objects WHERE object_id = ?";

    Connection conn = getOracleConnection();
    conn.setAutoCommit(false);/*w w w  .ja v a  2s .  c  om*/
    List<Object> list = new ArrayList<Object>();
    list.add("This is a short string.");
    list.add(new Integer(1234));
    list.add(new java.util.Date());

    // write object to Oracle
    long id = 0001;
    String className = list.getClass().getName();
    CallableStatement cstmt = conn.prepareCall(WRITE_OBJECT_SQL);

    cstmt.setLong(1, id);
    cstmt.setString(2, className);

    cstmt.registerOutParameter(3, java.sql.Types.BLOB);

    cstmt.executeUpdate();
    BLOB blob = (BLOB) cstmt.getBlob(3);
    OutputStream os = blob.getBinaryOutputStream();
    ObjectOutputStream oop = new ObjectOutputStream(os);
    oop.writeObject(list);
    oop.flush();
    oop.close();
    os.close();

    // Read object from oracle
    PreparedStatement pstmt = conn.prepareStatement(READ_OBJECT_SQL);
    pstmt.setLong(1, id);
    ResultSet rs = pstmt.executeQuery();
    rs.next();
    InputStream is = rs.getBlob(1).getBinaryStream();
    ObjectInputStream oip = new ObjectInputStream(is);
    Object object = oip.readObject();
    className = object.getClass().getName();
    oip.close();
    is.close();
    rs.close();
    pstmt.close();
    conn.commit();

    // de-serialize list a java object from a given objectID
    List listFromDatabase = (List) object;
    System.out.println("[After De-Serialization] list=" + listFromDatabase);
    conn.close();
}

From source file:edu.msu.cme.rdp.graph.sandbox.BloomFilterInterrogator.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("USAGE: BloomFilterStats <bloom_filter>");
        System.exit(1);/*from   www . ja v a  2 s  .c o m*/
    }

    File bloomFile = new File(args[0]);

    ObjectInputStream ois = ois = new ObjectInputStream(
            new BufferedInputStream(new FileInputStream(bloomFile)));
    BloomFilter filter = (BloomFilter) ois.readObject();
    ois.close();

    printStats(filter, System.out);

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String line;
    CodonWalker walker = null;
    while ((line = reader.readLine()) != null) {
        char[] kmer = line.toCharArray();
        System.out.print(line + "\t");
        try {
            walker = filter.new RightCodonFacade(kmer);
            walker.jumpTo(kmer);
            System.out.print("present");
        } catch (Exception e) {
            System.out.print("not present\t" + e.getMessage());
        }
        System.out.println();
    }
}

From source file:Cache.Servidor.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    // Se calcula el tamao de las particiones del cache
    // de manera que la relacin sea
    // 25% Esttico y 75% Dinmico,
    // siendo la porcin dinmica particionada en 3 partes.

    Lector l = new Lector(); // Obtener tamao total del cache.
    int tamCache = l.leerTamCache("config.txt");
    //===================================
    int tamCaches = 0;
    if (tamCache % 4 == 0) { // Asegura que el nro sea divisible por 4.
        tamCaches = tamCache / 4;//w  w w.  j  a  va2s  . c  om
    } else { // Si no, suma para que lo sea.
        tamCaches = (tamCache - (tamCache) % 4 + 4) / 4;
    } // y divide por 4.

    System.out.println("Tamao total Cache: " + (int) tamCache); // imprimir tamao cache.
    System.out.println("Tamao particiones y parte esttica: " + tamCaches); // imprimir tamao particiones.
    //===================================

    lru_cache1 = new LRUCache(tamCaches); //Instanciar atributos.

    lru_cache2 = new LRUCache(tamCaches);
    lru_cache3 = new LRUCache(tamCaches);
    cestatico = new CacheEstatico(tamCaches);
    cestatico.addEntryToCache("query3", "respuesta cacheEstatico a query 3");
    cestatico.addEntryToCache("query7", "respuesta cacheEstatico a query 7");

    try {
        ServerSocket servidor = new ServerSocket(4500); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            System.out.println("Objeto llego");
            //===================================
            Cache1 hilox1 = new Cache1(); // Instanciar hebras.
            Cache2 hilox2 = new Cache2();
            Cache3 hilox3 = new Cache3();

            // Leer el objeto, es un String.
            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("busqueda");

            //*************************Actualizar CACHE**************************************
            int actualizar = (int) request.get("actualizacion");
            // Si vienen el objeto que llego viene del Index es que va a actualizar el cache
            if (actualizar == 1) {
                int lleno = cestatico.lleno();
                if (lleno == 0) {
                    cestatico.addEntryToCache((String) request.get("busqueda"),
                            (String) request.get("respuesta"));
                } else {
                    // si el cache estatico esta lleno
                    //agrego l cache dinamico

                    if (hash(b) % 3 == 0) {
                        lru_cache1.addEntryToCache((String) request.get("busqueda"),
                                (String) request.get("respuesta"));
                    } else {
                        if (hash(b) % 3 == 1) {
                            lru_cache2.addEntryToCache((String) request.get("busqueda"),
                                    (String) request.get("respuesta"));

                        } else {
                            lru_cache3.addEntryToCache((String) request.get("busqueda"),
                                    (String) request.get("respuesta"));

                        }
                    }

                }
            } //***************************************************************
            else {

                // Para cada request del arreglo se distribuye
                // en Cache 1 2 o 3 segn su hash.
                JSONObject respuesta = new JSONObject();
                if (hash(b) % 3 == 0) {
                    respuesta = hilox1.fn(request); //Y corre la funcin de una hebra.
                } else {
                    if (hash(b) % 3 == 1) {
                        respuesta = hilox2.fn(request);
                    } else {
                        respuesta = hilox3.fn(request);
                    }
                }

                //RESPONDER DESDE EL SERVIDOR
                ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj
                resp.writeObject(respuesta);
                System.out.println("msj enviado desde el servidor");

                //clienteNuevo.close();
                //servidor.close();
            }

        }
    } catch (IOException ex) {
        Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.msu.cme.rdp.graph.utils.BloomFilterStats.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("USAGE: BloomFilterStats <bloom_filter>");
        System.exit(1);//  w ww  . j  av a 2 s  .  co m
    }

    File bloomFile = new File(args[0]);

    ObjectInputStream ois = ois = new ObjectInputStream(
            new BufferedInputStream(new FileInputStream(bloomFile)));
    BloomFilter filter = (BloomFilter) ois.readObject();
    ois.close();

    printStats(filter, System.out);
}

From source file:edu.msu.cme.rdp.graph.sandbox.CheckReadKmerPresence.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("USAGE: CheckReadKmerPresence <bloom_filter> <nucl_seq_file>");
        System.exit(1);/*from w  w w .java  2s.  c  o  m*/
    }

    File bloomFile = new File(args[0]);
    SeqReader reader = new SequenceReader(new File(args[1]));

    ObjectInputStream ois = ois = new ObjectInputStream(
            new BufferedInputStream(new FileInputStream(bloomFile)));
    BloomFilter filter = (BloomFilter) ois.readObject();
    ois.close();

    printStats(filter, System.out);
    Sequence seq;
    CodonWalker walker = null;
    while ((seq = reader.readNextSequence()) != null) {
        int kmerNum = 0;
        for (char[] kmer : KmerGenerator.getKmers(seq.getSeqString(), filter.getKmerSize())) {
            System.out.print(seq.getSeqName() + "\t" + (++kmerNum) + "\t" + kmer + "\t");
            try {
                walker = filter.new RightCodonFacade(kmer);
                System.out.println("true");
            } catch (Exception e) {
                System.out.println("false");
            }

        }
    }
}

From source file:ComplexCompany.java

public static void main(String args[]) throws Exception {
    Socket socket1;//  www. j a v a  2  s  .c o m
    int portNumber = 1777;
    String str = "";

    socket1 = new Socket(InetAddress.getLocalHost(), portNumber);

    ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream());

    ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream());

    ComplexCompany comp = new ComplexCompany("A");
    ComplexEmployee emp0 = new ComplexEmployee("B", 1000);
    comp.addPresident(emp0);

    ComplexDepartment sales = new ComplexDepartment("C");
    ComplexEmployee emp1 = new ComplexEmployee("D", 1200);
    sales.addManager(emp1);
    comp.addDepartment(sales);

    ComplexDepartment accounting = new ComplexDepartment("E");
    ComplexEmployee emp2 = new ComplexEmployee("F", 1230);
    accounting.addManager(emp2);
    comp.addDepartment(accounting);

    ComplexDepartment maintenance = new ComplexDepartment("Maintenance");
    ComplexEmployee emp3 = new ComplexEmployee("Greg Hladlick", 1020);
    maintenance.addManager(emp3);
    comp.addDepartment(maintenance);

    oos.writeObject(comp);

    while ((str = (String) ois.readObject()) != null) {
        System.out.println(str);
        oos.writeObject("bye");

        if (str.equals("bye"))
            break;
    }

    ois.close();
    oos.close();
    socket1.close();
}

From source file:com.linkedin.sample.Main.java

public static void main(String[] args) {

    /*/*w w  w.j av  a 2 s  .co m*/
    we need a OAuthService to handle authentication and the subsequent calls.
    Since we are going to use the REST APIs we need to generate a request token as the first step in the call.
    Once we get an access toke we can continue to use that until the API key changes or auth is revoked.
    Therefore, to make this sample easier to re-use we serialize the AuthHandler (which stores the access token) to
    disk and then reuse it.
            
    When you first run this code please insure that you fill in the API_KEY and API_SECRET above with your own
    credentials and if there is a service.dat file in the code please delete it.
            
     */

    //The Access Token is used in all Data calls to the APIs - it basically says our application has been given access
    //to the approved information in LinkedIn
    Token accessToken = null;

    //Using the Scribe library we enter the information needed to begin the chain of Oauth2 calls.
    OAuthService service = new ServiceBuilder().provider(LinkedInApi.class).apiKey(API_KEY)
            .apiSecret(API_SECRET).build();

    /*************************************
     * This first piece of code handles all the pieces needed to be granted access to make a data call
     */

    try {
        File file = new File("service.dat");

        if (file.exists()) {
            //if the file exists we assume it has the AuthHandler in it - which in turn contains the Access Token
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
            AuthHandler authHandler = (AuthHandler) inputStream.readObject();
            accessToken = authHandler.getAccessToken();
        } else {
            System.out.println("There is no stored Access token we need to make one");
            //In the constructor the AuthHandler goes through the chain of calls to create an Access Token
            AuthHandler authHandler = new AuthHandler(service);
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("service.dat"));
            outputStream.writeObject(authHandler);
            outputStream.close();
            accessToken = authHandler.getAccessToken();
        }

    } catch (Exception e) {
        System.out.println("Threw an exception when serializing: " + e.getClass() + " :: " + e.getMessage());
    }

    /*
     * We are all done getting access - time to get busy getting data
     *************************************/

    /**************************
     *
     * Querying the LinkedIn API
     *
     **************************/

    System.out.println();
    System.out.println("********A basic user profile call********");
    //The ~ means yourself - so this should return the basic default information for your profile in XML format
    //https://developer.linkedin.com/documents/profile-api
    String url = "http://api.linkedin.com/v1/people/~";
    OAuthRequest request = new OAuthRequest(Verb.GET, url);
    service.signRequest(accessToken, request);
    Response response = request.send();
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    System.out.println("********Get the profile in JSON********");
    //This basic call profile in JSON format
    //You can read more about JSON here http://json.org
    url = "http://api.linkedin.com/v1/people/~";
    request = new OAuthRequest(Verb.GET, url);
    request.addHeader("x-li-format", "json");
    service.signRequest(accessToken, request);
    response = request.send();
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    System.out.println("********Get the profile in JSON using query parameter********");
    //This basic call profile in JSON format. Please note the call above is the preferred method.
    //You can read more about JSON here http://json.org
    url = "http://api.linkedin.com/v1/people/~";
    request = new OAuthRequest(Verb.GET, url);
    request.addQuerystringParameter("format", "json");
    service.signRequest(accessToken, request);
    response = request.send();
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    System.out.println("********Get my connections - going into a resource********");
    //This basic call gets all your connections each one will be in a person tag with some profile information
    //https://developer.linkedin.com/documents/connections-api
    url = "http://api.linkedin.com/v1/people/~/connections";
    request = new OAuthRequest(Verb.GET, url);
    service.signRequest(accessToken, request);
    response = request.send();
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    System.out.println("********Get only 10 connections - using parameters********");
    //This basic call gets only 10 connections  - each one will be in a person tag with some profile information
    //https://developer.linkedin.com/documents/connections-api
    //more basic about query strings in a URL here http://en.wikipedia.org/wiki/Query_string
    url = "http://api.linkedin.com/v1/people/~/connections";
    request = new OAuthRequest(Verb.GET, url);
    request.addQuerystringParameter("count", "10");
    service.signRequest(accessToken, request);
    response = request.send();
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    System.out.println("********GET network updates that are CONN and SHAR********");
    //This basic call get connection updates from your connections
    //https://developer.linkedin.com/documents/get-network-updates-and-statistics-api
    //specifics on updates  https://developer.linkedin.com/documents/network-update-types

    url = "http://api.linkedin.com/v1/people/~/network/updates";
    request = new OAuthRequest(Verb.GET, url);
    request.addQuerystringParameter("type", "SHAR");
    request.addQuerystringParameter("type", "CONN");
    service.signRequest(accessToken, request);
    response = request.send();
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    System.out.println("********People Search using facets and Encoding input parameters i.e. UTF8********");
    //This basic call get connection updates from your connections
    //https://developer.linkedin.com/documents/people-search-api#Facets
    //Why doesn't this look like
    //people-search?title=developer&location=fr&industry=4

    //url = "http://api.linkedin.com/v1/people-search?title=D%C3%A9veloppeur&facets=location,industry&facet=location,fr,0";
    url = "http://api.linkedin.com/v1/people-search:(people:(first-name,last-name,headline),facets:(code,buckets))";
    request = new OAuthRequest(Verb.GET, url);
    request.addQuerystringParameter("title", "Dveloppeur");
    request.addQuerystringParameter("facet", "industry,4");
    request.addQuerystringParameter("facets", "location,industry");
    System.out.println(request.getUrl());
    service.signRequest(accessToken, request);
    response = request.send();
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    /////////////////field selectors
    System.out.println("********A basic user profile call with field selectors********");
    //The ~ means yourself - so this should return the basic default information for your profile in XML format
    //https://developer.linkedin.com/documents/field-selectors
    url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions)";
    request = new OAuthRequest(Verb.GET, url);
    service.signRequest(accessToken, request);
    response = request.send();
    System.out.println(response.getHeaders().toString());
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    System.out
            .println("********A basic user profile call with field selectors going into a subresource********");
    //The ~ means yourself - so this should return the basic default information for your profile in XML format
    //https://developer.linkedin.com/documents/field-selectors
    url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions:(company:(name)))";
    request = new OAuthRequest(Verb.GET, url);
    service.signRequest(accessToken, request);
    response = request.send();
    System.out.println(response.getHeaders().toString());
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    System.out.println("********A basic user profile call into a subresource return data in JSON********");
    //The ~ means yourself - so this should return the basic default information for your profile
    //https://developer.linkedin.com/documents/field-selectors
    url = "https://api.linkedin.com/v1/people/~/connections:(first-name,last-name,headline)?format=json";
    request = new OAuthRequest(Verb.GET, url);
    service.signRequest(accessToken, request);
    response = request.send();
    System.out.println(response.getHeaders().toString());
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    System.out.println("********A more complicated example using postings into groups********");
    //https://developer.linkedin.com/documents/field-selectors
    //https://developer.linkedin.com/documents/groups-api
    url = "http://api.linkedin.com/v1/groups/3297124/posts:(id,category,creator:(id,first-name,last-name),title,summary,creation-timestamp,site-group-post-url,comments,likes)";
    request = new OAuthRequest(Verb.GET, url);
    service.signRequest(accessToken, request);
    response = request.send();
    System.out.println(response.getHeaders().toString());
    System.out.println(response.getBody());
    System.out.println();
    System.out.println();

    /**************************
     *
     * Wrting to the LinkedIn API
     *
     **************************/

    /*
     * Commented out so we don't write into your LinkedIn/Twitter feed while you are just testing out
     * some code. Uncomment if you'd like to see writes in action.
     * 
     * 
            System.out.println("********Write to the  share - using XML********");
            //This basic shares some basic information on the users activity stream
            //https://developer.linkedin.com/documents/share-api
            url = "http://api.linkedin.com/v1/people/~/shares";
            request = new OAuthRequest(Verb.POST, url);
            request.addHeader("Content-Type", "text/xml");
            //Make an XML document
            Document doc = DocumentHelper.createDocument();
            Element share = doc.addElement("share");
            share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs");
            Element content = share.addElement("content");
            content.addElement("title").addText("A title for your share");
            content.addElement("submitted-url").addText("http://developer.linkedin.com");
            share.addElement("visibility").addElement("code").addText("anyone");
            request.addPayload(doc.asXML());
            service.signRequest(accessToken, request);
            response = request.send();
            //there is no body just a header
            System.out.println(response.getBody());
            System.out.println(response.getHeaders().toString());
            System.out.println();System.out.println();
            
            
            System.out.println("********Write to the  share and to Twitter - using XML********");
            //This basic shares some basic information on the users activity stream
            //https://developer.linkedin.com/documents/share-api
            url = "http://api.linkedin.com/v1/people/~/shares";
            request = new OAuthRequest(Verb.POST, url);
            request.addQuerystringParameter("twitter-post","true");
            request.addHeader("Content-Type", "text/xml");
            //Make an XML document
            doc = DocumentHelper.createDocument();
            share = doc.addElement("share");
            share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs and sending to twitter");
            content = share.addElement("content");
            content.addElement("title").addText("A title for your share");
            content.addElement("submitted-url").addText("http://developer.linkedin.com");
            share.addElement("visibility").addElement("code").addText("anyone");
            request.addPayload(doc.asXML());
            service.signRequest(accessToken, request);
            response = request.send();
            //there is no body just a header
            System.out.println(response.getBody());
            System.out.println(response.getHeaders().toString());
            System.out.println();System.out.println();
            
            
            
            
            
            System.out.println("********Write to the  share and to twitter - using JSON ********");
            //This basic shares some basic information on the users activity stream
            //https://developer.linkedin.com/documents/share-api
            //NOTE - a good troubleshooting step is to validate your JSON on jsonlint.org
            url = "http://api.linkedin.com/v1/people/~/shares";
            request = new OAuthRequest(Verb.POST, url);
            //set the headers to the server knows what we are sending
            request.addHeader("Content-Type", "application/json");
            request.addHeader("x-li-format", "json");
            //make the json payload using json-simple
            Map<String, Object> jsonMap = new HashMap<String, Object>();
            jsonMap.put("comment", "Posting from the API using JSON");
            JSONObject contentObject = new JSONObject();
            contentObject.put("title", "This is a another test post");
            contentObject.put("submitted-url","http://www.linkedin.com");
            contentObject.put("submitted-image-url", "http://press.linkedin.com/sites/all/themes/presslinkedin/images/LinkedIn_WebLogo_LowResExample.jpg");
            jsonMap.put("content", contentObject);
            JSONObject visibilityObject = new JSONObject();
            visibilityObject.put("code", "anyone");
            jsonMap.put("visibility", visibilityObject);
            request.addPayload(JSONValue.toJSONString(jsonMap));
            service.signRequest(accessToken, request);
            response = request.send();
            //again no body - just headers
            System.out.println(response.getBody());
            System.out.println(response.getHeaders().toString());
            System.out.println();System.out.println();
    */

    /**************************
     *
     * Understanding the response, creating logging, request and response headers
     *
     **************************/

    System.out.println();
    System.out.println("********A basic user profile call and response dissected********");
    //This sample is mostly to help you debug and understand some of the scaffolding around the request-response cycle
    //https://developer.linkedin.com/documents/debugging-api-calls
    url = "https://api.linkedin.com/v1/people/~";
    request = new OAuthRequest(Verb.GET, url);
    service.signRequest(accessToken, request);
    response = request.send();
    //get all the headers
    System.out.println("Request headers: " + request.getHeaders().toString());
    System.out.println("Response headers: " + response.getHeaders().toString());
    //url requested
    System.out.println("Original location is: " + request.getHeaders().get("content-location"));
    //Date of response
    System.out.println("The datetime of the response is: " + response.getHeader("Date"));
    //the format of the response
    System.out.println("Format is: " + response.getHeader("x-li-format"));
    //Content-type of the response
    System.out.println("Content type is: " + response.getHeader("Content-Type") + "\n\n");

    //get the HTTP response code - such as 200 or 404
    int responseNumber = response.getCode();

    if (responseNumber >= 199 && responseNumber < 300) {
        System.out.println("HOORAY IT WORKED!!");
        System.out.println(response.getBody());
    } else if (responseNumber >= 500 && responseNumber < 600) {
        //you could actually raise an exception here in your own code
        System.out.println("Ruh Roh application error of type 500: " + responseNumber);
        System.out.println(response.getBody());
    } else if (responseNumber == 403) {
        System.out.println("A 403 was returned which usually means you have reached a throttle limit");
    } else if (responseNumber == 401) {
        System.out.println("A 401 was returned which is a Oauth signature error");
        System.out.println(response.getBody());
    } else if (responseNumber == 405) {
        System.out.println(
                "A 405 response was received. Usually this means you used the wrong HTTP method (GET when you should POST, etc).");
    } else {
        System.out.println("We got a different response that we should add to the list: " + responseNumber
                + " and report it in the forums");
        System.out.println(response.getBody());
    }
    System.out.println();
    System.out.println();

    System.out.println("********A basic error logging function********");
    // Now demonstrate how to make a logging function which provides us the info we need to
    // properly help debug issues. Please use the logged block from here when requesting
    // help in the forums.
    url = "https://api.linkedin.com/v1/people/FOOBARBAZ";
    request = new OAuthRequest(Verb.GET, url);
    service.signRequest(accessToken, request);
    response = request.send();

    responseNumber = response.getCode();

    if (responseNumber < 200 || responseNumber >= 300) {
        logDiagnostics(request, response);
    } else {
        System.out.println("You were supposed to submit a bad request");
    }

    System.out.println("******Finished******");

}

From source file:Shape.java

public static void main(String[] args) throws Exception {
    List shapeTypes, shapes;//from  ww w. j a va2  s  .  c  om
    if (args.length == 0) {
        shapeTypes = new ArrayList();
        shapes = new ArrayList();
        // Add references to the class objects:
        shapeTypes.add(Circle.class);
        shapeTypes.add(Square.class);
        shapeTypes.add(Line.class);
        // Make some shapes:
        for (int i = 0; i < 10; i++)
            shapes.add(Shape.randomFactory());
        // Set all the static colors to GREEN:
        for (int i = 0; i < 10; i++)
            ((Shape) shapes.get(i)).setColor(Shape.GREEN);
        // Save the state vector:
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("CADState.out"));
        out.writeObject(shapeTypes);
        Line.serializeStaticState(out);
        out.writeObject(shapes);
    } else { // There's a command-line argument
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(args[0]));
        // Read in the same order they were written:
        shapeTypes = (List) in.readObject();
        Line.deserializeStaticState(in);
        shapes = (List) in.readObject();
    }
    // Display the shapes:
    System.out.println(shapes);
}