IppPrintService.java 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. /* IppPrintService.java --
  2. Copyright (C) 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.javax.print.ipp;
  32. import gnu.classpath.SystemProperties;
  33. import gnu.classpath.debug.Component;
  34. import gnu.classpath.debug.SystemLogger;
  35. import gnu.javax.print.ipp.attribute.DefaultValueAttribute;
  36. import gnu.javax.print.ipp.attribute.RequestedAttributes;
  37. import gnu.javax.print.ipp.attribute.defaults.CopiesDefault;
  38. import gnu.javax.print.ipp.attribute.defaults.FinishingsDefault;
  39. import gnu.javax.print.ipp.attribute.defaults.JobHoldUntilDefault;
  40. import gnu.javax.print.ipp.attribute.defaults.JobPriorityDefault;
  41. import gnu.javax.print.ipp.attribute.defaults.JobSheetsDefault;
  42. import gnu.javax.print.ipp.attribute.defaults.MediaDefault;
  43. import gnu.javax.print.ipp.attribute.defaults.MultipleDocumentHandlingDefault;
  44. import gnu.javax.print.ipp.attribute.defaults.NumberUpDefault;
  45. import gnu.javax.print.ipp.attribute.defaults.OrientationRequestedDefault;
  46. import gnu.javax.print.ipp.attribute.defaults.PrintQualityDefault;
  47. import gnu.javax.print.ipp.attribute.defaults.PrinterResolutionDefault;
  48. import gnu.javax.print.ipp.attribute.defaults.SidesDefault;
  49. import gnu.javax.print.ipp.attribute.printer.DocumentFormat;
  50. import gnu.javax.print.ipp.attribute.supported.CompressionSupported;
  51. import gnu.javax.print.ipp.attribute.supported.DocumentFormatSupported;
  52. import gnu.javax.print.ipp.attribute.supported.FinishingsSupported;
  53. import gnu.javax.print.ipp.attribute.supported.JobHoldUntilSupported;
  54. import gnu.javax.print.ipp.attribute.supported.JobSheetsSupported;
  55. import gnu.javax.print.ipp.attribute.supported.MediaSupported;
  56. import gnu.javax.print.ipp.attribute.supported.MultipleDocumentHandlingSupported;
  57. import gnu.javax.print.ipp.attribute.supported.OperationsSupported;
  58. import gnu.javax.print.ipp.attribute.supported.OrientationRequestedSupported;
  59. import gnu.javax.print.ipp.attribute.supported.PageRangesSupported;
  60. import gnu.javax.print.ipp.attribute.supported.PrintQualitySupported;
  61. import gnu.javax.print.ipp.attribute.supported.PrinterResolutionSupported;
  62. import gnu.javax.print.ipp.attribute.supported.PrinterUriSupported;
  63. import gnu.javax.print.ipp.attribute.supported.SidesSupported;
  64. import java.io.IOException;
  65. import java.lang.reflect.Field;
  66. import java.net.URI;
  67. import java.util.ArrayList;
  68. import java.util.Arrays;
  69. import java.util.Date;
  70. import java.util.HashSet;
  71. import java.util.Iterator;
  72. import java.util.List;
  73. import java.util.Map;
  74. import java.util.Set;
  75. import java.util.logging.Logger;
  76. import javax.print.DocFlavor;
  77. import javax.print.DocPrintJob;
  78. import javax.print.PrintService;
  79. import javax.print.ServiceUIFactory;
  80. import javax.print.attribute.Attribute;
  81. import javax.print.attribute.AttributeSet;
  82. import javax.print.attribute.AttributeSetUtilities;
  83. import javax.print.attribute.HashAttributeSet;
  84. import javax.print.attribute.HashPrintServiceAttributeSet;
  85. import javax.print.attribute.IntegerSyntax;
  86. import javax.print.attribute.PrintServiceAttribute;
  87. import javax.print.attribute.PrintServiceAttributeSet;
  88. import javax.print.attribute.standard.Compression;
  89. import javax.print.attribute.standard.Copies;
  90. import javax.print.attribute.standard.CopiesSupported;
  91. import javax.print.attribute.standard.Fidelity;
  92. import javax.print.attribute.standard.Finishings;
  93. import javax.print.attribute.standard.JobHoldUntil;
  94. import javax.print.attribute.standard.JobImpressions;
  95. import javax.print.attribute.standard.JobImpressionsSupported;
  96. import javax.print.attribute.standard.JobKOctets;
  97. import javax.print.attribute.standard.JobKOctetsSupported;
  98. import javax.print.attribute.standard.JobMediaSheets;
  99. import javax.print.attribute.standard.JobMediaSheetsSupported;
  100. import javax.print.attribute.standard.JobName;
  101. import javax.print.attribute.standard.JobPriority;
  102. import javax.print.attribute.standard.JobPrioritySupported;
  103. import javax.print.attribute.standard.JobSheets;
  104. import javax.print.attribute.standard.Media;
  105. import javax.print.attribute.standard.MultipleDocumentHandling;
  106. import javax.print.attribute.standard.NumberUp;
  107. import javax.print.attribute.standard.NumberUpSupported;
  108. import javax.print.attribute.standard.OrientationRequested;
  109. import javax.print.attribute.standard.PageRanges;
  110. import javax.print.attribute.standard.PrintQuality;
  111. import javax.print.attribute.standard.PrinterName;
  112. import javax.print.attribute.standard.PrinterResolution;
  113. import javax.print.attribute.standard.PrinterURI;
  114. import javax.print.attribute.standard.RequestingUserName;
  115. import javax.print.attribute.standard.Sides;
  116. import javax.print.event.PrintServiceAttributeListener;
  117. /**
  118. * Implementation of the PrintService interface
  119. * for IPP based printers.
  120. *
  121. * @author Wolfgang Baer (WBaer@gmx.de)
  122. */
  123. public class IppPrintService implements PrintService
  124. {
  125. /**
  126. * A Map with sets of attributes.
  127. * key: A attribute category
  128. * value: A set with values
  129. *
  130. * IPP may return sets of attributes e.g. for supported
  131. * compression methods so we need to map to sets here.
  132. */
  133. private Map<Class<? extends Attribute>, Set<Attribute>> printerAttr;
  134. /** The set of listeners.*/
  135. private HashSet<PrintServiceAttributeListener> printServiceAttributeListener;
  136. /** The username. */
  137. private transient String user;
  138. /** The password of the user. */
  139. private transient String passwd;
  140. /** The name of this print service. */
  141. private String name;
  142. /** The list of supported document flavors. */
  143. private List<DocFlavor> flavors;
  144. /** The standard printer URI. */
  145. private PrinterURI printerUri;
  146. /** The list of all supported printer URIs. */
  147. private ArrayList<PrinterURI> printerUris;
  148. /**
  149. * Logger for tracing - enable by passing
  150. * -Dgnu.classpath.debug.components=ipp to the vm.
  151. */
  152. static final Logger logger = SystemLogger.SYSTEM;
  153. /**
  154. * requesting-user-name defaults to the executing user.
  155. */
  156. public static final RequestingUserName REQUESTING_USER_NAME;
  157. /**
  158. * job-name defaults to "Java Printing".
  159. */
  160. public static final JobName JOB_NAME;
  161. static
  162. {
  163. JOB_NAME = new JobName("Java Printing", null);
  164. REQUESTING_USER_NAME = new RequestingUserName(
  165. SystemProperties.getProperty("user.name", ""), null);
  166. }
  167. // TODO Implement service listener notification and change detection.
  168. /**
  169. * Creates a <code>IppPrintService</code> object.
  170. *
  171. * @param uri the URI of the IPP printer.
  172. * @param username the user of this print service.
  173. * @param password the password of the user.
  174. *
  175. * @throws IppException if an error during connection occurs.
  176. */
  177. public IppPrintService(URI uri, String username, String password)
  178. throws IppException
  179. {
  180. printerUri = new PrinterURI(uri);
  181. user = username;
  182. passwd = password;
  183. printServiceAttributeListener =
  184. new HashSet<PrintServiceAttributeListener>();
  185. printerAttr = getPrinterAttributes();
  186. processResponse();
  187. }
  188. /**
  189. * Fetches all printer attributes from the IPP printer.
  190. *
  191. * @return The Map with the printer attributes.
  192. * @throws IppException if an error occurs.
  193. */
  194. private Map<Class<? extends Attribute>, Set<Attribute>> getPrinterAttributes()
  195. throws IppException
  196. {
  197. IppResponse response = null;
  198. try
  199. {
  200. IppRequest request = new IppRequest(printerUri.getURI(), user, passwd);
  201. int operation = OperationsSupported.GET_PRINTER_ATTRIBUTES.getValue();
  202. request.setOperationID((short) operation);
  203. request.setOperationAttributeDefaults();
  204. request.addOperationAttribute(printerUri);
  205. response = request.send();
  206. }
  207. catch (IOException e)
  208. {
  209. throw new IppException("IOException in IPP request/response.", e);
  210. }
  211. return response.getPrinterAttributes().get(0);
  212. }
  213. /**
  214. * Extracts the set of attribute values for a given
  215. * attribute category from the printer attributes map.
  216. *
  217. * @param attributeClass the category
  218. * @return The set of attributes of the category.
  219. */
  220. private <T extends Attribute> Set<T> getPrinterAttributeSet(Class<T> attributeClass)
  221. {
  222. Set<Attribute> set = printerAttr.get(attributeClass);
  223. Set<T> attSet = new HashSet<T>();
  224. for (Attribute att : set)
  225. attSet.add(attributeClass.cast(att));
  226. return attSet;
  227. }
  228. /**
  229. * Extracts the default attribute value for the given
  230. * default attribute category from the printer attributes map.
  231. *
  232. * @param attributeClass the category
  233. * @return The default attribute.
  234. *
  235. * @throws ClassCastException if attributClass is not an
  236. * instance of <code>DefaultValueAttribute</code>.
  237. */
  238. private Attribute getPrinterDefaultAttribute(Class<? extends Attribute> attributeClass)
  239. {
  240. Set<Attribute> set = printerAttr.get(attributeClass);
  241. return ((DefaultValueAttribute) set.toArray()[0]).getAssociatedAttribute();
  242. }
  243. /**
  244. * Processes the response, sorts and splits the attributes.
  245. */
  246. private void processResponse()
  247. {
  248. // printer name
  249. PrinterName[] tmp = getPrinterAttributeSet(PrinterName.class).toArray(new PrinterName[1]);
  250. name = tmp[0].getValue();
  251. // supported flavors
  252. // TODO Check if charsets-supported are charsets that are actually supported
  253. // for text doc flavors as cups doesn't send charset parameters
  254. // utf-8 is supported at least - so we go with this only for now
  255. flavors = new ArrayList<DocFlavor>();
  256. Set<DocumentFormatSupported> flavorAttributes = getPrinterAttributeSet(DocumentFormatSupported.class);
  257. if (flavorAttributes != null)
  258. {
  259. for (DocumentFormatSupported dfs : flavorAttributes)
  260. {
  261. String mimeType = dfs.getValue();
  262. if (mimeType.equals("text/plain"))
  263. {
  264. flavors.add(DocFlavor.CHAR_ARRAY.TEXT_PLAIN);
  265. flavors.add(DocFlavor.READER.TEXT_PLAIN);
  266. flavors.add(DocFlavor.STRING.TEXT_PLAIN);
  267. // add utf-8
  268. mimeType = mimeType + "; charset=utf-8";
  269. }
  270. else if (mimeType.equals("text/html"))
  271. {
  272. flavors.add(DocFlavor.CHAR_ARRAY.TEXT_HTML);
  273. flavors.add(DocFlavor.READER.TEXT_HTML);
  274. flavors.add(DocFlavor.STRING.TEXT_HTML);
  275. // add utf-8
  276. mimeType = mimeType + "; charset=utf-8";
  277. }
  278. // Process the predefined DocFlavors and if mimetype is
  279. // equal put them into the flavors array - otherwise
  280. // just build them as binarie class representation.
  281. boolean changed = false;
  282. try
  283. {
  284. Class<?>[] clazzes = new Class<?>[] { DocFlavor.BYTE_ARRAY.class,
  285. DocFlavor.INPUT_STREAM.class,
  286. DocFlavor.URL.class
  287. };
  288. for (int j = 0; j < clazzes.length; j++)
  289. {
  290. Field[] fields = clazzes[j].getDeclaredFields();
  291. for (int i = 0; i < fields.length; i++)
  292. {
  293. if (fields[i].getType().equals(clazzes[j]))
  294. {
  295. DocFlavor flavor = (DocFlavor) fields[i].get(null);
  296. if (flavor.getMimeType().equals(mimeType))
  297. changed = flavors.add(flavor);
  298. }
  299. }
  300. }
  301. if (!changed) // not in predefined constants of DocFlavor
  302. {
  303. // everything should be supported as binary stuff
  304. flavors.add(new DocFlavor(mimeType, "[B"));
  305. flavors.add(new DocFlavor(mimeType, "java.io.InputStream"));
  306. flavors.add(new DocFlavor(mimeType, "java.net.URL"));
  307. }
  308. }
  309. catch (SecurityException e)
  310. {
  311. // should not happen
  312. }
  313. catch (IllegalArgumentException e)
  314. {
  315. // should not happen
  316. }
  317. catch (IllegalAccessException e)
  318. {
  319. // should not happen, all fields are public
  320. }
  321. }
  322. if (this.getClass()
  323. .isAssignableFrom(gnu.javax.print.CupsPrintService.class))
  324. {
  325. // CUPS always provides filters to convert from Postscript.
  326. // This logic looks odd, but it's what OpenJDK does.
  327. flavors.add(DocFlavor.SERVICE_FORMATTED.PAGEABLE);
  328. flavors.add(DocFlavor.SERVICE_FORMATTED.PRINTABLE);
  329. }
  330. }
  331. // printer uris
  332. Set<PrinterUriSupported> uris = getPrinterAttributeSet(PrinterUriSupported.class);
  333. printerUris = new ArrayList<PrinterURI>(uris.size());
  334. for (PrinterUriSupported uri : uris)
  335. {
  336. printerUris.add( new PrinterURI(uri.getURI()));
  337. }
  338. }
  339. /**
  340. * We always return a implementation implementing CancelablePrintJob.
  341. *
  342. * @see javax.print.PrintService#createPrintJob()
  343. */
  344. public DocPrintJob createPrintJob()
  345. {
  346. return new DocPrintJobImpl(this, user, passwd);
  347. }
  348. /**
  349. * @see javax.print.PrintService#getAttribute(java.lang.Class)
  350. */
  351. public <T extends PrintServiceAttribute> T getAttribute(Class<T> category)
  352. {
  353. if (category == null)
  354. throw new NullPointerException("category may not be null");
  355. if (! PrintServiceAttribute.class.isAssignableFrom(category))
  356. throw new IllegalArgumentException(
  357. "category must be of type PrintServiceAttribute");
  358. Set<T> set = getPrinterAttributeSet(category);
  359. if (set != null && set.size() > 0)
  360. return set.iterator().next();
  361. return null;
  362. }
  363. /**
  364. * @see javax.print.PrintService#getAttributes()
  365. */
  366. public PrintServiceAttributeSet getAttributes()
  367. {
  368. PrintServiceAttributeSet set = new HashPrintServiceAttributeSet();
  369. for (Set<Attribute> attrSet : printerAttr.values())
  370. {
  371. for (Attribute attr : attrSet)
  372. {
  373. if (attr instanceof PrintServiceAttribute)
  374. set.add(attr);
  375. }
  376. }
  377. return AttributeSetUtilities.unmodifiableView(set);
  378. }
  379. /**
  380. * @see javax.print.PrintService#getDefaultAttributeValue(java.lang.Class)
  381. */
  382. public Object getDefaultAttributeValue(Class<? extends Attribute> category)
  383. {
  384. // required attributes
  385. if (category.equals(Fidelity.class))
  386. return Fidelity.FIDELITY_FALSE;
  387. if (category.equals(JobName.class))
  388. return JOB_NAME;
  389. if (category.equals(RequestingUserName.class))
  390. return REQUESTING_USER_NAME;
  391. // optional attributes
  392. if (category.equals(JobPriority.class)
  393. && printerAttr.containsKey(JobPriorityDefault.class))
  394. return getPrinterDefaultAttribute(JobPriorityDefault.class);
  395. if (category.equals(JobHoldUntil.class)
  396. && printerAttr.containsKey(JobHoldUntilDefault.class))
  397. return getPrinterDefaultAttribute(JobHoldUntilDefault.class);
  398. if (category.equals(JobSheets.class)
  399. && printerAttr.containsKey(JobSheetsDefault.class))
  400. return getPrinterDefaultAttribute(JobSheetsDefault .class);
  401. if (category.equals(MultipleDocumentHandling.class)
  402. && printerAttr.containsKey(MultipleDocumentHandlingDefault.class))
  403. return getPrinterDefaultAttribute(MultipleDocumentHandlingDefault.class);
  404. if (category.equals(Copies.class)
  405. && printerAttr.containsKey(CopiesDefault.class))
  406. return getPrinterDefaultAttribute(CopiesDefault.class);
  407. if (category.equals(Finishings.class)
  408. && printerAttr.containsKey(FinishingsDefault.class))
  409. return getPrinterDefaultAttribute(FinishingsDefault.class);
  410. if (category.equals(Sides.class)
  411. && printerAttr.containsKey(SidesDefault.class))
  412. return getPrinterDefaultAttribute(SidesDefault.class);
  413. if (category.equals(NumberUp.class)
  414. && printerAttr.containsKey(NumberUpDefault.class))
  415. return getPrinterDefaultAttribute(NumberUpDefault.class);
  416. if (category.equals(OrientationRequested.class)
  417. && printerAttr.containsKey(OrientationRequestedDefault.class))
  418. return getPrinterDefaultAttribute(OrientationRequestedDefault.class);
  419. if (category.equals(Media.class)
  420. && printerAttr.containsKey(MediaDefault.class))
  421. return getPrinterDefaultAttribute(MediaDefault.class);
  422. if (category.equals(PrinterResolution.class)
  423. && printerAttr.containsKey(PrinterResolutionDefault.class))
  424. return getPrinterDefaultAttribute(PrinterResolutionDefault.class);
  425. if (category.equals(PrintQuality.class)
  426. && printerAttr.containsKey(PrintQualityDefault.class))
  427. return getPrinterDefaultAttribute(PrintQualityDefault.class);
  428. if (category.equals(Compression.class)
  429. && printerAttr.containsKey(CompressionSupported.class))
  430. return Compression.NONE;
  431. if (category.equals(PageRanges.class))
  432. return new PageRanges(1, Integer.MAX_VALUE);
  433. return null;
  434. }
  435. /**
  436. * We return the value of <code>PrinterName</code> here.
  437. * @see javax.print.PrintService#getName()
  438. */
  439. public String getName()
  440. {
  441. return name;
  442. }
  443. /**
  444. * We currently provide no factories - just returns null.
  445. * @see javax.print.PrintService#getServiceUIFactory()
  446. */
  447. public ServiceUIFactory getServiceUIFactory()
  448. {
  449. // SUN does not provide any service factory for
  450. // print services (tested on linux/windows)
  451. // for the moment we do the same - just return null
  452. // later on we could provide at least the about UI dialog
  453. return null;
  454. }
  455. /**
  456. * @see javax.print.PrintService#getSupportedAttributeCategories()
  457. */
  458. public Class<?>[] getSupportedAttributeCategories()
  459. {
  460. Set<Class<? extends Attribute>> categories =
  461. new HashSet<Class<? extends Attribute>>();
  462. // Should only be job template attributes as of section 4.2
  463. if (printerAttr.containsKey(JobPrioritySupported.class))
  464. categories.add(JobPriority.class);
  465. if (printerAttr.containsKey(JobHoldUntilSupported.class))
  466. categories.add(JobHoldUntil.class);
  467. if (printerAttr.containsKey(JobSheetsSupported.class))
  468. categories.add(JobSheets.class);
  469. if (printerAttr.containsKey(MultipleDocumentHandlingSupported.class))
  470. categories.add(MultipleDocumentHandling.class);
  471. if (printerAttr.containsKey(CopiesSupported.class))
  472. categories.add(Copies.class);
  473. if (printerAttr.containsKey(FinishingsSupported.class))
  474. {
  475. // if only none finishing is supported - it does not count as supported
  476. Set<FinishingsSupported> set = getPrinterAttributeSet(FinishingsSupported.class);
  477. if (! (set.size() == 1 && set.contains(FinishingsSupported.NONE)))
  478. categories.add(Finishings.class);
  479. }
  480. if (printerAttr.containsKey(PageRangesSupported.class))
  481. categories.add(PageRanges.class);
  482. if (printerAttr.containsKey(SidesSupported.class))
  483. categories.add(Sides.class);
  484. if (printerAttr.containsKey(NumberUpSupported.class))
  485. categories.add(NumberUp.class);
  486. if (printerAttr.containsKey(OrientationRequestedSupported.class))
  487. categories.add(OrientationRequested.class);
  488. if (printerAttr.containsKey(MediaSupported.class))
  489. categories.add(Media.class);
  490. if (printerAttr.containsKey(PrinterResolutionSupported.class))
  491. categories.add(PrinterResolution.class);
  492. if (printerAttr.containsKey(PrintQualitySupported.class))
  493. categories.add(PrintQuality.class);
  494. // Chromaticity, Destination, MediaPrintableArea,
  495. // SheetCollate, PresentationDirection - not IPP attributes
  496. // attributes outside section 4.2
  497. if (printerAttr.containsKey(CompressionSupported.class))
  498. categories.add(Compression.class);
  499. if (printerAttr.containsKey(JobImpressionsSupported.class))
  500. categories.add(JobImpressions.class);
  501. if (printerAttr.containsKey(JobKOctetsSupported.class))
  502. categories.add(JobKOctets.class);
  503. if (printerAttr.containsKey(JobMediaSheetsSupported.class))
  504. categories.add(JobMediaSheets.class);
  505. // always supported as required by IPP specification
  506. categories.add(Fidelity.class);
  507. categories.add(JobName.class);
  508. categories.add(RequestingUserName.class);
  509. return categories.toArray(new Class[categories.size()]);
  510. }
  511. /**
  512. * Implemented by a GetPrinterAttributes request. Subclasses providing supported
  513. * attribute values totally different may override this methods. Subclass only in
  514. * need of handling the response differently may override the method
  515. * <code>handleSupportedAttributeValuesResponse(IppResponse, Class)</code> only.
  516. *
  517. * @see PrintService#getSupportedAttributeValues(Class, DocFlavor, AttributeSet)
  518. * @see #handleSupportedAttributeValuesResponse(IppResponse, Class)
  519. */
  520. public Object getSupportedAttributeValues(Class<? extends Attribute> category,
  521. DocFlavor flavor, AttributeSet attributes)
  522. {
  523. // We currently ignore the attribute set - there is nothing in the IPP
  524. // specification which would come closer to what we do here.
  525. if (category == null)
  526. throw new NullPointerException("category may not be null");
  527. if (!Attribute.class.isAssignableFrom(category))
  528. throw new IllegalArgumentException("category must be of type Attribute");
  529. if (flavor != null && !isDocFlavorSupported(flavor))
  530. throw new IllegalArgumentException("flavor is not supported");
  531. if (!isAttributeCategorySupported(category))
  532. return null;
  533. // always supported
  534. if (category.equals(Fidelity.class))
  535. return new Fidelity[] { Fidelity.FIDELITY_FALSE, Fidelity.FIDELITY_TRUE };
  536. if (category.equals(JobName.class))
  537. return JOB_NAME;
  538. if (category.equals(RequestingUserName.class))
  539. return REQUESTING_USER_NAME;
  540. // map category to category-supported
  541. String categoryName = IppUtilities.getSupportedAttrName(category);
  542. IppResponse response = null;
  543. try
  544. {
  545. IppRequest request = new IppRequest(printerUri.getURI(), user, passwd);
  546. request.setOperationID(
  547. (short) OperationsSupported.GET_PRINTER_ATTRIBUTES.getValue());
  548. request.setOperationAttributeDefaults();
  549. request.addOperationAttribute(new RequestedAttributes(categoryName));
  550. request.addOperationAttribute(printerUri);
  551. if (flavor != null)
  552. {
  553. DocumentFormat f = DocumentFormat.createDocumentFormat(flavor);
  554. request.addOperationAttribute(f);
  555. }
  556. response = request.send();
  557. int status = response.getStatusCode();
  558. if (! (status == IppStatusCode.SUCCESSFUL_OK
  559. || status == IppStatusCode.SUCCESSFUL_OK_IGNORED_OR_SUBSTITUED_ATTRIBUTES
  560. || status == IppStatusCode.SUCCESSFUL_OK_CONFLICTING_ATTRIBUTES) )
  561. {
  562. logger.log(Component.IPP, "Statuscode not OK - got:" + status);
  563. }
  564. }
  565. catch (IOException e)
  566. {
  567. // method cannot throw exception - just log
  568. logger.log(Component.IPP, "IOException", e);
  569. }
  570. catch (IppException e)
  571. {
  572. // method cannot throw exception - just log
  573. logger.log(Component.IPP, "IPPException", e);
  574. }
  575. return handleSupportedAttributeValuesResponse(response, category);
  576. }
  577. /**
  578. * Called to handle the supported attribute values response for the given
  579. * category. This might be overridden by subclasses with different requirements
  580. * for parsing/handling the response from the GetPrinterAttributes.
  581. *
  582. * @param response the response of the GetPrinterAttributes IPP request
  583. * @param category the category for which the supported values are requested
  584. * @return A object indicating the supported values for the given attribute
  585. * category, or <code>null</code> if this print service doesn't support the
  586. * given attribute category at all.
  587. *
  588. * @see #getSupportedAttributeValues(Class, DocFlavor, AttributeSet)
  589. */
  590. protected Object handleSupportedAttributeValuesResponse(IppResponse response,
  591. Class<? extends Attribute> category)
  592. {
  593. List<Map<Class<? extends Attribute>, Set<Attribute>>> printerAtts =
  594. response.getPrinterAttributes();
  595. // only one will be returned
  596. Map<Class<? extends Attribute>, Set<Attribute>> printerAttribute = printerAtts.get(0);
  597. Class<? extends Attribute> suppCategory = IppUtilities.getSupportedCategory(category);
  598. Set<Attribute> attr = printerAttribute.get(suppCategory);
  599. // We sometime assume its a single instance with arbritrary value just indicating
  600. // support or an array which is returned. This is because I sometimes just choosed
  601. // what sounds right to me - as I have yet to find a printer which supports every
  602. // special category in the SUN implementation to see what they return :-)
  603. // Map whats in the JSP API
  604. if (suppCategory.equals(JobPrioritySupported.class))
  605. return (JobPrioritySupported) attr.iterator().next();
  606. if (suppCategory.equals(JobHoldUntilSupported.class))
  607. return new JobHoldUntil(new Date());
  608. if (suppCategory.equals(JobSheetsSupported.class))
  609. return JobSheetsSupported.getAssociatedAttributeArray(attr);
  610. if (suppCategory.equals(MultipleDocumentHandlingSupported.class))
  611. return MultipleDocumentHandlingSupported.getAssociatedAttributeArray(attr);
  612. if (suppCategory.equals(CopiesSupported.class))
  613. return (CopiesSupported) attr.iterator().next();
  614. if (suppCategory.equals(FinishingsSupported.class))
  615. return FinishingsSupported.getAssociatedAttributeArray(attr);
  616. if (suppCategory.equals(PageRangesSupported.class))
  617. return new PageRanges[] { new PageRanges(1, Integer.MAX_VALUE) };
  618. if (suppCategory.equals(OrientationRequestedSupported.class))
  619. return OrientationRequestedSupported.getAssociatedAttributeArray(attr);
  620. if (suppCategory.equals(MediaSupported.class))
  621. return MediaSupported.getAssociatedAttributeArray(attr);
  622. if (suppCategory.equals(PrinterResolutionSupported.class))
  623. return PrinterResolutionSupported.getAssociatedAttributeArray(attr);
  624. if (suppCategory.equals(PrintQualitySupported.class))
  625. return PrintQualitySupported.getAssociatedAttributeArray(attr);
  626. if (suppCategory.equals(CompressionSupported.class))
  627. return CompressionSupported.getAssociatedAttributeArray(attr);
  628. // Special handling as it might also be in range of integers
  629. if (suppCategory.equals(NumberUpSupported.class))
  630. {
  631. if (attr.size() == 1) // number-up maybe in rangeofintegers
  632. return attr.iterator().next();
  633. int[][] members = new int[attr.size()][2];
  634. Iterator<Attribute> it = attr.iterator();
  635. for (int j = 0; j < attr.size(); j++)
  636. {
  637. int value = ((NumberUpSupported) it.next()).getMembers()[0][0];
  638. members[j] = new int[] { value, value };
  639. }
  640. NumberUpSupported supported = new NumberUpSupported(members);
  641. return supported;
  642. }
  643. return null;
  644. }
  645. /**
  646. * @see javax.print.PrintService#getSupportedDocFlavors()
  647. */
  648. public DocFlavor[] getSupportedDocFlavors()
  649. {
  650. return flavors.toArray(new DocFlavor[flavors.size()]);
  651. }
  652. /**
  653. * This is done by a validate-job operation and actually implemented in
  654. * this generic IPP reference implementation. Subclasses which does
  655. * not correctly support Validate-Job operation might want to override this.
  656. *
  657. * @see PrintService#getUnsupportedAttributes(DocFlavor, AttributeSet)
  658. */
  659. public AttributeSet getUnsupportedAttributes(DocFlavor flavor,
  660. AttributeSet attributes)
  661. {
  662. if (flavor != null && !isDocFlavorSupported(flavor))
  663. throw new IllegalArgumentException("flavor is not supported");
  664. IppResponse response = null;
  665. try
  666. {
  667. IppRequest request = new IppRequest(printerUri.getURI(), user, passwd);
  668. short operationId = (short) OperationsSupported.VALIDATE_JOB.getValue();
  669. request.setOperationID(operationId);
  670. request.setOperationAttributeDefaults();
  671. request.addOperationAttribute(printerUri);
  672. request.addOperationAttribute(Fidelity.FIDELITY_TRUE);
  673. if (attributes != null && attributes.size() > 0)
  674. {
  675. request.addAndFilterJobOperationAttributes(attributes);
  676. request.addAndFilterJobTemplateAttributes(attributes);
  677. }
  678. if (flavor != null)
  679. {
  680. DocumentFormat f = DocumentFormat.createDocumentFormat(flavor);
  681. request.addOperationAttribute(f);
  682. }
  683. response = request.send();
  684. int status = response.getStatusCode();
  685. if (! (status == IppStatusCode.SUCCESSFUL_OK
  686. || status == IppStatusCode.SUCCESSFUL_OK_IGNORED_OR_SUBSTITUED_ATTRIBUTES
  687. || status == IppStatusCode.SUCCESSFUL_OK_CONFLICTING_ATTRIBUTES) )
  688. {
  689. logger.log(Component.IPP, "Statuscode not OK - got:" + status);
  690. }
  691. }
  692. catch (IOException e)
  693. {
  694. // method cannot throw exception - just log
  695. logger.log(Component.IPP, "IOException", e);
  696. }
  697. catch (IppException e)
  698. {
  699. // method cannot throw exception - just log
  700. logger.log(Component.IPP, "IPPException", e);
  701. }
  702. // Validate Jobs returns only Unsupported and Operation
  703. List<Map<Class<? extends Attribute>, Set<Attribute>>> unsupportedMaps =
  704. response.getUnsupportedAttributes();
  705. if (unsupportedMaps.size() == 0)
  706. return null;
  707. Map<Class<? extends Attribute>, Set<Attribute>> unsupportedAttr = unsupportedMaps.get(0);
  708. if (unsupportedAttr.size() == 0)
  709. return null;
  710. // Convert the return map with unsupported attributes
  711. // into an AttribueSet instance
  712. HashAttributeSet set = new HashAttributeSet();
  713. for (Set<Attribute> unsupported : unsupportedAttr.values())
  714. {
  715. for (Attribute att : unsupported)
  716. set.add(att);
  717. }
  718. return set;
  719. }
  720. /**
  721. * @see PrintService#isAttributeCategorySupported(Class)
  722. */
  723. public boolean isAttributeCategorySupported(Class<? extends Attribute> category)
  724. {
  725. if (category == null)
  726. throw new NullPointerException("category may not be null");
  727. if (! Attribute.class.isAssignableFrom(category))
  728. throw new IllegalArgumentException("category must be of type Attribute");
  729. return Arrays.asList(getSupportedAttributeCategories()).contains(category);
  730. }
  731. /**
  732. * @see PrintService#isAttributeValueSupported(Attribute, DocFlavor, AttributeSet)
  733. */
  734. public boolean isAttributeValueSupported(Attribute attrval, DocFlavor flavor,
  735. AttributeSet attributes)
  736. {
  737. // just redirect to getSupportedAttributeValues
  738. Object values = getSupportedAttributeValues(attrval.getCategory(),
  739. flavor, attributes);
  740. // null means none supported
  741. if (values == null)
  742. return false;
  743. // object may be an array
  744. if (values.getClass().isArray())
  745. return Arrays.asList((Object[]) values).contains(attrval);
  746. // may be a single instance of the category (value is irrelevant)
  747. if (values.getClass().equals(attrval.getCategory()))
  748. return true;
  749. // a single instance of another class to give the bounds
  750. // copies
  751. if (values.getClass().equals(CopiesSupported.class))
  752. return ((CopiesSupported) values).contains((IntegerSyntax) attrval);
  753. // number up
  754. if (values.getClass().equals(NumberUpSupported.class))
  755. return ((NumberUpSupported) values).contains((IntegerSyntax) attrval);
  756. // job priority
  757. if (values.getClass().equals(JobPrioritySupported.class))
  758. {
  759. JobPriority priority = (JobPriority) attrval;
  760. JobPrioritySupported maxSupported = (JobPrioritySupported) values;
  761. if (priority.getValue() < maxSupported.getValue())
  762. return true;
  763. }
  764. // I am unsure if these might also show up - not yet found a printer where
  765. // Suns implementation supports them:
  766. // JobImpressionsSupported, JobKOctetsSupported, JobMediaSheetsSupported
  767. return false;
  768. }
  769. /**
  770. * @see javax.print.PrintService#isDocFlavorSupported(DocFlavor)
  771. */
  772. public boolean isDocFlavorSupported(DocFlavor flavor)
  773. {
  774. if (flavor == null)
  775. throw new NullPointerException("DocFlavor may not be null.");
  776. return flavors.contains(flavor);
  777. }
  778. /**
  779. * @see PrintService#addPrintServiceAttributeListener(PrintServiceAttributeListener)
  780. */
  781. public void addPrintServiceAttributeListener(
  782. PrintServiceAttributeListener listener)
  783. {
  784. printServiceAttributeListener.add(listener);
  785. }
  786. /**
  787. * @see PrintService#removePrintServiceAttributeListener(PrintServiceAttributeListener)
  788. */
  789. public void removePrintServiceAttributeListener(
  790. PrintServiceAttributeListener listener)
  791. {
  792. printServiceAttributeListener.remove(listener);
  793. }
  794. /**
  795. * Returns "IppPrinter: " + <code>getName()</code>
  796. * @return The string representation.
  797. */
  798. public String toString()
  799. {
  800. return "IppPrinter: " + getName();
  801. }
  802. /**
  803. * Returns the printer-uri of this print service.
  804. *
  805. * @return The printer-uri attribute.
  806. */
  807. public PrinterURI getPrinterURI()
  808. {
  809. return printerUri;
  810. }
  811. }