DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mastering Multi-Cloud and Edge Data Synchronization: A Retail Use Case With KubeMQ’s Java SDK
  • Simplifying Database Operations With HarperDB SDK for Java
  • Microservices With Apache Camel and Quarkus (Part 4)
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)

Trending

  • What Is Plagiarism? How to Avoid It and Cite Sources
  • How AI Agents Are Transforming Enterprise Automation Architecture
  • Accelerating AI Inference With TensorRT
  • Mastering Advanced Aggregations in Spark SQL
  1. DZone
  2. Coding
  3. Java
  4. A Look at the Cognos SDK With Java

A Look at the Cognos SDK With Java

Take a look at some modular code using IBM's Cognos SDK. This setup will help you execute the Cognos report and save the XLS format to your machine.

By 
Arun Pandey user avatar
Arun Pandey
DZone Core CORE ·
Oct. 28, 16 · Code Snippet
Likes (7)
Comment
Save
Tweet
Share
17.7K Views

Join the DZone community and get the full member experience.

Join For Free

A while back, I got the oppurtunity to work with the Cognos SDK and Java. After some exercises, I was able to write some modular code for my project. IBM Cognos SDK has plenty of examples of interacting with the Cognos environment and executing the report, but here, I am providing some better modular code to execute the Cognos report and save the XLS format to your machine.

Let's look at the code snippets of this example:

Cognos POM Dependencies

<dependency>
  <groupId>cognos</groupId>
  <artifactId>cognosClient</artifactId>
  <version>10.0.0</version>
</dependency>
<dependency>
  <groupId>cognos</groupId>
  <artifactId>cognos-axis</artifactId>
  <version>10.0.0</version>
</dependency>
<dependency>
  <groupId>com.ibm.cognos</groupId>
  <artifactId>axisCognosClient</artifactId>
  <version>10.2.1003.17</version>
</dependency>

CognosConnection.properties

cognos.sendpoint=http://localhost:6578/cognos/servlet/dispatch
cognos.namespace=CognosNamespaceServices
cognos.uid=xyz
cognos.pwd=abcd
cognos.report.source.path=/content/folder[@name='Samples']/folder[@name='Models']/package[@name='GO Data']/folder[@name='Report Samples']
cognos.report.source.filename=Sales Report
cognos.report.dest.path=C:\\Arun\\
cognos.report.dest.filename=Sales Report
cognos.report.format=xls

Constant.java

import java.text.SimpleDateFormat;

public interface Constant {

  String STUB_HEADER_NAMESPACE = "http://developer.cognos.com/schemas/bibus/3/";   
  String STUB_HEADER_PARTNAME = "biBusHeader";

  String COGNOS_REPORT_CONFIG_SQL = "SELECT REPORT_SOURCE_PATH, REPORT_SOURCE_FILE_NAME, REPORT_DEST_PATH, " +
    "REPORT_DEST_FILE_NAME, FORMAT, BUSINESS_DATE FROM COGNOS_REPORT_CONFIG WHERE CALENDAR_ID='";

  /** Cognos Properties Constant : read from properties file for development purpose **/
  String COGNOS_CONN_INFO_FILE = "/CognosConnection.properties";
  String PROP_SEND_POINT = "cognos.sendpoint";
  String PROP_NAMESPACE = "cognos.namespace";
  String PROP_UID = "cognos.uid";
  String PROP_PASSWORD = "cognos.pwd";
  String PROP_FORMAT = "cognos.report.format";
  String PROP_COGNOS_REPORT_SOURCE_PATH = "cognos.report.source.path";
  String PROP_COGNOS_REPORT_SOURCE_FILENAME = "cognos.report.source.filename";
  String PROP_COGNOS_REPORT_DEST_PATH = "cognos.report.dest.path";
  String PROP_COGNOS_REPORT_DEST_FILENAME = "cognos.report.dest.filename";
}

CognosPropertyReader.java

import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.log4j.Logger;
import Constant;

public class CognosPropertyReader implements Constant{

  private static Logger LOG = Logger.getLogger(CognosPropertyReader.class);

  private static String sendPoint;
  public static String namespace;
  private static String cognosUser;
  private static String cognosPwd;
  private static String reportFormat;
  private static String reportDestFolder;

  private static String reportSourcePath;
  private static String reportSourceFileName;
  private static String reportDestPath;
  private static String reportDestFileName;
  private static Properties cognosConnProperty = new Properties();

  static{
    try {
      cognosConnProperty.load(CognosPropertyReader.class.getResourceAsStream(COGNOS_CONN_INFO_FILE));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
     * This is simply to keep ready all the required properties for Cognos
     */
  public synchronized static void readProperties() throws SQLException, IOException {           

    sendPoint = cognosConnProperty.getProperty(PROP_SEND_POINT);
    namespace = cognosConnProperty.getProperty(PROP_NAMESPACE);
    cognosUser = cognosConnProperty.getProperty(PROP_UID);
    cognosPwd = cognosConnProperty.getProperty(PROP_PASSWORD);

    reportSourcePath = cognosConnProperty.getProperty(PROP_COGNOS_REPORT_SOURCE_PATH);
    reportSourceFileName = cognosConnProperty.getProperty(PROP_COGNOS_REPORT_SOURCE_FILENAME);
    reportDestPath = cognosConnProperty.getProperty(PROP_COGNOS_REPORT_DEST_PATH);
    reportDestFileName = cognosConnProperty.getProperty(PROP_COGNOS_REPORT_DEST_FILENAME);
    reportFormat = cognosConnProperty.getProperty(PROP_FORMAT);

    setReportDestFolder(reportDestPath);

    reportSourcePath += "/report[@name='" + reportSourceFileName +"']";
    reportDestPath += reportDestFileName;
  }

  public static String getSendPoint() {
    return sendPoint;
  }
  public static String getNamespace() {
    return namespace;
  }
  public static String getCognosUser() {
    return cognosUser;
  }
  public static String getCognosPwd() {
    return cognosPwd;
  }
  public static String getReportFormat() {
    return reportFormat;
  }
  public static String getReportSourcePath() {
    return reportSourcePath;
  }
  public static String getReportDestPath() {
    return reportDestPath;
  }
  public static String getReportDestFolder() {
    return reportDestFolder;
  }
  public static void setReportDestFolder(String reportDestFolder) {
    CognosPropertyReader.reportDestFolder = reportDestFolder;
  }
}

CognosConnector.java

import static Constant.STUB_HEADER_NAMESPACE;
import static Constant.STUB_HEADER_PARTNAME;

import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.sql.SQLException;

import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;

import org.apache.axis.client.Stub;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.log4j.Logger;

import com.cognos.developer.schemas.bibus._3.BiBusHeader;
import com.cognos.developer.schemas.bibus._3.ContentManagerService_PortType;
import com.cognos.developer.schemas.bibus._3.ContentManagerService_ServiceLocator;
import com.cognos.developer.schemas.bibus._3.ReportService_PortType;
import com.cognos.developer.schemas.bibus._3.ReportService_ServiceLocator;
import com.cognos.developer.schemas.bibus._3.SearchPathSingleObject;
import com.cognos.developer.schemas.bibus._3.XmlEncodedXML;
import CognosPropertyReader;

public class CognosConnector {

  private final static Logger LOG = Logger.getLogger(CognosConnector.class);

  private ContentManagerService_PortType cmService = null;
  private ReportService_PortType reportService = null;

  public CognosConnector(){}

  public CognosConnector() throws SQLException, IOException, {

    CognosPropertyReader.readProperties();
    try {
      java.net.URL endPoint = new java.net.URL(CognosPropertyReader.getSendPoint());

      reportService = new ReportService_ServiceLocator().getreportService(endPoint);

      cmService = new ContentManagerService_ServiceLocator().getcontentManagerService(endPoint);           
      LOG.info(quickLogon());
    }
    catch (MalformedURLException e) {
      LOG.error("Malformed URL:\n" + e.getMessage());
    } catch (ServiceException e) {
      LOG.error("ServiceException:\n" + e.getMessage());
    }

  }

  /**
     * This method logs the user to ReportNet
     */
  public String quickLogon() {
    StringBuffer credentialXML = new StringBuffer();

    credentialXML.append("<credential>");
    credentialXML.append("<namespace>").append(CognosPropertyReader.getNamespace()).append("</namespace>");
    credentialXML.append("<username>").append(CognosPropertyReader.getCognosUser()).append("</username>");
    credentialXML.append("<password>").append(CognosPropertyReader.getCognosPwd()).append("</password>");
    credentialXML.append("</credential>");

    String encodedCredentials = credentialXML.toString();

    try {       
      getCmService().logon(new XmlEncodedXML(encodedCredentials), new SearchPathSingleObject[]{});

      SOAPHeaderElement temp = ((Stub)cmService).getResponseHeader(STUB_HEADER_NAMESPACE, STUB_HEADER_PARTNAME);
      BiBusHeader cmBiBusHeader = (BiBusHeader)temp.getValueAsType(new QName(STUB_HEADER_NAMESPACE, STUB_HEADER_PARTNAME));
      ((Stub)cmService).setHeader(STUB_HEADER_NAMESPACE, STUB_HEADER_PARTNAME, cmBiBusHeader);
      return ("Logon successful as " + CognosPropertyReader.getCognosUser());
    } catch (RemoteException re) {
      LOG.error(re.getMessage());
    } catch (Exception e) {
      LOG.error(e.getMessage());
    }
  }

  /**
     * To get the ReportService which would be use to run the report
     */
  public ReportService_PortType getReportService(boolean isNewConversation) {

    BiBusHeader bibus = getHeaderObject(((Stub)reportService).getResponseHeader(STUB_HEADER_NAMESPACE, STUB_HEADER_PARTNAME), isNewConversation);

    if (null == bibus) {
      bibus = getHeaderObject(((Stub)cmService).getResponseHeader(STUB_HEADER_NAMESPACE, STUB_HEADER_PARTNAME), true);
    }
    ((Stub)reportService).clearHeaders();
    ((Stub)reportService).setHeader(STUB_HEADER_NAMESPACE, STUB_HEADER_PARTNAME, bibus); 
    return reportService;
  }

  /**
     * To get the header object
     */
  public static BiBusHeader getHeaderObject(SOAPHeaderElement SourceHeader, boolean isNewConversation) {
    if (null == SourceHeader){
      return null;
    }
    BiBusHeader bibus = null;
    try {
      bibus = (BiBusHeader)SourceHeader.getValueAsType(new QName(STUB_HEADER_NAMESPACE, STUB_HEADER_PARTNAME));

      /** If the header will be used for a new conversation, clear tracking information **/
      if (isNewConversation){
        bibus.setTracking(null);
      }
    } catch (Exception e) {
      LOG.error(e.getMessage());
    }
    return bibus;
  }

  public ContentManagerService_PortType getCmService() {
    return cmService;
  }

  public void setCmService(ContentManagerService_PortType cmService) {
    this.cmService = cmService;
  }
}

ReportExecutor.java

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.cognos.developer.schemas.bibus._3.AsynchDetailReportOutput;
import com.cognos.developer.schemas.bibus._3.AsynchDetailReportStatus;
import com.cognos.developer.schemas.bibus._3.AsynchDetailReportStatusEnum;
import com.cognos.developer.schemas.bibus._3.AsynchOptionBoolean;
import com.cognos.developer.schemas.bibus._3.AsynchOptionEnum;
import com.cognos.developer.schemas.bibus._3.AsynchReply;
import com.cognos.developer.schemas.bibus._3.AsynchReplyStatusEnum;
import com.cognos.developer.schemas.bibus._3.AsynchSecondaryRequest;
import com.cognos.developer.schemas.bibus._3.BaseClass;
import com.cognos.developer.schemas.bibus._3.Option;
import com.cognos.developer.schemas.bibus._3.Output;
import com.cognos.developer.schemas.bibus._3.Page;
import com.cognos.developer.schemas.bibus._3.ParameterValue;
import com.cognos.developer.schemas.bibus._3.ParmValueItem;
import com.cognos.developer.schemas.bibus._3.PropEnum;
import com.cognos.developer.schemas.bibus._3.QueryOptions;
import com.cognos.developer.schemas.bibus._3.RunOptionBoolean;
import com.cognos.developer.schemas.bibus._3.RunOptionEnum;
import com.cognos.developer.schemas.bibus._3.RunOptionStringArray;
import com.cognos.developer.schemas.bibus._3.SearchPathMultipleObject;
import com.cognos.developer.schemas.bibus._3.SearchPathSingleObject;
import com.cognos.developer.schemas.bibus._3.SimpleParmValueItem;
import com.cognos.developer.schemas.bibus._3.Sort;
import CognosConnector;
import CognosPropertyReader;

public class ReportExecutor {

  private static Logger LOG = Logger.getLogger(ReportExecutor.class);

  private static CognosConnector cognosConn;

  public ReportExecutor() throws SQLException, IOException{
    cognosConn = new CognosConnector();
  }

  /**
     * Check for a secondary request.
     */
  public boolean hasSecondaryRequest(AsynchReply response, String secondaryRequest) {
    AsynchSecondaryRequest[] secondaryRequests = response.getSecondaryRequests();

    for (int i = 0; i < secondaryRequests.length; i++) {
      if (secondaryRequests[i].getName().compareTo(secondaryRequest)== 0) {
        return true;
      }
    }
    return false;
  }

  /**
     * The run will return complete even if the report output is not created this method will
     * check for actual output after the run has returned a complete status.
     */
  public boolean outputIsReady(AsynchReply response) {
    for (int i = 0; i < response.getDetails().length; i++) {
      if ((response.getDetails()[i] instanceof AsynchDetailReportStatus)
          && (((AsynchDetailReportStatus)response.getDetails()[i]).getStatus()
              == AsynchDetailReportStatusEnum.responseReady)
          && (hasSecondaryRequest(response, "getOutput"))) {
        return true;
      }
    }
    return false;
  }

  /**
     * To execute the cognos report for XLS format
     */
  public void executeReport(String date) {

    String textOutput = null;
    String format = "spreadsheetML";

    try {
      /** setup the runOptions for execution of report */
      Option[] runOptions = new Option[4];

      RunOptionBoolean saveOutput = new RunOptionBoolean();
      saveOutput.setName(RunOptionEnum.saveOutput);
      saveOutput.setValue(false);
      runOptions[0] = saveOutput;

      /** Specify the output format */
      RunOptionStringArray outputFormat = new RunOptionStringArray();
      outputFormat.setName(RunOptionEnum.outputFormat);
      outputFormat.setValue(new String[]{format});
      runOptions[1] = outputFormat;

      /** Set the report not to prompt as we pass the parameters if any */
      RunOptionBoolean rop = new RunOptionBoolean();
      rop.setName(RunOptionEnum.prompt);
      rop.setValue(false);
      runOptions[2] = rop;

      /** Set the option to always have the primaryRequest in the response */
      AsynchOptionBoolean includePrimaryRequest = new AsynchOptionBoolean();
      includePrimaryRequest.setName(AsynchOptionEnum.alwaysIncludePrimaryRequest);
      includePrimaryRequest.setValue(true);
      runOptions[3] = includePrimaryRequest;

      SearchPathSingleObject spSingle = new SearchPathSingleObject();
      spSingle.set_value(CognosPropertyReader.getReportSourcePath());
      AsynchReply res = cognosConn.getReportService(true).run(spSingle, this.getReportParameters(date), runOptions);

      /** If response is not immediately complete, call wait until complete */
      if (!res.getStatus().equals(AsynchReplyStatusEnum.complete)) {
        while (!res.getStatus().equals(AsynchReplyStatusEnum.complete)) {
          /** before calling wait, double check that it is okay */
          if (hasSecondaryRequest(res, "wait")) {
            res = cognosConn.getReportService(false).wait(res.getPrimaryRequest(), new ParameterValue[] {}, new Option[] {});
          }
        }

        /** After calling wait() it is necessary to check to make sure
                 * the output is ready before retrieving it */
        if (outputIsReady(res)) {
          res = cognosConn.getReportService(false).getOutput(res.getPrimaryRequest(),
                                                             new ParameterValue[] {}, new Option[] {});
        }
      }

      AsynchDetailReportOutput reportOutput = null;

      for (int i = 0; i < res.getDetails().length; i++) {
        if (res.getDetails()[i] instanceof AsynchDetailReportOutput) {
          reportOutput = (AsynchDetailReportOutput)res.getDetails()[i];

          String[] data = reportOutput.getOutputPages();
          textOutput = data[0];
          /** look for output pages of the excel report. */
          BaseClass bcOutput[] = reportOutput.getOutputObjects();
          Output out = null;

          if (null != bcOutput) {   
            for (int k = 0; k < bcOutput.length; k++) {   
              if(bcOutput[k] instanceof Output) {
                LOG.info("Found Page in report... saving locally.");
                out = (Output)bcOutput[k];

                PropEnum []page_props = new PropEnum[]{
                  PropEnum.searchPath, PropEnum.defaultName,
                    PropEnum.data, PropEnum.dataType};
                BaseClass []bcPage = cognosConn.getCmService().query(new SearchPathMultipleObject(out.getSearchPath().getValue() + "/page"),
                                                                     page_props, new Sort[]{}, new QueryOptions() );
                if (null != bcPage) {   
                  for (int j = 0; j < bcPage.length; j++) {   
                    Page g = (Page)bcPage[j];
                    String pageName = g.getDefaultName().getValue();
                    String pageFile = CognosPropertyReader.getReportDestFolder() + "\\" + pageName;
                    /** save html page locally.*/
                    File oFile = new File(pageFile);
                    FileOutputStream fos = new FileOutputStream(oFile);
                    fos.write(g.getData().getValue());
                    fos.flush();
                    fos.close();
                  }
                }
              }
            }
          }

          /** Write the report output to a file */
          File oFile = new File(CognosPropertyReader.getReportDestPath().replaceAll(" ", "-") +".xls");
          FileOutputStream fos = new FileOutputStream(oFile);

          if (null != textOutput) {   
            byte binaryOutput[] = null;
            binaryOutput = com.cognos.org.apache.axis.encoding.Base64.decode(textOutput);
            fos.write(binaryOutput);
          }       
          fos.flush();
          fos.close();
        }
      }
    }
    catch( Exception ex) {
      LOG.error(ex.getMessage());
    }
  }

  /**
     * To get the Report parameter in form of date
     */
  public ParameterValue[] getReportParameters(String monthYear) {

    ParameterValue[] parameters = new ParameterValue[1];

    SimpleParmValueItem item = new SimpleParmValueItem();
    item.setDisplay(monthYear);
    item.setUse(monthYear);
    item.setInclusive(true);
    ParmValueItem[] pvi = new ParmValueItem[1];
    pvi[0] = item;

    parameters[0] = new ParameterValue();
    parameters[0].setName("date");
    parameters[0].setValue(pvi);
    return parameters;
  }
}

CognosReportExecutorClient.java

import java.io.IOException;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import ReportExecutor;

public class CognosReportExecutorClient{

  private final static Logger LOG = Logger.getLogger(CognosReportExecutorClient.class);

  public static void main(String[] args) throws IOException, SQLException {

    if(null == args[0] || args[0].length() < 1){
      System.exit(1);
    }
    String date = args[0]
      new ReportExecutor().executeReport(date); 
  }
}

Update the config info as per your need, and it's all good to go. I hope this will give a better understanding of how to use the Cognos IBM SDK.

Software development kit Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Multi-Cloud and Edge Data Synchronization: A Retail Use Case With KubeMQ’s Java SDK
  • Simplifying Database Operations With HarperDB SDK for Java
  • Microservices With Apache Camel and Quarkus (Part 4)
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!