壹佰网|ERP100 - 企业信息化知识门户

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 503|回复: 0

使用cognos sdk 创建并导入部署且设定参数的解决方法

[复制链接]
发表于 2012/3/11 14:07:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。如果您注册时有任何问题请联系客服QQ: 83569622  。

您需要 登录 才可以下载或查看,没有帐号?注册

x
cognos导入的时候我想设置如下内容:
1、可以设定导入方案的定义位置
2、可以设定导入目标的位置和名称
3、可以自动执行导入
咨询IBM的内部人员告知sdk不可以做到,我周末琢磨了两天,终于找到了解决方法,代码没有进行重构。
-----------------------------------------------------------------------------------------------------------------------
package com.cognos.deployment;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.Calendar;
import java.util.Vector;
import javax.xml.rpc.ServiceException;
import org.apache.axis.AxisFault;
import org.apache.axis.client.Stub;
import com.cognos.developer.schemas.bibus._3.AddOptions;
import com.cognos.developer.schemas.bibus._3.AsynchDetailEventID;
import com.cognos.developer.schemas.bibus._3.AsynchReply;
import com.cognos.developer.schemas.bibus._3.AsynchReplyStatusEnum;
import com.cognos.developer.schemas.bibus._3.AuditLevelEnum;
import com.cognos.developer.schemas.bibus._3.BaseClass;
import com.cognos.developer.schemas.bibus._3.BaseClassArrayProp;
import com.cognos.developer.schemas.bibus._3.BiBusHeader;
import com.cognos.developer.schemas.bibus._3.ClassEnum;
import com.cognos.developer.schemas.bibus._3.ContentManagerService_Port;
import com.cognos.developer.schemas.bibus._3.ContentManagerService_ServiceLocator;
import com.cognos.developer.schemas.bibus._3.DeploymentDetail;
import com.cognos.developer.schemas.bibus._3.DeploymentImportRule;
import com.cognos.developer.schemas.bibus._3.DeploymentOption;
import com.cognos.developer.schemas.bibus._3.DeploymentOptionArrayProp;
import com.cognos.developer.schemas.bibus._3.DeploymentOptionAuditLevel;
import com.cognos.developer.schemas.bibus._3.DeploymentOptionBoolean;
import com.cognos.developer.schemas.bibus._3.DeploymentOptionEnum;
import com.cognos.developer.schemas.bibus._3.DeploymentOptionImportRuleArray;
import com.cognos.developer.schemas.bibus._3.DeploymentOptionPackageInfo;
import com.cognos.developer.schemas.bibus._3.DeploymentOptionString;
import com.cognos.developer.schemas.bibus._3.ImportDeployment;
import com.cognos.developer.schemas.bibus._3.MonitorService_Port;
import com.cognos.developer.schemas.bibus._3.MonitorService_ServiceLocator;
import com.cognos.developer.schemas.bibus._3.MultilingualToken;
import com.cognos.developer.schemas.bibus._3.Option;
import com.cognos.developer.schemas.bibus._3.OptionArrayProp;
import com.cognos.developer.schemas.bibus._3.PackageDeploymentInfo;
import com.cognos.developer.schemas.bibus._3.ParameterValue;
import com.cognos.developer.schemas.bibus._3.PropEnum;
import com.cognos.developer.schemas.bibus._3.QueryOptions;
import com.cognos.developer.schemas.bibus._3.SearchPathMultipleObject;
import com.cognos.developer.schemas.bibus._3.SearchPathSingleObject;
import com.cognos.developer.schemas.bibus._3.Sort;
import com.cognos.developer.schemas.bibus._3.TokenProp;
import com.cognos.developer.schemas.bibus._3.UpdateActionEnum;
import com.cognos.developer.schemas.bibus._3.UpdateOptions;
import com.cognos.developer.schemas.bibus._3.XmlEncodedXML;
public class ExportAndRunDeployment {
private ContentManagerService_Port cmService = null;
private MonitorService_Port monitorService = null;
private DeploymentOptionArrayProp doap = new DeploymentOptionArrayProp();
public static String logFile = "Import.csv";
private String arguments[] = { "-a", "-i", "-d", "-s", "-u", "-p", "-c", "-g" };
private Vector packages = new Vector();

// This method gets and sets all deploymentOptions from the archive without
// a password
// In this script the deployment options are not changed.
public DeploymentOption[] deploymentOptions(String p_archive) {
  try {
   Option dOptions[] = new Option[] {};
   dOptions = cmService.getDeploymentOptions(p_archive, dOptions);
   DeploymentOption[] opt = new DeploymentOption[dOptions.length + 1];
   DeploymentOptionAuditLevel recordingLevel = new DeploymentOptionAuditLevel();
   recordingLevel.setName(DeploymentOptionEnum.fromString("recordingLevel"));
   recordingLevel.setValue(AuditLevelEnum.full);
//   {
//    DeploymentImportRule pacInfo[] = new DeploymentImportRule[1];
//    pacInfo[0] = new DeploymentImportRule();
////    pacInfo[0].setName(mt);  //package
//    //导入到的路径(就是你配置的导入到的位置)
//    pacInfo[0].setParent(new SearchPathSingleObject("/content/folder[@name='dummy']"));
//   }
   opt[0] = recordingLevel;
   
   System.arraycopy(dOptions, 0, opt, 1, dOptions.length);
   //设置所有者(相当于权限)
   opt = takeOwnership(opt);
   if (packages != null && packages.size() > 0) {
    for (int i = 1; i < opt.length; i++)
     if (opt.getName().getValue()
       .compareToIgnoreCase(DeploymentOptionEnum.fromString("package").getValue()) == 0) {
      int j = packages.size();
      //对于每一个单独的package
      if (packages != null && j > 0) {
       PackageDeploymentInfo pDeplInfo[] = new PackageDeploymentInfo[j];
       DeploymentOptionPackageInfo pack = new DeploymentOptionPackageInfo();
       for (int k = 0; k < j; k++) {
        MultilingualToken mt[] = new MultilingualToken[1];
        mt[0] = new MultilingualToken();
        mt[0].setLocale("en");
        mt[0].setValue(packages.get(k).toString());//这里是导入后的名字叫什么
        
        pDeplInfo[k] = new PackageDeploymentInfo();
        pDeplInfo[k].setSourceName(mt);
        pDeplInfo[k].setTargetName(mt);
        pDeplInfo[k].setEnabled(true); // ? Should it be set to true ?
       }
       // will not change the target name. Keep by default
       pack.setName(DeploymentOptionEnum.fromString("package"));
       pack.setValue(pDeplInfo);
       opt = pack;
      }
     }
   }
   return opt;
  } catch (RemoteException e) {
   e.printStackTrace();
   return null;
  }
}
public DeploymentOption[] takeOwnership(DeploymentOption[] opt) {
  for (int i = 0; i < opt.length; i++)
   if (opt.getName() == DeploymentOptionEnum.fromString("takeOwnership")) {
    // Change the ownership to the user performing the import.
    // Otherwise
    // there will be errors
    ((DeploymentOptionBoolean) opt).setValue(true);
   }
  return opt;
}
// This method selects and inserts an archive in CM from all available .zip
// files
// in <crn>\deployment if using default configuration
public String insertNewImport(String importName, String password, String importDeploymentName) {
  try {
   SearchPathMultipleObject spMulti = new SearchPathMultipleObject();
   spMulti.setValue("/adminFolder/adminFolder[@name='buru']");
   PropEnum props[] = new PropEnum[] { PropEnum.searchPath, PropEnum.policies };
   BaseClass importDeplFolder[] = cmService.query(spMulti, props, new Sort[] {}, new QueryOptions());
   ImportDeployment newImport = new ImportDeployment();
   TokenProp tp = new TokenProp();
   tp.setValue(importDeploymentName.length() > 0 ? importDeploymentName : importName);
   newImport.setDefaultName(tp);
   BaseClassArrayProp parent = new BaseClassArrayProp();
   parent.setValue(importDeplFolder);
   newImport.setParent(parent);
//   if (password != null && password.length() >= 1)
//    doap.setValue(deploymentOptions(importName, password));
//   else
    doap.setValue(deploymentOptions(importName));
   newImport.setDeploymentOptions(doap);
   String importPath = "/adminFolder/adminFolder[@name='buru']";
   AddOptions ao = new AddOptions();
   ao.setUpdateAction(UpdateActionEnum.replace); // replace if already exists
   SearchPathSingleObject spSingle = new SearchPathSingleObject(importPath);
   BaseClass archive[] = cmService.add(spSingle, new BaseClass[] { newImport }, ao);
   if (archive == null || archive.length <= 0)
    System.out.println("No Import was added to the Content Store.");
   return archive[0].getSearchPath().getValue();
  } catch (Exception ex) {
   printErrorMessage(ex);
   return null;
  }
}
// Extracts the error message from the stack trace
private void printErrorMessage(Exception e) {
  AxisFault f = (AxisFault) e;
  String a1 = f.dumpToString();
  int start = a1.indexOf("<messageString>");
  int end = a1.indexOf("</messageString>");
  if (start < end) {
   String message = a1.substring(start + 15, end - 1);
   System.out.println(message);
  } else
   System.out.println(e.getMessage());
}
/**
  * @param args
  * @throws Exception
  */
public static void main(String[] args) throws Exception {
  
  String zipName = "buruZip";// 文件名:zip包的文件名
  String password = null;// zip包的密码
  String schemaName = "buruImp";// 导入方案名:生成对象名
  // 登录信息
  String gateway = "http://localhost:9300/p2pd/servlet/dispatch";
  String nameSpace = "NTLM";
  String userID = "administrator";
  String pass = "cognos";
  // 本对象
  ExportAndRunDeployment impot = new ExportAndRunDeployment();
  impot.connectToReportServer(gateway);
  // Don't try to login if using Anonymous
  if (nameSpace != null && userID != null && pass != null)
   impot.quickLogon(nameSpace, userID, pass);
  else
   System.out.println("No logon information. Attempting to login as Anonymous user...");
  // 导入包名不为空
  if (zipName != null) {
   String impPath = impot.insertNewImport(zipName, password, schemaName);
   if (impPath == null)
    System.out.println("Problems occured while creating archive in CM " + zipName);
   String imported = impot.importPackage(schemaName, password,zipName );
   if (imported == null)
    System.out.println("Possible problems importing archive \n" + zipName
      + "no eventId  - check the Import history in Cognos Connection.");
   else {
    System.out.println("Event was sucessful: eventID=" + imported);
    impot.displayImportHistory(zipName, schemaName);
   }
  } else
   System.out.println("No Valid Archive Name Provided.");
}
public void displayImportHistory(String name, String impDeploymentName) {
  PropEnum props[] = new PropEnum[] { PropEnum.defaultName, PropEnum.searchPath, PropEnum.deployedObjectStatus,
    PropEnum.objectClass, PropEnum.status, PropEnum.hasMessage, PropEnum.deployedObjectClass };
  String impPath = "/adminFolder/importDeployment[@name='"
    + (impDeploymentName.length() > 0 ? impDeploymentName : name) + "']" + "//history//*";
  String msg = "Import started on " + Calendar.getInstance().getTime().toString() + "\n";
  msg += "Importing \"" + name + "\"";
  SearchPathMultipleObject spMulti = new SearchPathMultipleObject(impPath);
  try {
   BaseClass bc[] = cmService.query(spMulti, props, new Sort[] {}, new QueryOptions());
   if (bc != null && bc.length > 0)
    for (int i = 0; i < bc.length; i++) {
     if (bc.getObjectClass().getValue() == ClassEnum.fromString("deploymentDetail")) {
      DeploymentDetail dd = (DeploymentDetail) bc;
      // Print messages if any
      if (dd.getMessage() != null)
       System.out.println(dd.getMessage().getValue());
      if (dd.getDeployedObjectStatus().getValue() != null)
       msg += "\n" + dd.getDeployedObjectClass().getValue() + "," + dd.getDefaultName().getValue()
         + "," + dd.getDeployedObjectStatus().getValue().getValue();
     }
    }
   writeOutputToFile(logFile, msg);
  } catch (Exception e) {
   printErrorMessage(e);
  }
}
// Write the status of each object to a file
private void writeOutputToFile(String logFile, String msg) {
  try {
   FileOutputStream fos = new FileOutputStream(logFile);
   Writer w = new BufferedWriter(new OutputStreamWriter(fos));
   w.write(msg);
   w.flush();
   w.close();
   System.out.println("The Import is complete. The details have been saved to a file " + logFile);
   System.out.println(msg);
  } catch (IOException e) {
   System.out.println(e);
  }
}
public String importPackage(String importSchemaName,String passwprd, String zipName) throws Exception
{
  String eventID = null;
  
//  DeploymentImportRule pacInfo[] = new DeploymentImportRule[1];
  DeploymentOptionString archive = new DeploymentOptionString();
  DeploymentOptionBoolean packageSelect = new DeploymentOptionBoolean();
//  MultilingualToken mt[] = new MultilingualToken[1];
//  mt[0] = new MultilingualToken();
//  mt[0].setLocale("en-us");
//  mt[0].setValue("tp");
  
  String impPath="/adminFolder/adminFolder[@name='buru']/importDeployment[@name='"+importSchemaName+"']";
  SearchPathSingleObject spSingle = new SearchPathSingleObject(impPath);
  
  ///
  // The timeout has to be increased when the system is running out of resources
  org.apache.axis.client.Stub s = (org.apache.axis.client.Stub) cmService;
  s.setTimeout(0); // set to not timeout
  System.out.println("Importing archive " + importSchemaName + "... Please wait...");
  ///
  
  // Get archive object  
  BaseClass[] ArchiveInfo = cmService.query(new SearchPathMultipleObject(impPath), new PropEnum[] {PropEnum.searchPath, PropEnum.options}, new Sort[]{}, new QueryOptions());
  
//  pacInfo[0] = new DeploymentImportRule();
//  //原来的路径(导出的时候所在的路径,在包里面存储了这个信息)
//  pacInfo[0].setArchiveSearchPath(new SearchPathSingleObject("/content/package[@name='" + "tp" + "']"));//content/package[@name='" + packName + "']"));
//  pacInfo[0].setName(mt);  //package
//  //导入到的路径(就是你配置的导入到的位置)
//  pacInfo[0].setParent(new SearchPathSingleObject("/content/folder[@name='123']"));
  archive.setName(DeploymentOptionEnum.fromString("archive"));
  archive.setValue(importSchemaName);
  
  packageSelect.setName(DeploymentOptionEnum.fromString("packageSelect"));
  packageSelect.setValue(false);
  
  OptionArrayProp depoptsarr = ((ImportDeployment)ArchiveInfo[0]).getOptions();
  
  Option[] depopts = depoptsarr.getValue();
  DeploymentImportRule old[] = new DeploymentImportRule[]{};
  
  int i;
  
  for (i=0;i<depopts.length;i++){
   if(depopts instanceof DeploymentOptionImportRuleArray){
    old = ((DeploymentOptionImportRuleArray)depopts).getValue();
   
    DeploymentOptionImportRuleArray importRule=(DeploymentOptionImportRuleArray)depopts;
   
    DeploymentImportRule[] importRuleArray=importRule.getValue();
    for(int k=0;k<importRuleArray.length;k++){
     DeploymentImportRule  r=importRuleArray[k];
     
     //这里设置名字(显然是支持多语言的)
     MultilingualToken mt[] = new MultilingualToken[1];
     mt[0] = new MultilingualToken();
     mt[0].setLocale("en-us");
     mt[0].setValue("tp"+k);
     r.setName(mt);
     r.setParent(new SearchPathSingleObject("/content/folder[@name='123']"));//设置目标位置
    }
//    ((DeploymentOptionImportRuleArray)depopts).setValue(pacInfo);
   
   }
   
  }
  
  depoptsarr.setValue(depopts);
  
  ((ImportDeployment) ArchiveInfo[0]).setOptions(depoptsarr);
  
  try {
   cmService.update(ArchiveInfo, new UpdateOptions());
   
   AsynchReply result = monitorService.run(spSingle, new ParameterValue[]{}, new Option[]{});
   // See DCF 1375609 for details regarding this change
   AsynchReply reply = monitorService.run(spSingle, new ParameterValue[] {}, new Option[] {});
   if (!reply.getStatus().equals(AsynchReplyStatusEnum.conversationComplete)) {
    while (!reply.getStatus().equals(AsynchReplyStatusEnum.conversationComplete)) {
     reply = monitorService.wait(reply.getPrimaryRequest(), new ParameterValue[] {}, new Option[] {});
    }
   }
   if (reply.getStatus().getValue().equals("conversationComplete")
     || reply.getStatus().getValue().equals("complete"))
    eventID = ((AsynchDetailEventID) reply.getDetails()[0]).getEventID();
   
   for (i=0;i<depopts.length;i++){
    if(depopts instanceof DeploymentOptionImportRuleArray){
     ((DeploymentOptionImportRuleArray)depopts).setValue(old);
    }     
   }
   
   OptionArrayProp x = new OptionArrayProp();
   x.setValue(depopts);
   
   ((ImportDeployment) ArchiveInfo[0]).setOptions(x);
   
//   cmService.update(ArchiveInfo, new UpdateOptions());
   
   System.out.println("Imported " + zipName);
  }
  catch(Exception e){
   e.printStackTrace();
  }
  return eventID;
}
// Import the archive
public String importPackage2(String name, String password, String importDeploymentName) {
  String impPath = "/adminFolder/adminFolder[@name='buru']/importDeployment[@name='"
    + (importDeploymentName.length() > 0 ? importDeploymentName : name) + "']";
  String eventID = null;
  try {
   // The timeout has to be increased when the system is running out of resources
   org.apache.axis.client.Stub s = (org.apache.axis.client.Stub) cmService;
   s.setTimeout(0); // set to not timeout
   System.out.println("Importing archive " + name + "... Please wait...");
   SearchPathSingleObject spSingle = new SearchPathSingleObject(impPath);
   // See DCF 1375609 for details regarding this change
   AsynchReply reply = monitorService.run(spSingle, new ParameterValue[] {}, new Option[] {});
   if (!reply.getStatus().equals(AsynchReplyStatusEnum.conversationComplete)) {
    while (!reply.getStatus().equals(AsynchReplyStatusEnum.conversationComplete)) {
     reply = monitorService.wait(reply.getPrimaryRequest(), new ParameterValue[] {}, new Option[] {});
    }
   }
   if (reply.getStatus().getValue().equals("conversationComplete")
     || reply.getStatus().getValue().equals("complete"))
    eventID = ((AsynchDetailEventID) reply.getDetails()[0]).getEventID();
  } catch (Exception e) {
   printErrorMessage(e);
  }
  return eventID;
}

// This method connects to ReportNet
public void connectToReportServer(String endPoint) {
  ContentManagerService_ServiceLocator cmServiceLocator = new ContentManagerService_ServiceLocator();
  MonitorService_ServiceLocator moServiceLocator = new MonitorService_ServiceLocator();
  try {
   cmService = cmServiceLocator.getcontentManagerService(new java.net.URL(endPoint));
   monitorService = moServiceLocator.getmonitorService(new java.net.URL(endPoint));
   // set the Axis request timeout
   ((Stub) cmService).setTimeout(0); // in milliseconds, 0 turns the timeout off
   ((Stub) monitorService).setTimeout(0); // in milliseconds, 0 turns the timeout off
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (ServiceException e) {
   e.printStackTrace();
  }
}
// This method logs the user to Cognos 8
public String quickLogon(String namespace, String uid, String pwd) {
  StringBuffer credentialXML = new StringBuffer();
  credentialXML.append("<credential>");
  credentialXML.append("<namespace>").append(namespace).append("</namespace>");
  credentialXML.append("<username>").append(uid).append("</username>");
  credentialXML.append("<password>").append(pwd).append("</password>");
  credentialXML.append("</credential>");
  String encodedCredentials = credentialXML.toString();
  XmlEncodedXML xmlCredentials = new XmlEncodedXML();
  xmlCredentials.setValue(encodedCredentials);
  // Invoke the ContentManager service logon() method passing the credential string
  // You will pass an empty string in the second argument. Optionally,
  // you could pass the Role as an argument
  try {
   cmService.logon(xmlCredentials, null);
  } catch (Exception e) {
   System.out.println(e);
  }
  BiBusHeader CMbibus = (BiBusHeader) ((Stub) cmService).getHeaderObject("", "biBusHeader");
  if (CMbibus != null)
   ((Stub) monitorService).setHeader("", "biBusHeader", CMbibus);
  return ("Logon successful as " + uid);
}
}


该贴已经同步到 xiaoerp的微博
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|Archiver|小黑屋|手机版|壹佰网 ERP100 ( 京ICP备19053597号-2 )

Copyright © 2005-2012 北京海之大网络技术有限责任公司 服务器托管由互联互通
手机:13911575376
网站技术点击发送消息给对方83569622   广告&合作 点击发送消息给对方27675401   点击发送消息给对方634043306   咨询及人才点击发送消息给对方138011526

GMT+8, 2025/11/30 07:12 , Processed in 0.013141 second(s), 14 queries , File On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表