Print.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. /**
  2. Licensed Materials - Property of IBM
  3. IBM Cognos Products: DOCS
  4. (C) Copyright IBM Corp. 2005, 2008
  5. US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with
  6. IBM Corp.
  7. */
  8. /**
  9. * Print.java
  10. *
  11. * Copyright (C) 2008 Cognos ULC, an IBM Company. All rights reserved.
  12. * Cognos (R) is a trademark of Cognos ULC, (formerly Cognos Incorporated).
  13. *
  14. * Description: This code sample demonstrates how to run and print a report,
  15. * and how to get, add, and delete printers from the content store using the
  16. * following methods:
  17. * - run
  18. * Use this method to run a report, query, or report view.
  19. * - wait
  20. * Use this method to notify the server that the issuer of the request
  21. * is still waiting for the output, and to request that the processing
  22. * be continued.
  23. * - deliver
  24. * Use this method to request that the output of a report be printed
  25. * - query
  26. * Use this method to request objects from Content Manager.
  27. * - update
  28. * Use this method to modify existing objects in the content store.
  29. * - release
  30. * Use this method to remove inactive requests from the report service
  31. * cache earlier than they would be removed automatically by the system.
  32. * Removing abandoned requests makes resources available for
  33. * other requests, improving performance.
  34. * - delete
  35. * Use this method to delete objects from the content store.
  36. */
  37. import com.cognos.developer.schemas.bibus._3.AsynchReply;
  38. import com.cognos.developer.schemas.bibus._3.AsynchReplyStatusEnum;
  39. import com.cognos.developer.schemas.bibus._3.AsynchRequest;
  40. import com.cognos.developer.schemas.bibus._3.AsynchSecondaryRequest;
  41. import com.cognos.developer.schemas.bibus._3.BaseClass;
  42. import com.cognos.developer.schemas.bibus._3.BaseParameter;
  43. import com.cognos.developer.schemas.bibus._3.DeleteOptions;
  44. import com.cognos.developer.schemas.bibus._3.Option;
  45. import com.cognos.developer.schemas.bibus._3.ParameterValue;
  46. import com.cognos.developer.schemas.bibus._3.Printer;
  47. import com.cognos.developer.schemas.bibus._3.PropEnum;
  48. import com.cognos.developer.schemas.bibus._3.QueryOptions;
  49. import com.cognos.developer.schemas.bibus._3.RunOptionBoolean;
  50. import com.cognos.developer.schemas.bibus._3.RunOptionEnum;
  51. import com.cognos.developer.schemas.bibus._3.RunOptionString;
  52. import com.cognos.developer.schemas.bibus._3.RunOptionStringArray;
  53. import com.cognos.developer.schemas.bibus._3.SearchPathMultipleObject;
  54. import com.cognos.developer.schemas.bibus._3.SearchPathSingleObject;
  55. import com.cognos.developer.schemas.bibus._3.Sort;
  56. import com.cognos.developer.schemas.bibus._3.StringProp;
  57. import com.cognos.developer.schemas.bibus._3.TokenProp;
  58. import com.cognos.developer.schemas.bibus._3.UpdateOptions;
  59. public class Print
  60. {
  61. /**
  62. * This Java method returns a boolean that indicates whether this report
  63. * printed successfully on the specified printer.
  64. * @param connection
  65. * Connection to Server
  66. * @param report
  67. * Specifies the report.
  68. * @param printerPath
  69. * Specifies the location of the printer. Use the getAvailablePrinters
  70. * Java method to select the location of the printer.
  71. * @param asynchRequest
  72. * Specifies the primary request. If no primary response is passed
  73. * to this method, this method calls the report service run method.
  74. * A primary request is necessary to issue a secondary request, such
  75. * as a print request, because a secondary request can only continue a
  76. * conversation established by a primary request.
  77. */
  78. public String print(
  79. CRNConnect connection,
  80. BaseClassWrapper report,
  81. String printerPath,
  82. AsynchRequest asynchRequest)
  83. {
  84. AsynchReply asynchReply = null;
  85. String reportPath = report.getBaseClassObject().getSearchPath().getValue();
  86. try
  87. {
  88. Option[] options = setPrintRunOptions(printerPath);
  89. ParameterValue parameterValues[] = new ParameterValue[] {};
  90. ReportParameters reportParameters = new ReportParameters();
  91. BaseParameter[] baseParameters = reportParameters.getReportParameters(report, connection);
  92. //if no current request is passed in, we need to run the report
  93. if (asynchRequest == null)
  94. {
  95. if (baseParameters != null && baseParameters.length > 0)
  96. {
  97. parameterValues = ReportParameters.setReportParameters(baseParameters);
  98. }
  99. if (parameterValues == null || parameterValues.length <= 0)
  100. {
  101. parameterValues = new ParameterValue[] {};
  102. }
  103. //set options for running report
  104. Option execReportRunOptions[] = new Option[2];
  105. RunOptionBoolean saveOutputRunOption = new RunOptionBoolean();
  106. RunOptionBoolean promptFlag = new RunOptionBoolean();
  107. //Set the option for saving the output to false
  108. saveOutputRunOption.setName(RunOptionEnum.saveOutput);
  109. saveOutputRunOption.setValue(false);
  110. //Set the report not to prompt as we pass the parameter (if any)
  111. promptFlag.setName(RunOptionEnum.prompt);
  112. promptFlag.setValue(false);
  113. // Fill the array with the rest of the run options.
  114. execReportRunOptions[0] = saveOutputRunOption;
  115. execReportRunOptions[1] = promptFlag;
  116. //Run report
  117. asynchReply =
  118. connection.getReportService().run(
  119. new SearchPathSingleObject(reportPath),
  120. parameterValues,
  121. execReportRunOptions);
  122. // If response is not immediately complete, call wait until complete
  123. if (!asynchReply.getStatus().equals(AsynchReplyStatusEnum.complete))
  124. {
  125. while (!asynchReply.getStatus().equals(AsynchReplyStatusEnum.complete))
  126. {
  127. //before calling wait, double check that it is okay
  128. if (hasSecondaryRequest(asynchReply, "wait"))
  129. {
  130. asynchReply =
  131. connection.getReportService().wait(
  132. asynchReply.getPrimaryRequest(),
  133. new ParameterValue[] {},
  134. new Option[] {});
  135. }
  136. else
  137. {
  138. return "Error: Wait method not available as expected.";
  139. }
  140. }
  141. }
  142. asynchRequest = asynchReply.getPrimaryRequest();
  143. }
  144. if (asynchRequest != null)
  145. {
  146. //call print
  147. asynchReply = connection.getReportService().deliver(asynchRequest, parameterValues, options);
  148. // If response is not immediately complete, call wait until complete
  149. if ((!asynchReply.getStatus().equals(AsynchReplyStatusEnum.complete)) && (!asynchReply.getStatus().equals(AsynchReplyStatusEnum.conversationComplete)))
  150. {
  151. while ((!asynchReply.getStatus().equals(AsynchReplyStatusEnum.complete))
  152. && (!asynchReply.getStatus().equals(AsynchReplyStatusEnum.conversationComplete)))
  153. {
  154. //before calling wait, double check that it is okay
  155. if (hasSecondaryRequest(asynchReply, "wait"))
  156. {
  157. asynchReply =
  158. connection.getReportService().wait(
  159. asynchReply.getPrimaryRequest(),
  160. new ParameterValue[] {},
  161. new Option[] {});
  162. }
  163. else
  164. {
  165. return "Error: Wait method not available as expected.";
  166. }
  167. }
  168. }
  169. }
  170. else
  171. {
  172. System.out.println(
  173. "AsynchRequest null, unable to issue secondary request.");
  174. }
  175. // release the conversation to free resources.
  176. connection.getReportService().release(asynchRequest);
  177. }
  178. catch (Exception e)
  179. {
  180. System.out.println(
  181. "An error occurred in the print Java method.\n" + e);
  182. return "An error occurred in the print Java method.";
  183. }
  184. return "Print method complete";
  185. }
  186. /**
  187. * This Java method returns an array that specifies the run options
  188. * required by the print Java method.
  189. * @param printerPath
  190. * Specifies the location of the printer. Use the getAvailablePrinters
  191. * Java method to select the location of the printer.
  192. */
  193. private Option[] setPrintRunOptions(String printerPath)
  194. {
  195. try
  196. {
  197. Option[] options = new Option[4];
  198. RunOptionString printer = new RunOptionString();
  199. printer.setName(RunOptionEnum.printer);
  200. printer.setValue(printerPath);
  201. RunOptionBoolean print = new RunOptionBoolean();
  202. print.setName(RunOptionEnum.print);
  203. print.setValue(true);
  204. // Set the output format for the report to PDF.
  205. RunOptionStringArray format = new RunOptionStringArray();
  206. format.setName(RunOptionEnum.outputFormat);
  207. format.setValue(new String[] { "PDF" });
  208. //Set the report not to prompt as we pass the parameter (if any)
  209. RunOptionBoolean promptFlag = new RunOptionBoolean();
  210. promptFlag.setName(RunOptionEnum.prompt);
  211. promptFlag.setValue(false);
  212. options[0] = printer;
  213. options[1] = print;
  214. options[2] = format;
  215. options[3] = promptFlag;
  216. return options;
  217. }
  218. catch (Exception e)
  219. {
  220. System.out.println("Exception in Print.class\n" + e);
  221. return null;
  222. }
  223. }
  224. /**
  225. * This Java method gets information for all available printers from
  226. * the content store and returns a BaseClass array of printer objects.
  227. *
  228. * @param connection
  229. * Connection to Server
  230. *
  231. * @return printers[]
  232. * Returns an array containing the searchPath and defaultName
  233. * properties for each printer.
  234. */
  235. public BaseClass[] getAvailablePrinters(CRNConnect connection)
  236. {
  237. BaseClass printers[] = new BaseClass[] {};
  238. PropEnum props[] =
  239. new PropEnum[] { PropEnum.searchPath, PropEnum.defaultName };
  240. try
  241. {
  242. printers =
  243. connection.getCMService().query(
  244. new SearchPathMultipleObject("CAMID(\":\")/printer"),
  245. props,
  246. new Sort[] {},
  247. new QueryOptions());
  248. }
  249. catch (Exception e)
  250. {
  251. System.out.println(e);
  252. }
  253. return printers;
  254. }
  255. /**
  256. * This Java method adds a new printer to the content store.
  257. * @param connection
  258. * Connection to Server
  259. * @param name
  260. * Specifies a unique name for the printer.
  261. * @param networkAddress
  262. * Specifies the network address of the new printer.
  263. * @return
  264. * Returns an integer with a value of 1 if the printer was created
  265. * successfully in the content store or 0 if the request failed.
  266. */
  267. public String addPrinter(
  268. CRNConnect connection,
  269. String name,
  270. String networkAddress)
  271. {
  272. PropEnum props[] =
  273. new PropEnum[] {
  274. PropEnum.searchPath,
  275. PropEnum.defaultName,
  276. PropEnum.parent };
  277. try
  278. {
  279. BaseClass[] printers =
  280. connection.getCMService().query(
  281. new SearchPathMultipleObject("CAMID(\":\")/printer[@name=\'" + name + "\']"),
  282. props,
  283. new Sort[] {},
  284. new QueryOptions());
  285. if ((printers != null) && (printers.length > 0))
  286. {
  287. return ("A printer with this name already exists.");
  288. }
  289. StringProp location = new StringProp();
  290. String printerPath = "CAMID(\":\")";
  291. TokenProp printerName = new TokenProp();
  292. printerName.setValue(name);
  293. location.setValue(networkAddress);
  294. // DO NOT set searchPath when you add an object to the content store.
  295. Printer newPrinter = new Printer();
  296. newPrinter.setDefaultName(printerName);
  297. newPrinter.setPrinterAddress(location);
  298. // Identify the printer parent object.
  299. printers =
  300. connection.getCMService().query(
  301. new SearchPathMultipleObject(printerPath),
  302. props,
  303. new Sort[] {},
  304. new QueryOptions());
  305. newPrinter.setParent(printers[0].getParent());
  306. CSHandlers csh = new CSHandlers();
  307. csh.addObjectToCS(connection, newPrinter, printerPath);
  308. return "Printer added successfully";
  309. }
  310. catch (Exception e)
  311. {
  312. System.out.println(e);
  313. return "Failed to add new printer";
  314. }
  315. }
  316. /**
  317. * This Java method updates the network address of a printer in
  318. * the content store.
  319. *
  320. * @param connection
  321. * Connection to Server
  322. * @param name
  323. * Specifies a unique name for the printer.
  324. * @param networkAddress
  325. * Specifies the network address of the new printer.
  326. * @return
  327. * Returns an integer with a value of 1 if the printer's network
  328. * address was updated successfully or 0 if the request failed.
  329. */
  330. public String changePrinterAddress(
  331. CRNConnect connection,
  332. String name,
  333. String newNetworkAddress)
  334. {
  335. PropEnum props[] =
  336. new PropEnum[] { PropEnum.searchPath, PropEnum.defaultName };
  337. Printer prt = new Printer();
  338. try
  339. {
  340. BaseClass[] printers =
  341. connection.getCMService().query(
  342. new SearchPathMultipleObject("CAMID(\":\")/printer"),
  343. props,
  344. new Sort[] {},
  345. new QueryOptions());
  346. for (int i = 0; i < printers.length; i++)
  347. {
  348. String printerName = printers[i].getDefaultName().getValue();
  349. if (printerName.compareToIgnoreCase(name) == 0)
  350. {
  351. prt = (Printer)printers[i];
  352. }
  353. }
  354. StringProp networkAddress = new StringProp();
  355. networkAddress.setValue(newNetworkAddress);
  356. prt.setPrinterAddress(networkAddress);
  357. BaseClass[] bc = new BaseClass[1];
  358. bc[0] = prt;
  359. PropEnum[] updateReturnProps = new PropEnum[] { PropEnum.printerAddress };
  360. UpdateOptions updateOpts = new UpdateOptions();
  361. updateOpts.setReturnProperties(updateReturnProps);
  362. BaseClass[] newBc = connection.getCMService().update(bc, updateOpts);
  363. return (
  364. "Network Address for printer "
  365. + name
  366. + " set to "
  367. + ((Printer)newBc[0]).getPrinterAddress().getValue()
  368. + ".");
  369. }
  370. catch (Exception e)
  371. {
  372. System.out.println(e);
  373. return ("Exception occurred attempting to change printer address");
  374. }
  375. }
  376. /**
  377. * This Java method updates the name of a printer in the content store.
  378. * @param connection
  379. * Connection to Server
  380. * @param oldName
  381. * Specifies the current name of the printer.
  382. * @param newName
  383. * Specifies a new unique name for the printer.
  384. * @return
  385. * Returns an integer with a value of 1 if the printer's name was
  386. * updated successfully or 0 if the request failed.
  387. */
  388. public String changePrinterName(
  389. CRNConnect connection,
  390. String oldName,
  391. String newName)
  392. {
  393. PropEnum props[] =
  394. new PropEnum[] { PropEnum.searchPath, PropEnum.defaultName };
  395. Printer prt = new Printer();
  396. try
  397. {
  398. BaseClass[] printers =
  399. connection.getCMService().query(
  400. new SearchPathMultipleObject("CAMID(\":\")/printer"),
  401. props,
  402. new Sort[] {},
  403. new QueryOptions());
  404. for (int i = 0; i < printers.length; i++)
  405. {
  406. String printerName = printers[i].getDefaultName().getValue();
  407. if (printerName.compareToIgnoreCase(oldName) == 0)
  408. {
  409. prt = (Printer)printers[i];
  410. }
  411. }
  412. TokenProp newNameT = new TokenProp();
  413. newNameT.setValue(newName);
  414. prt.setDefaultName(newNameT);
  415. BaseClass[] bc = new BaseClass[1];
  416. bc[0] = prt;
  417. BaseClass[] newBc = connection.getCMService().update(bc, new UpdateOptions());
  418. return (
  419. "Printer "
  420. + oldName
  421. + " renamed to "
  422. + ((Printer)newBc[0]).getDefaultName().getValue()
  423. + ".");
  424. }
  425. catch (Exception e)
  426. {
  427. System.out.println(e);
  428. return ("Exception occurred attempting to change printer name");
  429. }
  430. }
  431. /**
  432. * This Java method deletes a printer from the content store.
  433. * @param connection
  434. * Connection to Server
  435. * @param name
  436. * Specifies the unique name of the printer.
  437. * @return
  438. * Returns an integer with a value of 1 if the printer was deleted
  439. * successfully or 0 if the request failed.
  440. */
  441. public String deletePrinter(CRNConnect connection, String name)
  442. {
  443. PropEnum props[] =
  444. new PropEnum[] {
  445. PropEnum.searchPath,
  446. PropEnum.defaultName,
  447. PropEnum.parent };
  448. String toBeDeleted = new String();
  449. //Printer newPrinter = new Printer();
  450. try
  451. {
  452. BaseClass[] printers =
  453. connection.getCMService().query(
  454. new SearchPathMultipleObject("CAMID(\":\")/printer"),
  455. props,
  456. new Sort[] {},
  457. new QueryOptions());
  458. boolean doesExist = false;
  459. for (int i = 0; i < printers.length; i++)
  460. {
  461. String printerName = printers[i].getDefaultName().getValue();
  462. if (printerName.compareToIgnoreCase(name) == 0)
  463. {
  464. toBeDeleted = name;
  465. doesExist = true;
  466. break;
  467. }
  468. }
  469. if (!doesExist)
  470. {
  471. return ("Printer does not exist!");
  472. }
  473. // Set the options for the delete method.
  474. DeleteOptions del = new DeleteOptions();
  475. // Set the force option to true. When the force option is true, a
  476. // selected object will be deleted if the current user has either
  477. // write or setPolicy permission for the following:
  478. // - the selected object
  479. // - the parent of the selected object
  480. // - every descendant of the selected object
  481. del.setForce(true);
  482. if (toBeDeleted != null)
  483. {
  484. System.out.println("Deleting printer: " + toBeDeleted);
  485. BaseClass bc[] =
  486. connection.getCMService().query(
  487. new SearchPathMultipleObject("CAMID(\":\")/printer[@name=\'" + toBeDeleted + "\']"),
  488. props,
  489. new Sort[] {},
  490. new QueryOptions());
  491. if ((bc != null) && (bc.length > 0))
  492. {
  493. int i = connection.getCMService().delete(bc, del);
  494. if (i > 0)
  495. {
  496. return (
  497. "The printer "
  498. + toBeDeleted
  499. + " was deleted successfully");
  500. }
  501. else
  502. {
  503. return (
  504. "Error occurred while deleting the printer "
  505. + toBeDeleted);
  506. }
  507. }
  508. else
  509. {
  510. return ("Printer " + name + " was not found");
  511. }
  512. }
  513. }
  514. catch (Exception e)
  515. {
  516. System.out.println(e.getMessage());
  517. return ("Caught Exception while deleting printer.");
  518. }
  519. return "Error occurred in deletePrinter.";
  520. }
  521. public boolean hasSecondaryRequest(
  522. AsynchReply response,
  523. String secondaryRequest)
  524. {
  525. AsynchSecondaryRequest[] secondaryRequests =
  526. response.getSecondaryRequests();
  527. for (int i = 0; i < secondaryRequests.length; i++)
  528. {
  529. if (secondaryRequests[i].getName().compareTo(secondaryRequest)
  530. == 0)
  531. {
  532. return true;
  533. }
  534. }
  535. return false;
  536. }
  537. }