Skip to content

Instantly share code, notes, and snippets.

@awrowse
Created June 22, 2012 21:28
Show Gist options
  • Save awrowse/2975303 to your computer and use it in GitHub Desktop.
Save awrowse/2975303 to your computer and use it in GitHub Desktop.
Java CWS Demo
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.rightnow.ps.example;
import com.rightnow.ws.base.*;
import com.rightnow.ws.faults.*;
import com.rightnow.ws.messages.*;
import com.rightnow.ws.objects.*;
import com.rightnow.ws.generic.*;
import com.rightnow.ws.metadata.MetaDataClass;
import com.rightnow.ws.objects.Thread;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.ConsoleHandler;
import org.apache.axis2.AxisFault;
/* Service imports */
import com.rightnow.ws.wsdl.RightNowSyncService;
import com.rightnow.ws.wsdl.RightNowSyncServiceStub;
/* Security Header Imports */
import com.rightnow.ws.wsdl.ServerErrorFault;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.*;
import javax.activation.DataHandler;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.OMNamespaceImpl;
import org.apache.axiom.om.impl.llom.OMElementImpl;
import org.apache.axiom.soap.impl.llom.soap11.SOAP11Factory;
import org.apache.ws.security.WSConstants;
import org.apache.axis2.client.ServiceClient;
/**
*
* @author andy.rowse
*/
public class DemoApp {
RightNowSyncService _service;
Logger _log;
public DemoApp(String username, String password) throws AxisFault {
_log = Logger.getLogger(this.getClass().getName());
_log.setLevel(Level.ALL);
_service = new RightNowSyncServiceStub();
ServiceClient serviceClient = ((org.apache.axis2.client.Stub) _service)._getServiceClient();
serviceClient.addHeader(createSecurityHeader(username, password));
}
private OMElement createSecurityHeader(String username, String password) {
OMNamespaceImpl wsseNS = new OMNamespaceImpl(WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX);
OMFactory factory = new SOAP11Factory();
OMElementImpl securityHeader;
OMElementImpl usernameTokenElement;
OMElementImpl usernameElement;
OMElementImpl passwordElement;
// create the Security header block
securityHeader = new OMElementImpl("Security", wsseNS, factory);
securityHeader.addAttribute("mustUnderstand", "1", null);
// nest the UsernameToken in the Security header
usernameTokenElement = new OMElementImpl(WSConstants.USERNAME_TOKEN_LN, wsseNS, securityHeader, factory);
// nest the Username and Password elements
usernameElement = new OMElementImpl(WSConstants.USERNAME_LN, wsseNS, usernameTokenElement, factory);
usernameElement.setText(username);
passwordElement = new OMElementImpl(WSConstants.PASSWORD_LN, wsseNS, usernameTokenElement, factory);
passwordElement.setText(password);
passwordElement.addAttribute(WSConstants.PASSWORD_TYPE_ATTR,
WSConstants.PASSWORD_TEXT, null);
return securityHeader;
}
public ClientInfoHeader getClientInfoHeader() {
ClientInfoHeader clientInfoHeader = new ClientInfoHeader();
clientInfoHeader.setAppID("Demo App");
return clientInfoHeader;
}
public GetProcessingOptions getGetProcessingOptions() {
GetProcessingOptions options = new GetProcessingOptions();
options.setFetchAllNames(true);
return options;
}
public CreateProcessingOptions getCreateProcessingOptions() {
CreateProcessingOptions options = new CreateProcessingOptions();
options.setSuppressExternalEvents(true);
options.setSuppressRules(true);
return options;
}
public Answer getAnswer(Integer id) throws RemoteException {
/* Create ID Object */
ID answerID = new ID();
answerID.setId(id);
/* Get empty answer object */
Answer myAnswer = new Answer();
/* Set ID object on answer to facilitate fetching */
myAnswer.setID(answerID);
/* Put our object into a collection */
RNObject[] objects = new RNObject[]{myAnswer};
/* Finally, get everything from the server */
RNObjectsResult getResults = null;
try {
getResults = _service.get(objects, getGetProcessingOptions(), getClientInfoHeader());
} catch (ServerErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
} catch (com.rightnow.ws.wsdl.RequestErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
} catch (com.rightnow.ws.wsdl.UnexpectedErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
}
/* Now turn the results into something usable */
RNObject[] rnObjects = getResults.getRNObjects();
myAnswer = (Answer) rnObjects[0];
return myAnswer;
}
public Incident testIncident() throws RemoteException {
Incident newIncident = new Incident();
//IncidentContact
IncidentContact incContact = new IncidentContact();
NamedID contactNamedID = new NamedID();
ID contactID = new ID();
//contactID.setId(Long.valueOf(fields.get("clientid").toString()));
contactID.setId(5711);
contactNamedID.setID(contactID);
incContact.setContact(contactNamedID);
newIncident.setPrimaryContact(incContact);
//Set Category or Topic - Subtopic
NamedIDHierarchy catNameId = new NamedIDHierarchy();
//ID catagoryID = new ID();
//catagoryID.setId(Integer.parseInt(fields.get("topic").toString()));
//catNameId.setID(catagoryID);
catNameId.setName("Hospital Inpatient - AMI");
NamedIDHierarchy[] catNamedIdHierarchyArray = new NamedIDHierarchy[]{catNameId};
NamedIDHierarchyList catNamedIdHierarchyList = new NamedIDHierarchyList();
catNamedIdHierarchyList.setNamedIDHierarchyList(catNamedIdHierarchyArray);
newIncident.setCategory(catNameId);
// Set Status to Public
NamedID swtNamedID = new NamedID();
//swtNamedID.setName(fields.get("status").toString());
swtNamedID.setName("Assigned");
StatusWithType swt = new StatusWithType();
swt.setStatus(swtNamedID);
newIncident.setStatusWithType(swt);
// Check Question for length and trim to 240 for summary
//String question = fields.get("question").toString();
String question = "This is my question";
String summary = question;
if (question.length() > 240) {
summary = question.substring(0, 240);
}
newIncident.setSubject(summary);
ThreadList questionThreadList = new ThreadList();
Thread questionThread = new Thread();
NamedID questionEntryType = new NamedID();
questionEntryType.setName("Customer");
questionThread.setEntryType(questionEntryType);
questionThread.setText(question);
questionThreadList.addThreadList(questionThread);
newIncident.setThreads(questionThreadList);
RNObjectsResult createResults = null;
RNObject[] objects = new RNObject[]{newIncident};
try {
createResults = this._service.create(objects, this.getCreateProcessingOptions(), this.getClientInfoHeader());
} catch (ServerErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
} catch (com.rightnow.ws.wsdl.RequestErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
} catch (com.rightnow.ws.wsdl.UnexpectedErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
}
Incident new_inc = (Incident) createResults.getRNObjects()[0];
System.out.println(new_inc.getID().getId());
RNObject[] fetchObjects = new RNObject[]{new_inc};
RNObjectsResult getResults = null;
try {
getResults = this._service.get(fetchObjects, this.getGetProcessingOptions(), this.getClientInfoHeader());
} catch (ServerErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
} catch (com.rightnow.ws.wsdl.RequestErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
} catch (com.rightnow.ws.wsdl.UnexpectedErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
}
new_inc = (Incident) getResults.getRNObjects()[0];
System.out.println(new_inc.getReferenceNumber());
return newIncident;
}
private Contact populateContactInfo(String email, String phone) throws RemoteException {
RNObject[] saveobjects = null;
Contact newContact = null;
try {
newContact = new Contact();
PersonName contactName = new PersonName();
contactName.setLast(email);
newContact.setName(contactName);
//Build an E-MailList object
EmailList emailList = new EmailList();
//Build the Email array, here we populate a single e-mail address
Email[] emailArray = new Email[1];
emailArray[0] = new Email();
emailArray[0].setAction(ActionEnum.add);
emailArray[0].setAddress(email);
//Set the type of e-mail
NamedID emailType = new NamedID();
ID emailTypeID = new ID();
emailTypeID.setId(0);
emailType.setID(emailTypeID);
//Add the address type to the e-mail object
emailArray[0].setAddressType(emailType);
emailList.setEmailList(emailArray);
//Build a PhoneList object
PhoneList phoneList = new PhoneList();
// Build the Phone array, populate a single phone number
Phone[] phoneArray = new Phone[1];
phoneArray[0] = new Phone();
phoneArray[0].setAction(ActionEnum.add);
phoneArray[0].setNumber(phone);
//set the type of Phone Number
NamedID phoneType = new NamedID();
ID phoneTypeID = new ID();
phoneTypeID.setId(0);
phoneType.setID(phoneTypeID);
//Add the phone type to the phone object
phoneArray[0].setPhoneType(phoneType);
phoneList.setPhoneList(phoneArray);
//Add the PhoneList and EmailList to the new Contact object
//newContact.setName(personName);
newContact.setEmails(emailList);
newContact.setPhones(phoneList);
newContact.setLogin(email);
saveobjects = new RNObject[]{ newContact };
} catch(Exception ex){
System.out.println(ex.getMessage());
}
try {
RNObjectsResult result = this._service.create(saveobjects, this.getCreateProcessingOptions(), this.getClientInfoHeader());
} catch (ServerErrorFault ex) {
_log.log(Level.SEVERE, ex.getMessage(), ex);
} catch (com.rightnow.ws.wsdl.RequestErrorFault ex) {
_log.log(Level.SEVERE, ex.getFaultMessage().getRequestErrorFault().getExceptionMessage(), ex);
} catch (com.rightnow.ws.wsdl.UnexpectedErrorFault ex) {
_log.log(Level.SEVERE, ex.getMessage(), ex);
}
return newContact;
}
public long queryCSVEmail(String email) throws RemoteException {
CSVTableSet queryCSV = null;
ClientInfoHeader clientInfoHeader = new ClientInfoHeader();
long returnValue = -1;
clientInfoHeader.setAppID("RightNow QUEST Import");
String queryString = "SELECT ID from Contact where Login = '" + email + "' OR Emails.EmailList.Address = '" + email + "'";
try {
queryCSV = _service.queryCSV(queryString, 1000, clientInfoHeader);
} catch (ServerErrorFault ex) {
_log.log(Level.SEVERE, ex.getMessage(), ex);
} catch (com.rightnow.ws.wsdl.RequestErrorFault ex) {
_log.log(Level.SEVERE, ex.getFaultMessage().getRequestErrorFault().getExceptionMessage(), ex);
} catch (com.rightnow.ws.wsdl.UnexpectedErrorFault ex) {
_log.log(Level.SEVERE, ex.getMessage(), ex);
}
CSVTables csvTables = queryCSV.getCSVTables();
for (CSVTable table : csvTables.getCSVTable()) {
//System.out.println("Name: " + table.getName());
//System.out.println("Columns: " + table.getColumns());
CSVRow row = table.getRows();
String[] rowData = row.getRow();
try {
for (String data : rowData) {
//System.out.println("Row Data: " + data);
returnValue = Long.valueOf(data);
}
} catch (NullPointerException ex) {
returnValue = -1;
}
}
return returnValue;
}
public long queryByRefNo2 (String refno) throws RemoteException {
CSVTableSet queryObjects = null;
long returnValue = -1;
// String queryString = "SELECT * FROM SMC.SMCAttachment WHERE SMC.SMCAttachment.SMCThread.Incidents.ReferenceNumber = '120530-000025';"
// + "SELECT * FROM SMC.SMCThread WHERE SMC.SMCThread.Incidents.ReferenceNumber = '120530-000025';";
String queryString = "SELECT Incident.Threads.* FROM Incident WHERE Incident.ReferenceNumber = '120530-000025';";
// + "SELECT * FROM SMC.SMCThread WHERE SMC.SMCThread.Incidents.ReferenceNumber = '120530-000025';";
try {
queryObjects = _service.queryCSV(queryString, 10000, this.getClientInfoHeader());
CSVTables csvTables = queryObjects.getCSVTables();
for (CSVTable table : csvTables.getCSVTable()) {
//System.out.println("Name: " + table.getName());
//System.out.println("Columns: " + table.getColumns());
CSVRow row = table.getRows();
String columns = table.getColumns();
System.out.println("Columns: " + columns);
String[] rowData = row.getRow();
try {
for (String data : rowData) {
System.out.println("Row Data: " + data);
}
} catch (NullPointerException ex) {
returnValue = -1;
}
}
} catch (ServerErrorFault ex) {
_log.log(Level.SEVERE, ex.getMessage(), ex);
} catch (com.rightnow.ws.wsdl.RequestErrorFault ex) {
_log.log(Level.SEVERE, ex.getFaultMessage().getRequestErrorFault().getExceptionMessage(), ex);
} catch (com.rightnow.ws.wsdl.UnexpectedErrorFault ex) {
_log.log(Level.SEVERE, ex.getMessage(), ex);
}
System.out.println("Query returned");
return returnValue;
}
public CSVTable getReportData(Integer report_id_value, Integer limit, Integer start){
//Create new AnalyticsReport Object
AnalyticsReport analyticsReport = new AnalyticsReport();
//Specify a report ID
ID reportID = new ID();
reportID.setId(report_id_value);
analyticsReport.setID(reportID);
try
{
CSVTableSet runAnalyticsReportResult = _service.runAnalyticsReport(analyticsReport, limit, start, this.getClientInfoHeader());
CSVTables csvTables = runAnalyticsReportResult.getCSVTables();
for (CSVTable table : csvTables.getCSVTable()) {
_log.log(Level.INFO, "Name: " + table.getName());
_log.log(Level.INFO, "Columns: " + table.getColumns());
return table;
}
}
catch (RemoteException ex) {
_log.log(Level.SEVERE, null, ex);
}
catch (ServerErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
}
catch (com.rightnow.ws.wsdl.RequestErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
}
catch (com.rightnow.ws.wsdl.UnexpectedErrorFault ex) {
_log.log(Level.SEVERE, null, ex);
}
return null;
}
public void getFileData(Integer incidentid, Integer fileid) throws IOException{
DataHandler fileData = null;
ID fileID = new ID();
fileID.setId(fileid);
Incident incident = new Incident();
ID incidentID = new ID();
incidentID.setId(incidentid);
incident.setID(incidentID);
//Calc start time
long startTime=System.currentTimeMillis();
_log.log(Level.INFO, "StartTime: " + startTime);
//Retrieve data
try {
//System.out.println(" before calling to get the file "+System.currentTimeMillis());
fileData = _service.getFileData(incident,fileID, false, this.getClientInfoHeader());
} catch (Exception ex) {
_log.log(Level.SEVERE, null, ex);
}
//Calc end time
long endTime=System.currentTimeMillis();
long duration = endTime - startTime;
_log.log(Level.INFO, "EndTime: " + endTime);
_log.log(Level.INFO, "Duration: " + Float.valueOf(duration) / 1000 + " seconds");
//Calc file size
byte[] my_bytes = toBytes(fileData);
_log.log(Level.INFO, "File size in kilobytes: " + Float.valueOf(my_bytes.length) / 1024);
}
public static byte[] toBytes(DataHandler handler) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
handler.writeTo(output);
return output.toByteArray();
}
public void getIncidentWithExtras() {
long startTime=System.currentTimeMillis();
_log.log(Level.INFO, "StartTime: " + startTime);
ArrayList<RNObject> rn_objects = new ArrayList<RNObject>();
ArrayList<String[]> report_rows = new ArrayList<String[]>();
//Run report and get a list of Threads that need processing
CSVTable jobQueue = this.getReportData(142601, 5, 0);
try {
/*
*
* Prep object requests
*
*/
for (String data : jobQueue.getRows().getRow()) {
/* Split CSV string */
String[] row_data = data.split(",");
//Add to array list so that we can loop it again later
report_rows.add(row_data);
/* Split string to get attachment ids */
String[] attachment_data = row_data[6].split("::");
for(String attachment_id : attachment_data){
/* Add iVu attachment ot Fetch Queue*/
GenericObject go = new GenericObject();
//Set the object type
RNObjectType objType = new RNObjectType();
objType.setNamespace("SendSecure");
objType.setTypeName("iVUAttachments");
go.setObjectType(objType);
ID go_ID = new ID();
go_ID.setId(Integer.valueOf(attachment_id));
go.setID(go_ID);
/* Add to fetch queue */
rn_objects.add(go);
}
/* Add Thread CBO to Fetch Queue */
Integer thread_cbo_id = Integer.valueOf(row_data[7]);
GenericObject go2 = new GenericObject();
//Set the object type
RNObjectType objType2 = new RNObjectType();
objType2.setNamespace("SendSecure");
objType2.setTypeName("SecureReplies");
go2.setObjectType(objType2);
ID go2_ID = new ID();
go2_ID.setId(thread_cbo_id);
go2.setID(go2_ID);
/* Add to fetch queue */
rn_objects.add(go2);
/* Add Incident to Fetch Queue */
ID incidentID = new ID();
incidentID.setId(Integer.valueOf(row_data[0]));
Incident myIncident = new Incident();
myIncident.setID(incidentID);
ThreadList threads_tmpl = new ThreadList();
myIncident.setThreads(threads_tmpl);
FileAttachmentIncidentList fattach_tmpl = new FileAttachmentIncidentList();
myIncident.setFileAttachments(fattach_tmpl);
/* Put our Incident object into a collection */
rn_objects.add(myIncident);
}
/*
* Fetch Everything
*
*/
RNObjectsResult results = _service.get( rn_objects.toArray(new RNObject[0]), this.getGetProcessingOptions(), this.getClientInfoHeader());
_log.log(Level.INFO, results.toString());
/*
*
* Process Threads
*
*/
for (String[] thread_row : report_rows) {
Integer incident_id = Integer.valueOf(thread_row[0]);
Integer thread_cbo_id = Integer.valueOf(thread_row[7]);
List<String> attachment_data = Arrays.asList(thread_row[6].split("::"));
Incident incident_obj = null;
GenericObject thread_cbo_obj = null;
ArrayList<GenericObject> attachment_objs = new ArrayList<GenericObject>();
/* Pull out our objects from the dump of data returned by service.get */
for(RNObject rn_obj : results.getRNObjects()){
/* Find the Incident object */
if(rn_obj.getClass() == Incident.class){
Incident inc_obj = (Incident) rn_obj;
if(inc_obj.getID().getId() == incident_id){
incident_obj = inc_obj;
}
}
/* Find Generic Objects */
if(rn_obj.getClass() == GenericObject.class){
GenericObject gen_obj = (GenericObject) rn_obj;
/* Find the iVUAttachment CBO's */
if("SendSecure".equals(gen_obj.getObjectType().getNamespace())
&& "iVUAttachments".equals(gen_obj.getObjectType().getTypeName())){
String gen_obj_id = String.valueOf(gen_obj.getID().getId());
if(attachment_data.contains(gen_obj_id)){
attachment_objs.add(gen_obj);
}
}
/* Find the Thread CBO */
if("SendSecure".equals(gen_obj.getObjectType().getNamespace())
&& "SecureReplies".equals(gen_obj.getObjectType().getTypeName())
&& gen_obj.getID().getId() == thread_cbo_id){
thread_cbo_obj = gen_obj;
_log.info("Found CBO for Thread CBO with ID of: " + thread_cbo_obj.getID().getId());
}
}
}
//got objects, now process thread
_log.log(Level.INFO, "Found Incident Obj with ID: " + incident_obj.getID().getId());
_log.log(Level.INFO, "Found Attachments with count: " + attachment_objs.size());
/* Iterate through all threads */
if(incident_obj != null){
for(Thread thread_obj : incident_obj.getThreads().getThreadList()){
if(thread_obj.getEntryType().getID().getId() == 2){
_log.log(Level.INFO, "Account Name: " + ((thread_obj.getAccount() != null ) ? thread_obj.getAccount().getName() : "" ) + "\n"
+ "Contact Name: " + ((thread_obj.getContact() != null ) ? thread_obj.getContact().getName() : "") + "\n"
+ "Thread Type: " + ((thread_obj.getEntryType() != null )? thread_obj.getEntryType().getName() : "" ) + "\n"
+ "Created Time: " + thread_obj.getCreatedTime().getTime().toString() + "\n"
+ "Thread: " + thread_obj.getText()
);
}
}
}
/* Handle Attachments */
if(!attachment_objs.isEmpty()){
for(GenericObject attachment_obj : attachment_objs){
//Do something
_log.log(Level.INFO, "Processing Attachment with ID: " + attachment_obj.getID().getId());
}
}
_log.log(Level.INFO, "\n---------------------------\n-------------------------------\n-------------------------\n");
}
} catch (Exception ex) {
_log.log(Level.SEVERE, null, ex);
}
long endTime=System.currentTimeMillis();
long duration = endTime - startTime;
_log.log(Level.INFO, "EndTime: " + endTime);
_log.log(Level.INFO, "Duration: " + Float.valueOf(duration) / 1000 + " seconds");
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
try {
DemoApp demo = new DemoApp(args[0], args[1]);
//demo.queryByRefNo2("120620-000009");
//Report ID, Limit, Start
// demo.getReportData(142473, 10, 0);
// demo.getFileData(6464845, 57848);
demo.getIncidentWithExtras();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment