0% found this document useful (0 votes)
66 views

Automating and Scheduling File Import Activity Using Rest API 29june2020

This document describes automating and scheduling file import activities for Oracle CX Sales using REST APIs. It discusses uploading files to Oracle WebCenter Content Server, submitting import requests, monitoring import status, and scheduling recurring imports. Sample Java code is provided to illustrate the process, including a utility class to interface with WebCenter Content Server and a scheduler to repeatedly run imports on a configured schedule.

Uploaded by

Wael
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Automating and Scheduling File Import Activity Using Rest API 29june2020

This document describes automating and scheduling file import activities for Oracle CX Sales using REST APIs. It discusses uploading files to Oracle WebCenter Content Server, submitting import requests, monitoring import status, and scheduling recurring imports. Sample Java code is provided to illustrate the process, including a utility class to interface with WebCenter Content Server and a scheduler to repeatedly run imports on a configured schedule.

Uploaded by

Wael
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Automating and Scheduling File

Import Activity Using REST API


Oracle CX Sales and B2B Service
Implementation Note | Updated: June 29, 2020
Resource Centers
Oracle CX Sales and B2B Service

Table of Contents
Overview .................................................................................................................................................. 4
File Import Activity REST API ............................................................................................................... 4
Solution Details ........................................................................................................................................ 6
The ImportActivityInvoker Utility .........................................................................................7
References .............................................................................................................................................. 26

2|Page
Resource Centers
Oracle CX Sales and B2B Service

Safe Harbor
The following is intended to outline our general product direction. It is intended for information
purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any
material, code, or functionality, and should not be relied upon in making purchasing decisions. The
development, release, and timing of any features or functionality described for Oracle’s products
remains at the sole discretion of Oracle. The sample code shown in the document is just for reference
to understand the approach.
Content Subject to Change
The information in this document is correct as of the published date. However, Oracle CX Sales and
B2B Service continues to evolve and software updates are applied frequently; therefore this
information is subject to change. Check with your Oracle Representative for updates.
This content is not warranted to be error-free.
About This Document
This document supplements standard product documentation, which you are encouraged to review.
To find documentation and other learning resources, such as guides, whitepapers, and videos, visit the
Help Center for Oracle CX Sales and B2B Service.
Audience
This document is for Oracle CX Sales and B2B Service customers involved in implementation. The tips
and techniques detailed in this document may not be suitable for a non-Cloud deployment of Oracle
CX Sales and B2B Service or other CX Applications.
Prerequisite knowledge/skills
You must have a basic understanding of Java and REST API to use the information in this document.

3|Page
Resource Centers
Oracle CX Sales and B2B Service

Overview
As you transition from Classic Import (FBDI) to the new Import Management framework, Oracle
provides recommendation and best practices to automate and schedule recurring Import Jobs. This
document describes the end-to-end process for automating and scheduling the file import activity
using Rest APIs for Oracle CX Sales and B2B Service. You can improvise the solution as per your
specific requirement.
Note: As of now, users are unable to import recurring import jobs using the Import Management UI
although you can schedule immediate or future import activities. This solution can help you with
automating and scheduling the repeating import job.
Key topics include the following:

• Automating the upload of an import file to Oracle WebCenter Content Server


• Initiating an import job
• Getting the status of a submitted import job
• Scheduling a repeating import job
Important Points of Reference:

• The sample code and steps use Java code and Eclipse IDE.
• The scheduler used to repeatedly schedule the import activity is Quartz Scheduler. Any
external scheduler can be used.
• The sample code uses the automatic mapping approach, so no mapping number is provided in
the request. However, if you want to use preexisting mapping, provide mappingNumber as
input for the 'ImportMapping' attribute in the request.

File Import Activity REST API


The utility described in this document uses a standard Oracle CX Sales file import REST API. The URL
for the REST API is as follows:
https://<POD_NAME>/crmRestApi/resources/latest/importActivities
The import activity automation process using REST API includes the following steps:
1. Uploading the Input File to Oracle WebCenter Content Server and Getting the ContentID of the
File.
The file import REST API requires to pass the Oracle WebCenter Content Server ContentID of the
input file in the request payload. Hence, you must upload the file on Oracle WebCenter Content
Server and get the Oracle WebCenter Content Server ContentID for the input file to be used in
the request body.
2. Submit the Import Request.
The details for submitting the import Request are as follows:
Content-Type: application/vnd.oracle.adf.resourceitem+json or application/json
Method: POST

4|Page
Resource Centers
Oracle CX Sales and B2B Service

Request Body (used in the sample code):


{
"Name": "File Import through REST API",
"Activate": "YES",
"ObjectCode": "Account"
"DataFiles" : [ {
"InputFileContentId": "UCMFA00007278"
}
]
}

In the request body, the object for which import is to be done is passed in the ObjectCode
attribute and the import file is passed in the datafiles’ InputFileContentId attribute. All available
objects to Import/Export can be retrieved using:
https://<PODNAME>/crmRestApi/resources/latest/importExportObjectMetadata
3. Monitor the Status of the Import Activity.
The POST request submitted above returns a response that includes the ImportActivityId and
other attributes like URL to track the status of the import activity
Submit a Get request passing the URL retrieved to monitor the status of import activity.
https://<POD_NAME>/crmRestApi/resources/latest/importActivities/<IMPORT_ACTIVITY_ID>/
child/DataFiles/<CONTENT_ID_IMPORT_FILE>
4. Verify the Success (SuccessReportContentId), Error (ErrorReportContentId), or Exception
(ExceptionReportContentId) Records from Corresponding contentIds.
• If the import activity is successfully completed, the status returned is COMPLETE and no log
or report is generated.
• If the import activity is unsuccessful, the status returned is COMPLETE_WITH_ERRORS, and
the ErrorReportContentId attribute shows the Oracle WebCenter Content Server’s ContentId
of the error report file.
Keep polling for the status, until one of the above is received in the response.
5. Download Files from Oracle WebCenter Content Server using ContentIDs Received in step 4.
6. Schedule the solution
The entire automation process described in the above steps can be scheduled using an external
scheduler so that the solution can run repeatedly. The scheduler used in this procedure is Quartz
Scheduler, which is an open source scheduler that can be integrated with any Java application.

5|Page
Resource Centers
Oracle CX Sales and B2B Service

Solution Details
The sample java utility illustrates how to automate the process of initiating a file import activity and
scheduling it repeatedly. Read through the steps listed in this section to understand the automated
approach.
The values for parameters, such as username and password, that are used in the code are being picked
up from the properties file (Config.properties).
Config.properties

[email protected]
password=***********
UCMServer=https://<POD_NAME>/cs/idcplg
pathtoDownloadFiles=C:/Users/abc/Documents/Downloads/FILES/
pathtoImportFile=C:/Users/abc/Documents/Downloads/Account_Oct17-2.csv
importActivitySubmissionURL=https://<POD_NAME>/crmRestApi/resources/latest/importA
ctivities
activateImportNow=YES
importActivityName=Rest API Import through Java
repeatCount=3
repeatInterval=10

To connect to the Oracle WebCenter Content Server through java client code, Oracle provides a
utility that is used to upload and download the files from Oracle WebCenter Content Server. To use
this utility, include the oracle.ucm.fa_client_11.1.1.jar jar in the class path. It contains the Java API for
connecting to Oracle WebCenter Content Server.
A Singleton class with the name PropertyLoader.java has been created that keeps the path to Config
file and loads the file.
PropertyLoader.java

public class PropertyLoader {

private final static String PATH_TO_CONFIG_FILE = "Config.properties";

private static PropertyLoader PROPERTY_LOADER_SINGLE_INSTANCE = null;


private Properties properties = new Properties();
final static Logger logger = Logger.getLogger(PropertyLoader.class);

private PropertyLoader() {

InputStream filetoReadProperties;
try {
filetoReadProperties = new FileInputStream(new
File(PATH_TO_CONFIG_FILE));
properties.load(filetoReadProperties);
} catch (FileNotFoundException exception) {
6|Page
Resource Centers
Oracle CX Sales and B2B Service

logger.debug("FileNotFoundException"+exception);
}
catch (IOException exception) {
// TODO Auto-generated catch block
logger.debug("IOException"+exception);
}

}
public static PropertyLoader getInstance() throws IOException {

if ( PROPERTY_LOADER_SINGLE_INSTANCE == null) {
PROPERTY_LOADER_SINGLE_INSTANCE = new PropertyLoader();
}

return PROPERTY_LOADER_SINGLE_INSTANCE;
}

public Map<String, String> getPropertyMap(){


Map<String, String> propertyMap = new HashMap<String, String>();
for (String propertyKey : properties.stringPropertyNames()) {
propertyMap.put(propertyKey, properties.getProperty(propertyKey));
}
return propertyMap;
}

public String getPropertyValue(String propertyKey) {


if (propertyKey != null && !propertyKey.isEmpty()) {
return properties.getProperty(propertyKey);
}
return null;
}
}

The ImportActivityInvoker Utility


The ImportActivityInvoker.java class initiates the import process by sending a POST request to the
file import REST API. However, to create the request body, it needs to have Oracle WebCenter
Content Server contentID of the input file. For that it calls the getUCMContentIDOfImportFile()
method from another class UCMAdapter.java.
Let us look at the class UCMAdapter.java that will upload the import file to Oracle WebCenter
Content Server and return the contentID of the uploaded file back to ImportActivityInvoker.java.

UCMAdapter.java
public class UCMAdapter {

final static Logger logger = Logger.getLogger(UCMAdapter.class);

7|Page
Resource Centers
Oracle CX Sales and B2B Service

private static PropertyLoader propertyFileDetails = null;

public UCMAdapter() {
try {
//PropertyConfigurator.configure(LOG4J_CONFIGURATION_PATH);
propertyFileDetails = PropertyLoader.getInstance();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public String uploadFiletoUCMandgetContentID() {

ServiceResponse myServiceResponse = uploadImportFiletoUCM();


String contentID = getContentIdfromUCMResponse(myServiceResponse);
return contentID;
}

private String getContentIdfromUCMResponse(ServiceResponse


myServiceResponse) {

String contentID = new String();

try {

DataBinder myResponseDataBinder;
myResponseDataBinder = myServiceResponse.getResponseAsBinder();
contentID = myResponseDataBinder.getLocal("dDocName");
return contentID;
}

catch (IdcClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return contentID;

private ServiceResponse uploadImportFiletoUCM() {

IdcClient client = createClienttoConnecttoUCM();


IdcContext userContext = getIdcContext();
ServiceResponse myServiceResponse =
sendRequesttoUCM(client,userContext);
return myServiceResponse;
}

8|Page
Resource Centers
Oracle CX Sales and B2B Service

private ServiceResponse sendRequesttoUCM(IdcClient client, IdcContext


userContext) {
String fileName =
propertyFileDetails.getPropertyValue("pathtoImportFile");
InputStream fileStream = null;

try {
fileStream = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

long fileLength = new File(fileName).length();


DataBinder myRequestDataBinder = client.createBinder();

myRequestDataBinder.putLocal("IdcService", "CHECKIN_UNIVERSAL");
myRequestDataBinder.putLocal("dDocType", "Application");
myRequestDataBinder.putLocal("dDocTitle", "WSFILeUploadTest");
myRequestDataBinder.putLocal("dDocAuthor",
propertyFileDetails.getPropertyValue("userName"));
myRequestDataBinder.putLocal("dSecurityGroup", "Public");
myRequestDataBinder.putLocal("dDocAccount", "");
myRequestDataBinder.addFile("primaryFile", new TransferFile(fileStream,
"AccountCharu.csv", fileLength, "text/html"));
ServiceResponse myServiceResponse = null;
try {
myServiceResponse = client.sendRequest(userContext,
myRequestDataBinder);
} catch (IdcClientException e) {
logger.debug("IDC Client Exception occurred. Unable to upload file.
Message: " + e.getMessage() + ", Stack trace: ");

e.printStackTrace();

}
return myServiceResponse;

private IdcContext getIdcContext() {


IdcContext userContext = new
IdcContext(propertyFileDetails.getPropertyValue("userName"),
propertyFileDetails.getPropertyValue("password"));
return userContext;
}

private IdcClient createClienttoConnecttoUCM() {

IdcClientManager manager = new IdcClientManager();


IdcClient client = null;
try {

9|Page
Resource Centers
Oracle CX Sales and B2B Service

client =
manager.createClient(propertyFileDetails.getPropertyValue("UCMServer"));
} catch (IdcClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return client;
}

public Document search(String contentID) {


ServiceResponse serviceResponse = null;
Document doc = new Document();
try {

StringBuilder query = new StringBuilder();

if (contentID != null) {
query.append("dDocName <matches> `");
query.append(contentID);
query.append("`");

System.out.println("Search Query: " + query.toString());

IdcClient client = createClienttoConnecttoUCM();


IdcContext userContext = getIdcContext();

DataBinder dataBinderReq = client.createBinder();

//Perform the search using IDC Service GET_SEARCH_RESULTS


dataBinderReq.putLocal("IdcService", "GET_SEARCH_RESULTS");
dataBinderReq.putLocal("QueryText", query.toString());

serviceResponse = client.sendRequest(userContext,
dataBinderReq);
System.out.println(serviceResponse);
DataBinder dataBinderRes =
serviceResponse.getResponseAsBinder();
DataResultSet resultSet =
dataBinderRes.getResultSet("SearchResults");
System.out.println(resultSet);

for (DataObject dataObject : resultSet.getRows()) {

doc.setDocumentId(dataObject.get("dID"));
doc.setOriginalFileName(dataObject.get("dOriginalName"));

10 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

System.out.println("filename"+dataObject.get("dOriginalName"));
System.out.println("filename"+dataObject.get("dDocTitle"));

} catch(Exception ex) {
System.out.println("Error Search: " + ex.getMessage());
} finally {
if (serviceResponse != null) {
serviceResponse.close();
}
}
return doc;
}

public InputStream download(Document document) {


ServiceResponse severiceResponse = null;

try {

IdcClient client = createClienttoConnecttoUCM();


IdcContext userContext = getIdcContext();
DataBinder dataBinderReq = client.createBinder();
dataBinderReq.putLocal("IdcService", "GET_FILE");
dataBinderReq.putLocal("dID", document.getDocumentId());

severiceResponse = client.sendRequest(userContext, dataBinderReq);


InputStream is = severiceResponse.getResponseStream();
File f=new
File(propertyFileDetails.getPropertyValue("pathtoDownloadFiles")+document.getOrigi
nalFileName());

OutputStream out=new FileOutputStream(f);


byte buf[]=new byte[1024];
int len;
while((len=is.read(buf))>0)
out.write(buf,0,len);
out.close();

System.out.println("\n File correctly created.");


is.close();

} catch(Exception ex) {

System.out.println("Error GetFile(): " + ex.getMessage());


}
return null;
}

11 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

There is one more file - Document.java - that is called by UCMAdapter.java. This class maps the
response and request properties to and from Oracle WebCenter Content Server to corresponding java
objects.

Document.java
public class Document implements Comparable<Document>{
private String contentId;
private String documentId;
private String owner;
private String title;
private String doctype;
private String securitygroup;
private Date releaseDate;
private String OriginalFileName;

public String getOriginalFileName() {


return OriginalFileName;
}

public void setOriginalFileName(String originalFileName) {


OriginalFileName = originalFileName;
}

public void setContentId(String contentId) {


this.contentId = contentId;
}

public String getContentId() {


return contentId;
}

public void setDocumentId(String documentId) {


this.documentId = documentId;
}

public String getDocumentId() {


return documentId;
}

public void setOwner(String owner) {


this.owner = owner;
}

public String getOwner() {


return owner;
}

public void setDocType(String doctype) {


this.doctype = doctype;
}
12 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

public String getDocType() {


return doctype;
}

public void setSecurityGroup(String securitygroup) {


this.securitygroup = securitygroup;
}

public String getSecurityGroup() {


return securitygroup;
}

public void setTitle(String title) {


this.title = title;
}

public String getTitle() {


return title;
}

public void setReleaseDate(Date date) {


this.releaseDate = date;
}

public Date getReleaseDate() {


return releaseDate;
}

@Override
public int compareTo(Document o) {
return ( o.releaseDate.before(releaseDate) ? -1 : 1);

Please note that JSON request and response objects from Oracle WebCenter Content Server are
mapped to java classes in the code. For that Jackson dependencies are included. To initiate the Post
and Get requests to the REST API through java, jersey libraries have been used. The following
screenshot shows maven dependencies added in the project.

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.29.1</version>

13 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
<version>2.29.1</version>
<type>pom</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>2.29.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19.4</version>
</dependency>
<dependency>

14 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

<groupId>org.glassfish.jersey.bundles.repackaged</groupId>
<artifactId>jersey-guava</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.26</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles.repackaged</groupId>
<artifactId>jersey-guava</artifactId>
<version>2.25.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<!-- Quartz API -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>

Once the contentID is received from the previous step, the following operations are invoked in the
given order.

a. Submit the File Import Activity Request:


• The request parameters for this service will be given and POST request is submitted.
• The request parameters will have values for attributes Name, Activate, ObjectCode and
DataFiles (explained in the important points section),
• This will return the response body that contains the URL to be used to track the status of
import activity.
b. Get the status of Import activity:
• The response received in above step is parsed to get the URL that will be used to track the
status of the import activity.

15 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

• Submit the Get request with URL received in the response body to monitor the status of the
import activity.
c. Download the success or error logs based on the status received:
• If the import activity was successfully completed, it will return the Oracle WebCenter
Content Server ContentId of the success report file that was generated.
• If the import activity was unsuccessful , it will return the Oracle WebCenter Content Server
ContentId of the error report file
Keep polling to check the status, until one of the above is received in the response. Download the
status log files from Oracle WebCenter Content Server using ContentIds received in step above. Use
the same Utility provided by Oracle (oracle.ucm.fa_client_11.1.1.jar) to download the status log files
that was to be used to upload the input file to Oracle WebCenter Content Server.
All the steps above are automated using ImportActivityInvoker.java.

ImportActivityInvoker.java

public class ImportActivityInvoker {

private static Client client;


private static HttpAuthenticationFeature feature;
final static Logger logger = Logger.getLogger(ImportActivity.class);
private static PropertyLoader propertyFileDetails = null;

static{

try {

propertyFileDetails = PropertyLoader.getInstance();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {


try {
submitImportJob();
} catch (InterruptedException e) {

e.printStackTrace();
}
}

//Submit the import job by calling the REST API


public static void submitImportJob() throws InterruptedException{

String contentID = getUCMContentIDOfImportFile();

16 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

Response response = sendPostRequestandGetResponse(contentID);


String statusURL = getURLtoMonitorStatus(response);
monitorStatusandDownloadFile(statusURL);

//Uploading the import input file to Oracle WebCenter Content Server and getting
the Oracle WebCenter Content Server contentID for the file. This method calls the
method of UCMAdapter.java class described in the above pages

private static String getUCMContentIDOfImportFile() {


UCMAdapter ucm = new UCMAdapter();
String contentID = ucm.uploadFiletoUCMandgetContentID();
return contentID;

//Send the POST request to submit the import activity


private static Response sendPostRequestandGetResponse(String contentID) {
createAuthenticationFeatures();
createclientforRestRequest();

//Configure REST API URL to submit the import job


WebTarget webTarget =
client.target(propertyFileDetails.getPropertyValue("importActivitySubmissionURL"))
;
ObjectMapper mapper = configureMapperforJSONJavaConversion();
String objecttoImport = "Account";
ImportRequest importRequest =
configureImportParametersforRequest(contentID,objecttoImport);
String requestBody =createRequestBody(importRequest,mapper);
Response response = sendRequest(webTarget,requestBody);
return response;

//Configure user credentials to post the request for submitting import job
private static void createAuthenticationFeatures() {
feature = HttpAuthenticationFeature.basicBuilder()
.nonPreemptive()
.credentials(propertyFileDetails.getPropertyValue("userName"),
propertyFileDetails.getPropertyValue("password"))
.build();

private static void createclientforRestRequest() {

ClientConfig clientConfig = new ClientConfig();


clientConfig.register(feature) ;

client = ClientBuilder.newClient(clientConfig);

17 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

//The Jackson ObjectMapper can parse JSON from a string, stream or file, and
create a Java object or object graph representing the parsed JSON. Parsing JSON
into Java objects is also referred to as to deserialize Java objects from JSON.

private static ObjectMapper configureMapperforJSONJavaConversion() {


ObjectMapper mapper = new
ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.PASCAL_CASE_TO_CAM
EL_CASE);
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.setSerializationInclusion(Include.NON_EMPTY);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}

//Configure import parameters that are to be passed as part the request body. The
parameters are configured using java Objects. This will be mapped to JSON response
using JackSon mapper
private static ImportRequest configureImportParametersforRequest(String
ContentID,String objecttoImport) {
//ImportRequest.java is the JAVA class that maps to the JSON Request body
ImportRequest importRequest = new ImportRequest();
importRequest.setActivate(propertyFileDetails.getPropertyValue("activateImportN
ow"));
importRequest.setName(propertyFileDetails.getPropertyValue("importActivityName"
)+System.currentTimeMillis());
importRequest.setObjectCode(objecttoImport);
//DataFile.java is the class that maps to the nested JSON object DataFile in the
requestbody
DataFile dataFile = new DataFile();
dataFile.setInputFileContentId(ContentID);
ArrayList<DataFile> datafiles = new ArrayList<>();
datafiles.add(dataFile);

importRequest.setDataFiles(datafiles);

return importRequest;

//Convert the ImportRequest JAVA object to JSON object using JackSon mapper
private static String createRequestBody(ImportRequest importRequest,ObjectMapper
mapper) {
String requestBody = null;

try {
requestBody = mapper.writeValueAsString(importRequest);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return requestBody;

18 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

//Submit the POST request configured above


private static Response sendRequest(WebTarget webTarget, String requestBody) {
Invocation.Builder invocationBuilder = webTarget.request();
Response response = invocationBuilder.post(Entity.entity(requestBody,
MediaType.APPLICATION_JSON_TYPE));
return response;
}

//Once the response is received after submitting the import activity, the response
is parsed to get the URL that can be used to monitor status

private static String getURLtoMonitorStatus(Response response) {

String URLtomonitorStatus = parseResponse( response);


return URLtomonitorStatus;

//The response received is first mapped to Java object (ImportActivity.java) and


status URL is returned
private static String parseResponse(Response response) {
logger.debug("Response Status"+response.getStatus());
String output = response.readEntity(String.class);

logger.debug("Server response .... \n");


logger.debug(output);
String URLtoMonitorStatus = null;
try {
ObjectMapper mapper = configureMapperforJSONJavaConversion();
ImportActivity importActivityObject = mapper.readValue(output,
ImportActivity.class);
ArrayList<Link> links = importActivityObject.getLinks();
Link link = links.get(0);
logger.debug(link.getHref());

ArrayList<DataFile> dataFiles = importActivityObject.getDataFiles();


DataFile datFile = dataFiles.get(0);
System.out.println(datFile.getDescription());

ArrayList<Link> datFileLinks = datFile.getLinks();


for(Link datFilelink : datFileLinks) {
if (datFilelink.getRel().equals("self")){

URLtoMonitorStatus = datFilelink.getHref();
logger.debug("URL to monitor status of import
activity"+datFilelink.getHref());
}
}

19 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return URLtoMonitorStatus;
}

//Status Of import activity is monitored every 2 minutes till


SuccessReportContentId or ErrorReportContentId is received in the response

private static void monitorStatusandDownloadFile(String StatusURL) {


boolean flag = true;
while(flag){

logger.debug("Waiting for import job to be completed... and so suspending


the job for 2 min.");

try {
Thread.sleep(60 * 1000 * 2);
} catch (InterruptedException e1) {

e1.printStackTrace();
}

//Invoke web service to get the status


WebTarget webTarget = client.target(StatusURL);
Builder invocationBuilder = webTarget.request();
Response response = invocationBuilder.get();
String output = response.readEntity(String.class);

try {
ObjectMapper mapper = configureMapperforJSONJavaConversion();
DataFile status = mapper.readValue(output, DataFile.class);

if(status.getStatus().equals("COMPLETE_WITH_ERRORS")){
logger.debug("Import activity failed with error");
UCMAdapter ucm = new UCMAdapter();
Document document
=ucm.search(status.getErrorReportContentId());
ucm.download(document);
flag = false;
}
else
if(status.getStatus().equals("COMPLETE")){
logger.info("Import activity Succeeded");
flag = false;
}

} catch (IOException e) {

e.printStackTrace();
}

20 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

}
}
}

The other files used in the code are the ones that map JSON request and response objects back and
forth to java objects.

ImportActivity.java

public class ImportActivity {

@JsonDeserialize
private long ImportActivityId;

@JsonDeserialize
private ArrayList <DataFile> dataFiles = new ArrayList <DataFile>();

@JsonDeserialize
@JsonProperty("links")
private ArrayList <Link> links = new ArrayList<Link>() ;

public ArrayList<Link> getLinks() {


return links;
}
public void setLinks(ArrayList<Link> links) {
this.links = links;
}
public long getImportActivityId() {
return ImportActivityId;
}
public void setImportActivityId(long importActivityId) {
ImportActivityId = importActivityId;
}
public ArrayList<DataFile> getDataFiles() {
return dataFiles;
}
public void setDataFiles(ArrayList<DataFile> dataFiles) {
this.dataFiles = dataFiles;
}
}

DataFile.java

21 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

public class DataFile {

@JsonDeserialize
private String InputFileContentId;

@JsonDeserialize
@JsonProperty("links")
private ArrayList <Link> links = new ArrayList<Link>() ;

@JsonDeserialize
@JsonProperty("SuccessReportContentId")
private String SuccessReportContentId;

@JsonDeserialize
@JsonProperty("ErrorReportContentId")
private String ErrorReportContentId;

public String getSuccessReportContentId() {


return SuccessReportContentId;
}

public void setSuccessReportContentId(String successReportContentId) {


SuccessReportContentId = successReportContentId;
}

public String getErrorReportContentId() {


return ErrorReportContentId;
}

public void setErrorReportContentId(String errorReportContentId) {


ErrorReportContentId = errorReportContentId;
}

public String getDescription() {


return Description;
}

public void setDescription(String description) {


Description = description;
}

@JsonDeserialize
private String Description;

public String getInputFileContentId() {


return InputFileContentId;
}

public void setInputFileContentId(String inputFileContentId) {


InputFileContentId = inputFileContentId;
}

22 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

@JsonProperty
public ArrayList<Link> getLinks() {
return links;
}

public void setLinks(ArrayList<Link> links) {


this.links = links;
}

Link.java

@JsonNaming(PropertyNamingStrategy.LowerCaseStrategy.class)
public class Link {

@JsonDeserialize
private String rel;
@JsonDeserialize
private String href;
@JsonDeserialize
private String name;
@JsonDeserialize
private String kind;

private Properties properties;


public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public String getRel() {
return rel;
}
public void setRel(String rel) {
this.rel = rel;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKind() {
return kind;
23 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

}
public void setKind(String kind) {
this.kind = kind;
}

ImportRequest.java
public class ImportRequest {

private String Name;

private ArrayList<DataFile> DataFiles;

private String ObjectCode;

private String Activate;

@JsonProperty
public ArrayList<DataFile> getDataFiles() {
return DataFiles;
}
public void setDataFiles(ArrayList<DataFile> dataFiles) {
DataFiles = dataFiles;
}

@JsonProperty
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}

@JsonProperty
public String getObjectCode() {
return ObjectCode;
}
public void setObjectCode(String objectCode) {
ObjectCode = objectCode;
}

@JsonProperty
public String getActivate() {
return Activate;
}
public void setActivate(String activate) {
Activate = activate;
}

24 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

The solution above can be made to run repeatedly by scheduling it with any external scheduler. The
scheduler used here is Quartz Scheduler. To be able to use Quartz Scheduler in the code, these
operations have to be performed:

• Add quartz libraries/dependencies in the code.


• Create a class that includes the Quartz job to submit file import activity. The class
ImportActivityJob.java does the same.

ImportActivityJob.java
public class ImportActivityJob implements Job {

@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
try {
ImportActivityInvoker.submitImportJob();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

• Define the trigger to configure when and how frequently to execute the job. The code
here schedules the automation of import activity with an interval of 10 minutes, repeating
the process thrice.

ImportActivityScheduler.java
public class ImportActivityScheduler {

private JobDetail job;


private SimpleTrigger trigger;

private static PropertyLoader propertyFileDetails = null;

static{

try {
//PropertyConfigurator.configure(LOG4J_CONFIGURATION_PATH);
propertyFileDetails = PropertyLoader.getInstance();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

25 | P a g e
Resource Centers
Oracle CX Sales and B2B Service

public static void main(String[] args) {


ImportActivityScheduler scheduleImportActivity = new
ImportActivityScheduler();
scheduleImportActivity.createJob();
scheduleImportActivity.configureScheduler();
scheduleImportActivity.initiateJob();
}

private void initiateJob() {


Scheduler scheduler;
try {
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException e) {

e.printStackTrace();
}

private void configureScheduler() {


trigger = TriggerBuilder.newTrigger().withIdentity("Import Activity
Trigger").startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()

.withIntervalInMinutes(Integer.parseInt(propertyFileDetails.getPropertyValue("r
epeatInterval")))

.withRepeatCount(Integer.parseInt(propertyFileDetails.getPropertyValue("repeatC
ount"))))
.build();
}

private void createJob() {


job = JobBuilder.newJob(ImportActivityJob.class).withIdentity("Import
activity Job").build();
}
}

References
• REST API for Oracle CX Sales and B2B Service guide
• Import Data Using REST APIs topic
• A version of jar (oracle.ucm.fa_client_11.1.1.jar:) is available in the knowledge article: Oracle
WebCenter Content (WCC) Document Transfer Utility Readme (Doc ID 1624063.1)
• Understanding Import and Export management for CX Sales and B2B Service guide
• Import Data Using REST APIs guide
• Understanding Import and Export Management guide

26 | P a g e

You might also like