kante / Tangra

Tangra: A web-based tool for administering research studies and tracking participant progress.
1 stars 0 forks source link

Java sample code for interfacing with Tangra instance #28

Open kante opened 10 years ago

kante commented 10 years ago

I have some code I used for Dr. Yaakov Stern's project that we can use as starter code.

Ideally we would use this to create a simple proof of concept/starter code study on an android device. Something that just goes through two stages, saves data from the first stage, and displays in in the next should be pretty straightforward.

kante commented 10 years ago
package tangra;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class TangraSession 
{
    String serverURL;
    HttpClient httpclient;
    HttpPost httppost;
    HttpContext localContext;
    BasicCookieStore cookieStore;

    public String username = null;
    public String password = null;
    public String stageName = null;
    public int currentStageNumber = -1;
    public String currentTrialString = null;

    // Pretty useless... must have used this for testing before. 
    //  should probably be deleted?
    public static void main(String args[])
    {
        TangraSession session = new TangraSession("localhost:8000");
        session.authenticate("d", "d");
        session.finishSession();

    }

    /**
     * Constructor
     */   
    public TangraSession(String aServerURL)
    {
        serverURL = aServerURL;
        httpclient = new DefaultHttpClient();
        localContext = new BasicHttpContext();
        cookieStore = new BasicCookieStore();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    }

    public void finishSession()
    {
        HttpGet httpget = new HttpGet("http://" + serverURL + "/exe_interface/fsess");

        try {
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httpget);
            String stringResponse = convertStreamToString( response.getEntity().getContent());

            if (!stringResponse.equals("OK")) {
                System.out.println("WARNING: fsess was not successful!!!!!");
                FileWriter fstream = new FileWriter(System.getProperty("java.io.tmpdir")+"tangralog.html");
                 BufferedWriter out = new BufferedWriter(fstream);
                 out.write(stringResponse);
                 out.close();
            }

            EntityUtils.consume(response.getEntity());

        } catch (ClientProtocolException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 
     */
    public void postFile(String filePaths)
    {
        HttpPost httppost = new HttpPost("http://" + this.serverURL + "/investigator/upload_file/" + this.username);
        File file = new File(filePaths);
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file, "text/plain");
        mpEntity.addPart("file", cbFile);

        httppost.setEntity(mpEntity);
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response;
        try {
            response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (resEntity != null) {
                System.out.println(EntityUtils.toString(resEntity));
            }
            if (resEntity != null) {
                resEntity.consumeContent();
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //httpclient.getConnectionManager().shutdown();
    }

    /**
     * 
     * @param is
     * @return
     */
    public static String convertStreamToString(java.io.InputStream is) 
    {
        try {
            return new java.util.Scanner(is).useDelimiter("\\A").next();
        } catch (java.util.NoSuchElementException e) {
            return "";
        }
    }

    public void getStageData()
    {
        HttpGet httpget = new HttpGet("http://" + serverURL + "/exe_interface/get_current_stage_info");

        try {

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httpget);
            String stringResponse = convertStreamToString( response.getEntity().getContent());
            String[] stageData = stringResponse.split(",");
            String nameData = stageData[0];
            this.stageName = nameData.substring(nameData.indexOf(":")+1, nameData.length());

            String numData = stageData[1];
            this.currentStageNumber = Integer.parseInt(numData.substring(numData.indexOf(":")+1, numData.length()));

            String trialStringData = stageData[2];
            this.currentTrialString = trialStringData.substring(trialStringData.indexOf(":")+1, trialStringData.length());

            EntityUtils.consume(response.getEntity());

        } catch (ClientProtocolException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }

    /**
     * authenticate - Attempt to 
     * @param username
     * @param password
     * @return
     */
    public boolean authenticate(String username, String password)
    {  
         httppost = new HttpPost("http://" + serverURL + "/exe_interface/login");

         try {
             // Add your data
             ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
             nameValuePairs.add(new BasicNameValuePair("username", username));
             nameValuePairs.add(new BasicNameValuePair("password", password));
             UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
             httppost.setEntity(entity);

             // Execute HTTP Post Request
             HttpResponse response = httpclient.execute(httppost);

             System.out.println(response.toString());
             String tangraReply = convertStreamToString(response.getEntity().getContent());
             EntityUtils.consume(entity);

             if (tangraReply.equals("Logged in successfully!")) {
                 this.username = username;
                 this.password = password;

                 return true;
             } else { 
                 return false;
             }

         } catch (ClientProtocolException e) {
             System.out.println("Client protocol exception:" + e.getMessage());
             return false;
         } catch (IOException e) {
             System.out.println("IOException: " + e.getMessage());
             return false;
         }
    }
}
kante commented 10 years ago
TangraSession session = new TangraSession("localhost:8000");
String username = strUserID;
String password = new String(jpwdField.getPassword());

Boolean loginSuccess = tangraSession.authenticate(strTemp, password);

if (!loginSuccess) {
    jtitleLabel.setText("Could not log in. Please try again." );
} 

tangraSession.finishSession();