com.simplenoteapp.test.Test.java Source code

Java tutorial

Introduction

Here is the source code for com.simplenoteapp.test.Test.java

Source

/*
 * Test.java
 *
 * Copyright  2010, Stephen Perry.
 *
 * This file is part of Simplenote BlackBerry.
 *
 * Simplenote BlackBerry is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * 
 * Simplenote BlackBerry is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Simplenote BlackBerry.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

package com.simplenoteapp.test;

import com.simplenoteapp.simplenote.Simplenote;
import com.simplenoteapp.simplenote.SimplenoteRequester;
import com.simplenoteapp.simplenote.NoteInfo;

import org.apache.commons.codec.binary.Base64;

import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;

public class Test implements Simplenote.LoginListener, Simplenote.GetIndexListener, Simplenote.CreateNoteListener {
    private static String CREATE = "create";
    private static String INDEX = "index";

    private Simplenote simpleNote = new Simplenote(new DesktopRequester());
    private String command;
    private String username;
    private String password;

    public Test(String command, String username, String password) {
        this.command = command;
        this.username = username;
        this.password = password;
    }

    static void log(String msg) {
        System.out.println(msg);
    }

    private void error(String msg, Exception e) {
        System.err.print(msg);
        if (e != null) {
            System.err.println(e.getMessage());
            e.printStackTrace(System.err);
        }
        System.err.print('\n');
        System.exit(1);
    }

    private void error(String msg) {
        error(msg, null);
    }

    private String readNote() {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer buf = new StringBuffer();
        String s;
        try {
            while ((s = in.readLine()) != null) {
                buf.append(s);
                buf.append('\n');
            }
            in.close();
        } catch (IOException e) {
            error("Read note", e);
        }
        return buf.toString();
    }

    public void run() {
        simpleNote.login(username, password, this);
    }

    public void loginSucceeded() {
        if (command.equals(CREATE)) {
            simpleNote.createNote(readNote(), this);
        } else if (command.equals(INDEX)) {
            simpleNote.getIndex(this);
        } else
            /* Should check for this failure before logging in, but
             * it's only a test app...
             */
            usage();
    }

    public void loginFailed(Exception e) {
        error("Login failed:", e);
    }

    public void getIndexSucceeded(Vector noteInfo) {
        for (Enumeration e = noteInfo.elements(); e.hasMoreElements();) {
            NoteInfo i = (NoteInfo) e.nextElement();
            System.out.println("Key: " + i.getKey());
            System.out.println("Last modified: " + i.getModifiedDate());
            System.out.println("Deleted: " + i.isDeleted());
            System.out.print('\n');
        }
        System.exit(0);
    }

    public void getIndexFailed(Exception e) {
        error("Get index failed:", e);
    }

    public void createNoteSucceeded(String key) {
        System.out.println("Created note with key: " + key);
        System.exit(0);
    }

    public void createNoteFailed(Exception e) {
        error("Create note failed:", e);
    }

    private static void usage() {
        System.err.println("Usage: java com.simplenoteapp.test.Test index|create username password");
        System.exit(1);
    }

    public static void main(String[] args) {
        if (args.length != 3)
            usage();

        new Test(args[0], args[1], args[2]).run();
    }
}

class DesktopRequester implements SimplenoteRequester {

    private static final int BUFFER_SIZE = 1024;

    private String readResponse(InputStream is) throws IOException {
        char cbuf[] = new char[BUFFER_SIZE];
        StringBuffer sbuf = new StringBuffer();
        BufferedReader r = null;
        try {
            r = new BufferedReader(new InputStreamReader(is));
            for (;;) {
                int n = r.read(cbuf, 0, BUFFER_SIZE);
                if (n == -1)
                    break;
                sbuf.append(cbuf, 0, n);
            }
        } finally {
            try {
                r.close();
            } catch (IOException e) {
            }
        }
        return sbuf.toString();
    }

    /**
     * Fetch the given URI and return the contents as a string.
     * @param uri to be fetched
     * @return content returned from the request
     * @throws IOException an IO error occurred
     */
    public String get(String uriString) throws IOException {
        URL url = new URL(uriString);
        return readResponse(url.openStream());
    }

    /**
     * Base 64 encode the given data and post it to uri.
     * @param uri to which the data is to be posted
     * @param postData string to be converted to UTF-8, then encoded
     * as base 64 and posted to uri
     * @return content returned from the request
     * @throws IOException
     */
    public String postBase64(String uriString, String postData) throws IOException {
        Test.log("postBase64 uri=" + uriString + " data=" + postData);
        byte[] base64 = Base64.encodeBase64(postData.getBytes(), false, false);
        Test.log("base64=" + new String(base64));

        URL url = new URL(uriString);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStream out = conn.getOutputStream();
        out.write(base64);
        out.flush();
        String response = readResponse(conn.getInputStream());
        out.close();
        return response;
    }
}