agileinterop.AgileInterop.java Source code

Java tutorial

Introduction

Here is the source code for agileinterop.AgileInterop.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package agileinterop;

import com.agile.api.*;
import com.dexcom.agile.Agile;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.yamlbeans.YamlException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 *
 * @author mburny
 */
public class AgileInterop {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        JSONObject obj;

        try {
            String username, password, agileUrl, operation, body;

            username = args[0];
            password = args[1];
            agileUrl = args[2];
            operation = args[3];
            body = args[4];

            // Connect to Agile
            Agile.connect(username, password, agileUrl);

            switch (operation) {
            case "getPSRData":
                obj = getPSRData(body);
                break;
            case "getPSRList":
                obj = getPSRList(body);
                break;
            case "getPSRCellValues":
                obj = getPSRCellValues(body);
                break;
            case "getRelatedPSRs":
                obj = getRelatedPSRs(body);
                break;
            case "createRelatedPSRs":
                obj = createRelatedPSRs(body);
                break;
            case "writeNewDataToPSRs":
                obj = writeNewDataToPSRs(body);
                break;
            case "attachFileToPSR":
                obj = attachFileToPSR(body);
                break;
            case "crawlAgileByDateOriginated":
                obj = crawlAgileByDateOriginated(body);
                break;
            case "crawlAgileByPSRList":
                obj = crawlAgileByPSRList(body);
                break;
            default:
                throw new AssertionError();
            }

            obj.put("status", "success");

        } catch (APIException | ParseException | InterruptedException ex) {
            obj = new JSONObject();
            obj.put("status", "error");
            obj.put("data", ex.getMessage());
        } catch (Exception ex) {
            obj = new JSONObject();
            obj.put("status", "error");
            obj.put("data", ex.getMessage());
        }

        System.out.print(obj.toJSONString());
    }

    /**
     * Example:
     * {
     *     "startDate": "02/12/2014",
     *     "endDate": "03/01/2014",
     *     "database": "C:\\Users\\mburny\\Desktop\\AgileBot\\mt\\agile.db",
     *     "map": "C:\\Users\\mburny\\Desktop\\AgileBot\\mt\\map.json"
     * }
     * 
     * @param body
     * @return
     * @throws ParseException 
     */
    private static JSONObject crawlAgileByDateOriginated(String body) throws ParseException {
        // Parse body as JSON
        JSONParser parser = new JSONParser();
        JSONObject jsonBody = (JSONObject) parser.parse(body);

        return null;
    }

    /**
     * Example:
     * {
     *     "psrNumbers": ["SR-123456", "SR-234567", "SR-345678", "SR-456789"],
     *     "database": "C:\\Users\\mburny\\Desktop\\AgileBot\\mt\\agile.db",
     *     "map": "C:\\Users\\mburny\\Desktop\\AgileBot\\mt\\map.json"
     * }
     * 
     * @param body
     * @return 
     * @throws ParseException
     */
    private static JSONObject crawlAgileByPSRList(String body) throws ParseException {
        // Parse body as JSON
        JSONParser parser = new JSONParser();
        JSONArray jsonBody = (JSONArray) parser.parse(body);

        return null;
    }

    private static JSONObject getPSRData(String body) throws ParseException, InterruptedException, APIException {
        // Parse body as JSON
        JSONParser parser = new JSONParser();
        JSONArray jsonBody = (JSONArray) parser.parse(body);

        Map<String, Object> data = new HashMap<>();

        class GetObjectData implements Runnable {
            private String psrNumber;
            private Map<String, Object> data;
            private IServiceRequest psr;

            public GetObjectData(String psrNumber, Map<String, Object> data)
                    throws APIException, InterruptedException {
                this.psrNumber = psrNumber;
                this.data = data;

                psr = (IServiceRequest) Agile.session.getObject(IServiceRequest.OBJECT_TYPE, psrNumber);
            }

            @Override
            public void run() {
                this.data.put(psrNumber, new HashMap<String, Object>());

                try {
                    if (psr != null) {
                        getCellValues();
                        getAttachments();
                        getHistory();
                    }
                } catch (APIException ex) {
                    Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            private void getCellValues() throws APIException {
                Map<String, Object> cellValues = new HashMap<>();

                long startTime = System.currentTimeMillis();

                // Get cell values
                ICell[] cells = psr.getCells();
                for (ICell cell : cells) {
                    if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                        if (cell.getValue() != null) {
                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                            sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                            cellValues.put(cell.getName(), sdf.format((Date) cell.getValue()));
                        } else {
                            cellValues.put(cell.getName(), cell.toString());
                        }
                    } else {
                        cellValues.put(cell.getName(), cell.toString());
                    }
                }

                long endTime = System.currentTimeMillis();

                String logMessage = String.format("%s: getCellValues executed in %d milliseconds", psrNumber,
                        endTime - startTime);
                System.out.println(logMessage);

                ((HashMap<String, Object>) this.data.get(psrNumber)).put("cellValues", cellValues);
            }

            private void getAttachments() throws APIException {
                List<Map<String, String>> attachments = new ArrayList<>();

                long startTime = System.currentTimeMillis();

                // Get attachments information
                ITable table = psr.getTable("Attachments");
                ITwoWayIterator tableIterator = table.getTableIterator();
                while (tableIterator.hasNext()) {
                    IRow row = (IRow) tableIterator.next();
                    Map<String, String> attachment = new HashMap<>();

                    ICell[] cells = row.getCells();
                    for (ICell cell : cells) {
                        if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                            if (cell.getValue() != null) {
                                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                                sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                                attachment.put(cell.getName(), sdf.format((Date) cell.getValue()));
                            } else {
                                attachment.put(cell.getName(), cell.toString());
                            }
                        } else {
                            attachment.put(cell.getName(), cell.toString());
                        }
                    }

                    attachments.add(attachment);
                }

                long endTime = System.currentTimeMillis();

                String logMessage = String.format("%s: getAttachments executed in %d milliseconds", psrNumber,
                        endTime - startTime);
                System.out.println(logMessage);

                ((HashMap<String, Object>) this.data.get(psrNumber)).put("attachments", attachments);
            }

            private void getHistory() throws APIException {
                List<Map<String, String>> histories = new ArrayList<>();

                long startTime = System.currentTimeMillis();

                // Get history information
                ITable table = psr.getTable("History");
                ITwoWayIterator tableIterator = table.getTableIterator();
                while (tableIterator.hasNext()) {
                    IRow row = (IRow) tableIterator.next();
                    Map<String, String> history = new HashMap<>();

                    ICell[] cells = row.getCells();
                    for (ICell cell : cells) {
                        if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                            if (cell.getValue() != null) {
                                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                                sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                                history.put(cell.getName(), sdf.format((Date) cell.getValue()));
                            } else {
                                history.put(cell.getName(), cell.toString());
                            }
                        } else {
                            history.put(cell.getName(), cell.toString());
                        }
                    }

                    histories.add(history);
                }

                long endTime = System.currentTimeMillis();

                String logMessage = String.format("%s: getHistory executed in %d milliseconds", psrNumber,
                        endTime - startTime);
                System.out.println(logMessage);

                ((HashMap<String, Object>) this.data.get(psrNumber)).put("history", histories);
            }
        }

        synchronized (data) {
            // Do something funky with the first one
            Thread t = new Thread(new GetObjectData(jsonBody.get(0).toString(), data));
            t.start();
            t.join();

            ExecutorService executor = Executors.newFixedThreadPool(10);
            for (Object object : jsonBody.subList(1, jsonBody.size() - 1)) {
                executor.execute(new Thread(new GetObjectData(object.toString(), data)));
            }

            executor.shutdown();
            while (!executor.isTerminated()) {
            }
        }

        JSONObject obj = new JSONObject();
        obj.put("data", data);
        return obj;
    }

    private static JSONObject getPSRList(String body)
            throws ParseException, InterruptedException, java.text.ParseException, Exception {
        // Parse body as JSON
        JSONParser parser = new JSONParser();
        JSONObject jsonBody = (JSONObject) parser.parse(body);

        Date startDateOriginated = new SimpleDateFormat("MM/dd/yyyy")
                .parse(jsonBody.get("startDateOriginated").toString());
        Date endDateOriginated = new SimpleDateFormat("MM/dd/yyyy")
                .parse(jsonBody.get("endDateOriginated").toString());

        List<String> data = new ArrayList<>();

        class getPSRListForDate implements Runnable {
            private Date dateOriginated;
            private List<String> data;

            public getPSRListForDate(Date dateOriginated, List<String> data) {
                this.dateOriginated = dateOriginated;
                this.data = data;
            }

            public getPSRListForDate(List<String> data) {
                this.data = data;
            }

            @Override
            public void run() {
                try {
                    String dateOriginatedString = new SimpleDateFormat("MM/dd/yyyy").format(dateOriginated);

                    Long startTime = System.currentTimeMillis();

                    IQuery query = (IQuery) Agile.session.createObject(IQuery.OBJECT_TYPE,
                            "Product Service Requests");

                    String criteria = "[Cover Page.Date Originated] == '" + dateOriginatedString
                            + " 12:00:00 AM GMT' AND "
                            + "[Cover Page.Type] IN ('Customer Complaint', 'Customer Inquiry', 'Partner Complaint', "
                            + "'Reportable Malfunction / Adverse Event', 'Ancillary Devices & Applications', 'Distributors / Partners', "
                            + "'MDR Decision Tree', 'Investigation Report - No RGA', 'Investigation Report - RGA')";
                    query.setCriteria(criteria);

                    query.setResultAttributes(new Integer[] { 4856 }); // 4856 = Object ID of [Cover Page.PSR Number]

                    ITable queryResults = query.execute();
                    queryResults.setPageSize(5000);

                    ITwoWayIterator tableIterator = queryResults.getTableIterator();
                    while (tableIterator.hasNext()) {
                        IRow row = (IRow) tableIterator.next();
                        data.add(row.getCell(4856).toString()); // 4856 = Object ID of [Cover Page.PSR Number]
                    }

                    Long endTime = System.currentTimeMillis();

                    String logMessage = String.format("getPSRList: Query for %s executed in %d milliseconds",
                            new SimpleDateFormat("yyyy-MM-dd").format(dateOriginated), endTime - startTime);
                    System.out.println(logMessage);
                } catch (APIException ex) {
                    Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        if (startDateOriginated.after(endDateOriginated)) {
            throw new Exception("startDateOriginated is after endDateOriginated. This makes no sense, silly.");
        }

        synchronized (data) {
            Date currentDateOriginated = startDateOriginated;

            ExecutorService executor = Executors.newFixedThreadPool(6);
            do {
                executor.execute(new Thread(new getPSRListForDate(currentDateOriginated, data)));

                Calendar c = Calendar.getInstance();
                c.setTime(currentDateOriginated);
                c.add(Calendar.DATE, 1);

                currentDateOriginated = c.getTime();
            } while (currentDateOriginated.before(endDateOriginated)
                    | currentDateOriginated.equals(endDateOriginated));

            executor.shutdown();
            while (!executor.isTerminated()) {
            }
        }

        JSONObject obj = new JSONObject();
        obj.put("data", data);
        return obj;
    }

    private static JSONObject getPSRCellValues(String body)
            throws UnsupportedOperationException, YamlException, APIException {
        String[] psrNumbers = body.split(",");

        // Trim and upper case all PSR numbers
        for (int i = 0; i < psrNumbers.length; i++) {
            psrNumbers[i] = psrNumbers[i].trim().toUpperCase();
        }

        Map<String, Map<String, String>> data = new HashMap<>();
        for (String psrNumber : psrNumbers) {
            Map<String, String> psrData = new HashMap<>();

            IServiceRequest psr = (IServiceRequest) Agile.session.getObject(IServiceRequest.OBJECT_TYPE, psrNumber);

            ICell[] cells = psr.getCells();
            for (ICell cell : cells) {
                String cellName = cell.getName();

                if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                    if (cell.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                        sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                        psrData.put(cell.getName(), sdf.format((Date) cell.getValue()));
                    } else {
                        psrData.put(cell.getName(), cell.toString());
                    }
                } else {
                    psrData.put(cell.getName(), cell.toString());
                }
            }

            data.put(psrNumber, psrData);
        }

        JSONObject obj = new JSONObject();
        obj.put("data", data);
        return obj;
    }

    private static JSONObject getRelatedPSRs(String body) throws APIException, ParseException {
        // Parse body as JSON
        JSONParser parser = new JSONParser();
        JSONArray jsonBody = (JSONArray) parser.parse(body);

        Map<String, List<String>> data = new HashMap<>();

        for (Object psrNumber : jsonBody) {
            List<String> relatedPSRNumbers = Agile.getRelatedPSRs((String) psrNumber);
            data.put((String) psrNumber, relatedPSRNumbers);
        }

        JSONObject obj = new JSONObject();
        obj.put("data", data);
        return obj;
    }

    private static JSONObject createRelatedPSRs(String body)
            throws UnsupportedOperationException, ParseException, APIException {
        // Parse body as JSON
        JSONParser parser = new JSONParser();
        JSONObject jsonBody = (JSONObject) parser.parse(body);

        Map<String, List<String>> data = new HashMap<>();

        for (Iterator it = jsonBody.entrySet().iterator(); it.hasNext();) {
            Map.Entry pair = (Map.Entry) it.next();

            String psrNumber = (String) pair.getKey();
            JSONArray relatedPSRTypes = (JSONArray) pair.getValue();

            List<String> relatedPSRNumbers = new ArrayList<>();
            for (Object relatedPSRType : relatedPSRTypes) {
                String relatedPSRNumber = Agile.createRelatedPSR(psrNumber, (String) relatedPSRType);
                relatedPSRNumbers.add(relatedPSRNumber);
            }

            data.put(psrNumber, relatedPSRNumbers);
        }

        JSONObject obj = new JSONObject();
        obj.put("data", data);
        return obj;
    }

    private static JSONObject writeNewDataToPSRs(Object body) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    private static JSONObject attachFileToPSR(Object body) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

}