You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Design.java 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.ui.declarative;
  17. import java.beans.IntrospectionException;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.io.Serializable;
  22. import java.lang.annotation.Annotation;
  23. import java.util.Collection;
  24. import java.util.Locale;
  25. import java.util.logging.Level;
  26. import java.util.logging.Logger;
  27. import org.jsoup.Jsoup;
  28. import org.jsoup.nodes.Document;
  29. import org.jsoup.nodes.Document.OutputSettings.Syntax;
  30. import org.jsoup.nodes.DocumentType;
  31. import org.jsoup.nodes.Element;
  32. import org.jsoup.nodes.Node;
  33. import org.jsoup.parser.Parser;
  34. import org.jsoup.select.Elements;
  35. import com.vaadin.annotations.DesignRoot;
  36. import com.vaadin.shared.util.SharedUtil;
  37. import com.vaadin.ui.Component;
  38. import com.vaadin.ui.declarative.DesignContext.ComponentCreatedEvent;
  39. import com.vaadin.ui.declarative.DesignContext.ComponentCreationListener;
  40. /**
  41. * Design is used for reading a component hierarchy from an html string or input
  42. * stream and, conversely, for writing an html representation corresponding to a
  43. * given component hierarchy.
  44. *
  45. * <p>
  46. * In html form a valid nonempty component hierarchy contains a single root
  47. * element located under the &lt;body&gt; tag. A hierarchy of components is
  48. * achieved by nesting other elements under the root element. An empty component
  49. * hierarchy is represented as no elements under the &lt;body&gt; tag.
  50. *
  51. * <p>
  52. * For writing a component hierarchy the root element is specified as a
  53. * Component parameter or as a DesignContext object containing the root
  54. * Component. An empty hierarchy can be written by giving a null root Component.
  55. *
  56. * @since 7.4
  57. * @author Vaadin Ltd
  58. */
  59. public class Design implements Serializable {
  60. private static final String UTF8 = "UTF-8";
  61. /**
  62. * Callback for creating instances of a given component class when reading
  63. * designs. The default implementation, {@link DefaultComponentFactory} will
  64. * use <code>Class.forName(className).newInstance()</code>, which might not
  65. * be suitable e.g. in an OSGi environment or if the Component instances
  66. * should be created as managed CDI beans.
  67. * <p>
  68. * Use {@link Design#setComponentFactory(ComponentFactory)} to configure
  69. * Vaadin to use a custom component factory.
  70. *
  71. * @since 7.4.1
  72. */
  73. public interface ComponentFactory extends Serializable {
  74. /**
  75. * Creates a component based on the fully qualified name derived from
  76. * the tag name in the design.
  77. *
  78. * @param fullyQualifiedClassName
  79. * the fully qualified name of the component to create
  80. * @param context
  81. * the design context for which the component is created
  82. *
  83. * @return a newly created component
  84. */
  85. public Component createComponent(String fullyQualifiedClassName,
  86. DesignContext context);
  87. }
  88. /**
  89. * Delegate for handling the mapping between tag names and component
  90. * instances.
  91. * <p>
  92. * Use {@link Design#setComponentMapper(ComponentMapper)} to configure
  93. * Vaadin to use a custom component mapper.
  94. *
  95. * @since 7.5.0
  96. * @author Vaadin Ltd
  97. */
  98. public interface ComponentMapper extends Serializable {
  99. /**
  100. * Resolves and creates a component using the provided component factory
  101. * based on a tag name.
  102. * <p>
  103. * This method should be in sync with
  104. * {@link #componentToTag(Component, DesignContext)} so that the
  105. * resolved tag for a created component is the same as the tag for which
  106. * the component was created.
  107. *
  108. * @param tag
  109. * the tag name to create a component for
  110. * @param componentFactory
  111. * the component factory that actually creates a component
  112. * based on a fully qualified class name
  113. * @param context
  114. * the design context for which the component is created
  115. * @return a newly created component
  116. */
  117. public Component tagToComponent(String tag,
  118. ComponentFactory componentFactory, DesignContext context);
  119. /**
  120. * Resolves a tag name from a component.
  121. *
  122. * @param component
  123. * the component to get a tag name for
  124. * @param context
  125. * the design context for which the tag name is needed
  126. * @return the tag name corresponding to the component
  127. */
  128. public String componentToTag(Component component, DesignContext context);
  129. }
  130. /**
  131. * Default implementation of {@link ComponentFactory}, using
  132. * <code>Class.forName(className).newInstance()</code> for finding the
  133. * component class and creating a component instance.
  134. *
  135. * @since 7.4.1
  136. */
  137. public static class DefaultComponentFactory implements ComponentFactory {
  138. @Override
  139. public Component createComponent(String fullyQualifiedClassName,
  140. DesignContext context) {
  141. Class<? extends Component> componentClass;
  142. try {
  143. componentClass = resolveComponentClass(fullyQualifiedClassName,
  144. context);
  145. } catch (DesignException e) {
  146. // Try with an inner class.
  147. int lastDot = fullyQualifiedClassName.lastIndexOf('.');
  148. if (lastDot != -1) {
  149. String qualifiedInnerClassName = fullyQualifiedClassName
  150. .substring(0, lastDot)
  151. + "$"
  152. + fullyQualifiedClassName.substring(lastDot + 1);
  153. return createComponent(qualifiedInnerClassName, context);
  154. } else {
  155. throw e;
  156. }
  157. }
  158. assert Component.class.isAssignableFrom(componentClass) : "resolveComponentClass returned "
  159. + componentClass + " which is not a Vaadin Component class";
  160. try {
  161. return componentClass.newInstance();
  162. } catch (Exception e) {
  163. throw new DesignException("Could not create component "
  164. + fullyQualifiedClassName, e);
  165. }
  166. }
  167. /**
  168. * Resolves a component class based on the fully qualified name of the
  169. * class.
  170. *
  171. * @param qualifiedClassName
  172. * the fully qualified name of the resolved class
  173. * @param context
  174. * the design context for which the class is resolved
  175. * @return a component class object representing the provided class name
  176. */
  177. protected Class<? extends Component> resolveComponentClass(
  178. String qualifiedClassName, DesignContext context) {
  179. try {
  180. Class<?> componentClass = Class.forName(qualifiedClassName);
  181. return componentClass.asSubclass(Component.class);
  182. } catch (ClassNotFoundException e) {
  183. throw new DesignException(
  184. "Unable to load component for design", e);
  185. }
  186. }
  187. }
  188. /**
  189. * Default implementation of {@link ComponentMapper},
  190. *
  191. * @since 7.5.0
  192. */
  193. public static class DefaultComponentMapper implements ComponentMapper {
  194. @Override
  195. public Component tagToComponent(String tagName,
  196. ComponentFactory componentFactory, DesignContext context) {
  197. // Extract the package and class names.
  198. // Otherwise, get the full class name using the prefix to package
  199. // mapping. Example: "vaadin-vertical-layout" ->
  200. // "com.vaadin.ui.VerticalLayout"
  201. String[] parts = tagName.split("-", 2);
  202. if (parts.length < 2) {
  203. throw new DesignException("The tagname '" + tagName
  204. + "' is invalid: missing prefix.");
  205. }
  206. String prefixName = parts[0];
  207. String packageName = context.getPackage(prefixName);
  208. if (packageName == null) {
  209. throw new DesignException("Unknown tag: " + tagName);
  210. }
  211. String[] classNameParts = parts[1].split("-");
  212. String className = "";
  213. for (String classNamePart : classNameParts) {
  214. // Split will ignore trailing and multiple dashes but that
  215. // should be
  216. // ok
  217. // <vaadin-button--> will be resolved to <vaadin-button>
  218. // <vaadin--button> will be resolved to <vaadin-button>
  219. className += SharedUtil.capitalize(classNamePart);
  220. }
  221. String qualifiedClassName = packageName + "." + className;
  222. Component component = componentFactory.createComponent(
  223. qualifiedClassName, context);
  224. if (component == null) {
  225. throw new DesignException("Got unexpected null component from "
  226. + componentFactory.getClass().getName() + " for class "
  227. + qualifiedClassName);
  228. }
  229. return component;
  230. }
  231. @Override
  232. public String componentToTag(Component component, DesignContext context) {
  233. Class<?> componentClass = component.getClass();
  234. String packageName = getPackageName(componentClass);
  235. String prefix = context.getPackagePrefix(packageName);
  236. if (prefix == null) {
  237. prefix = packageName.replace('.', '_').toLowerCase(
  238. Locale.ENGLISH);
  239. context.addPackagePrefix(prefix, packageName);
  240. }
  241. prefix = prefix + "-";
  242. String className = classNameToElementName(componentClass
  243. .getSimpleName());
  244. String tagName = prefix + className;
  245. return tagName;
  246. }
  247. private String getPackageName(Class<?> componentClass) {
  248. if (componentClass.isMemberClass()) {
  249. Class<?> enclosingClass = componentClass.getEnclosingClass();
  250. return getPackageName(enclosingClass) + "."
  251. + enclosingClass.getSimpleName();
  252. } else {
  253. return componentClass.getPackage().getName();
  254. }
  255. }
  256. /**
  257. * Creates the name of the html tag corresponding to the given class
  258. * name. The name is derived by converting each uppercase letter to
  259. * lowercase and inserting a dash before the letter. No dash is inserted
  260. * before the first letter of the class name.
  261. *
  262. * @param className
  263. * the name of the class without a package name
  264. * @return the html tag name corresponding to className
  265. */
  266. private String classNameToElementName(String className) {
  267. StringBuilder result = new StringBuilder();
  268. for (int i = 0; i < className.length(); i++) {
  269. Character c = className.charAt(i);
  270. if (Character.isUpperCase(c)) {
  271. if (i > 0) {
  272. result.append("-");
  273. }
  274. result.append(Character.toLowerCase(c));
  275. } else {
  276. result.append(c);
  277. }
  278. }
  279. return result.toString();
  280. }
  281. }
  282. private static volatile ComponentFactory componentFactory = new DefaultComponentFactory();
  283. private static volatile ComponentMapper componentMapper = new DefaultComponentMapper();
  284. /**
  285. * Sets the component factory that is used for creating component instances
  286. * based on fully qualified class names derived from a design file.
  287. * <p>
  288. * Please note that this setting is global, so care should be taken to avoid
  289. * conflicting changes.
  290. *
  291. * @param componentFactory
  292. * the component factory to set; not <code>null</code>
  293. *
  294. * @since 7.4.1
  295. */
  296. public static void setComponentFactory(ComponentFactory componentFactory) {
  297. if (componentFactory == null) {
  298. throw new IllegalArgumentException(
  299. "Cannot set null component factory");
  300. }
  301. Design.componentFactory = componentFactory;
  302. }
  303. /**
  304. * Gets the currently used component factory.
  305. *
  306. * @see #setComponentFactory(ComponentFactory)
  307. *
  308. * @return the component factory
  309. *
  310. * @since 7.4.1
  311. */
  312. public static ComponentFactory getComponentFactory() {
  313. return componentFactory;
  314. }
  315. /**
  316. * Sets the component mapper that is used for resolving between tag names
  317. * and component instances.
  318. * <p>
  319. * Please note that this setting is global, so care should be taken to avoid
  320. * conflicting changes.
  321. *
  322. * @param componentMapper
  323. * the component mapper to set; not <code>null</code>
  324. *
  325. * @since 7.5.0
  326. */
  327. public static void setComponentMapper(ComponentMapper componentMapper) {
  328. if (componentMapper == null) {
  329. throw new IllegalArgumentException(
  330. "Cannot set null component mapper");
  331. }
  332. Design.componentMapper = componentMapper;
  333. }
  334. /**
  335. * Gets the currently used component mapper.
  336. *
  337. * @see #setComponentMapper(ComponentMapper)
  338. *
  339. * @return the component mapper
  340. *
  341. * @since 7.5.0
  342. */
  343. public static ComponentMapper getComponentMapper() {
  344. return componentMapper;
  345. }
  346. /**
  347. * Parses the given input stream into a jsoup document
  348. *
  349. * @param html
  350. * the stream containing the design
  351. * @return the parsed jsoup document
  352. * @throws IOException
  353. */
  354. private static Document parse(InputStream html) {
  355. try {
  356. Document doc = Jsoup.parse(html, UTF8, "", Parser.htmlParser());
  357. return doc;
  358. } catch (IOException e) {
  359. throw new DesignException("The html document cannot be parsed.");
  360. }
  361. }
  362. /**
  363. * Constructs a component hierarchy from the design specified as an html
  364. * tree.
  365. *
  366. * <p>
  367. * If a component root is given, the component instances created during
  368. * reading the design are assigned to its member fields based on their id,
  369. * local id, and caption
  370. *
  371. * @param doc
  372. * the html tree
  373. * @param componentRoot
  374. * optional component root instance. The type must match the type
  375. * of the root element in the design. Any member fields whose
  376. * type is assignable from {@link Component} are bound to fields
  377. * in the design based on id/local id/caption
  378. */
  379. private static DesignContext designToComponentTree(Document doc,
  380. Component componentRoot) {
  381. if (componentRoot == null) {
  382. return designToComponentTree(doc, null, null);
  383. } else {
  384. return designToComponentTree(doc, componentRoot,
  385. componentRoot.getClass());
  386. }
  387. }
  388. /**
  389. * Constructs a component hierarchy from the design specified as an html
  390. * tree.
  391. *
  392. * <p>
  393. * If a component root is given, the component instances created during
  394. * reading the design are assigned to its member fields based on their id,
  395. * local id, and caption
  396. *
  397. * @param doc
  398. * the html tree
  399. * @param componentRoot
  400. * optional component root instance. The type must match the type
  401. * of the root element in the design.
  402. * @param classWithFields
  403. * a class (componentRoot class or a super class) with some
  404. * member fields. The member fields whose type is assignable from
  405. * {@link Component} are bound to fields in the design based on
  406. * id/local id/caption
  407. */
  408. private static DesignContext designToComponentTree(Document doc,
  409. Component componentRoot, Class<?> classWithFields) {
  410. DesignContext designContext = new DesignContext(doc);
  411. designContext.readPackageMappings(doc);
  412. // No special handling for a document without a body element - should be
  413. // taken care of by jsoup.
  414. Element root = doc.body();
  415. Elements children = root.children();
  416. if (children.size() > 1) {
  417. throw new DesignException(
  418. "The first level of a component hierarchy should contain at most one root component, but found "
  419. + children.size() + ".");
  420. }
  421. Element element = children.size() == 0 ? null : children.first();
  422. if (componentRoot != null) {
  423. if (element == null) {
  424. throw new DesignException(
  425. "The root element cannot be null when the specified root Component is"
  426. + " not null.");
  427. }
  428. // user has specified root instance that may have member fields that
  429. // should be bound
  430. final FieldBinder binder;
  431. try {
  432. binder = new FieldBinder(componentRoot, classWithFields);
  433. } catch (IntrospectionException e) {
  434. throw new DesignException(
  435. "Could not bind fields of the root component", e);
  436. }
  437. // create listener for component creations that binds the created
  438. // components to the componentRoot instance fields
  439. ComponentCreationListener creationListener = new ComponentCreationListener() {
  440. @Override
  441. public void componentCreated(ComponentCreatedEvent event) {
  442. binder.bindField(event.getComponent(), event.getLocalId());
  443. }
  444. };
  445. designContext.addComponentCreationListener(creationListener);
  446. // create subtree
  447. designContext.readDesign(element, componentRoot);
  448. // make sure that all the member fields are bound
  449. Collection<String> unboundFields = binder.getUnboundFields();
  450. if (!unboundFields.isEmpty()) {
  451. throw new DesignException(
  452. "Found unbound fields from component root "
  453. + unboundFields);
  454. }
  455. // no need to listen anymore
  456. designContext.removeComponentCreationListener(creationListener);
  457. } else {
  458. // createChild creates the entire component hierarchy
  459. componentRoot = element == null ? null : designContext
  460. .readDesign(element);
  461. }
  462. designContext.setRootComponent(componentRoot);
  463. return designContext;
  464. }
  465. /**
  466. * Generates an html tree representation of the component hierarchy having
  467. * the root designContext.getRootComponent(). The hierarchy is stored under
  468. * &lt;body&gt; in the tree. The generated tree represents a valid html
  469. * document.
  470. *
  471. *
  472. * @param designContext
  473. * a DesignContext object specifying the root component
  474. * (designContext.getRootComponent()) of the hierarchy
  475. * @return an html tree representation of the component hierarchy
  476. */
  477. private static Document createHtml(DesignContext designContext) {
  478. // Create the html tree skeleton.
  479. Document doc = new Document("");
  480. DocumentType docType = new DocumentType("html", "", "", "");
  481. doc.appendChild(docType);
  482. Element html = doc.createElement("html");
  483. doc.appendChild(html);
  484. html.appendChild(doc.createElement("head"));
  485. Element body = doc.createElement("body");
  486. html.appendChild(body);
  487. // Append the design under <body> in the html tree. createNode
  488. // creates the entire component hierarchy rooted at the
  489. // given root node.
  490. Component root = designContext.getRootComponent();
  491. if (root != null) {
  492. Node rootNode = designContext.createElement(root);
  493. body.appendChild(rootNode);
  494. }
  495. designContext.writePackageMappings(doc);
  496. return doc;
  497. }
  498. /**
  499. * Loads a design for the given root component.
  500. * <p>
  501. * This methods assumes that the component class (or a super class) has been
  502. * marked with an {@link DesignRoot} annotation and will either use the
  503. * value from the annotation to locate the design file, or will fall back to
  504. * using a design with the same same as the annotated class file (with an
  505. * .html extension)
  506. * <p>
  507. * Any {@link Component} type fields in the root component which are not
  508. * assigned (i.e. are null) are mapped to corresponding components in the
  509. * design. Matching is done based on field name in the component class and
  510. * id/local id/caption in the design file.
  511. * <p>
  512. * The type of the root component must match the root element in the design
  513. *
  514. * @param rootComponent
  515. * The root component of the layout
  516. * @return The design context used in the load operation
  517. * @throws DesignException
  518. * If the design could not be loaded
  519. */
  520. public static DesignContext read(Component rootComponent)
  521. throws DesignException {
  522. // Try to find an @DesignRoot annotation on the class or any parent
  523. // class
  524. Class<? extends Component> annotatedClass = findClassWithAnnotation(
  525. rootComponent.getClass(), DesignRoot.class);
  526. if (annotatedClass == null) {
  527. throw new IllegalArgumentException(
  528. "The class "
  529. + rootComponent.getClass().getName()
  530. + " or any of its superclasses do not have an @DesignRoot annotation");
  531. }
  532. DesignRoot designAnnotation = annotatedClass
  533. .getAnnotation(DesignRoot.class);
  534. String filename = designAnnotation.value();
  535. if (filename.equals("")) {
  536. // No value, assume the html file is named as the class
  537. filename = annotatedClass.getSimpleName() + ".html";
  538. }
  539. InputStream stream = annotatedClass.getResourceAsStream(filename);
  540. if (stream == null) {
  541. throw new DesignException("Unable to find design file " + filename
  542. + " in " + annotatedClass.getPackage().getName());
  543. }
  544. try {
  545. Document doc = parse(stream);
  546. DesignContext context = designToComponentTree(doc, rootComponent,
  547. annotatedClass);
  548. return context;
  549. } finally {
  550. try {
  551. stream.close();
  552. } catch (IOException e) {
  553. getLogger().log(Level.FINE, "Error closing design stream", e);
  554. }
  555. }
  556. }
  557. private static Logger getLogger() {
  558. return Logger.getLogger(Design.class.getName());
  559. }
  560. /**
  561. * Find the first class with the given annotation, starting the search from
  562. * the given class and moving upwards in the class hierarchy.
  563. *
  564. * @param componentClass
  565. * the class to check
  566. * @param annotationClass
  567. * the annotation to look for
  568. * @return the first class with the given annotation or null if no class
  569. * with the annotation was found
  570. */
  571. private static Class<? extends Component> findClassWithAnnotation(
  572. Class<? extends Component> componentClass,
  573. Class<? extends Annotation> annotationClass) {
  574. if (componentClass == null) {
  575. return null;
  576. }
  577. if (componentClass.isAnnotationPresent(annotationClass)) {
  578. return componentClass;
  579. }
  580. Class<?> superClass = componentClass.getSuperclass();
  581. if (!Component.class.isAssignableFrom(superClass)) {
  582. return null;
  583. }
  584. return findClassWithAnnotation(superClass.asSubclass(Component.class),
  585. annotationClass);
  586. }
  587. /**
  588. * Loads a design from the given file name using the given root component.
  589. * <p>
  590. * Any {@link Component} type fields in the root component which are not
  591. * assigned (i.e. are null) are mapped to corresponding components in the
  592. * design. Matching is done based on field name in the component class and
  593. * id/local id/caption in the design file.
  594. * <p>
  595. * The type of the root component must match the root element in the design.
  596. *
  597. * @param filename
  598. * The file name to load. Loaded from the same package as the
  599. * root component
  600. * @param rootComponent
  601. * The root component of the layout
  602. * @return The design context used in the load operation
  603. * @throws DesignException
  604. * If the design could not be loaded
  605. */
  606. public static DesignContext read(String filename, Component rootComponent)
  607. throws DesignException {
  608. InputStream stream = rootComponent.getClass().getResourceAsStream(
  609. filename);
  610. if (stream == null) {
  611. throw new DesignException("File " + filename
  612. + " was not found in the package "
  613. + rootComponent.getClass().getPackage().getName());
  614. }
  615. try {
  616. return read(stream, rootComponent);
  617. } finally {
  618. try {
  619. stream.close();
  620. } catch (IOException e) {
  621. getLogger().log(Level.FINE, "Error closing design stream", e);
  622. }
  623. }
  624. }
  625. /**
  626. * Loads a design from the given stream using the given root component. If
  627. * rootComponent is null, the type of the root node is read from the design.
  628. * <p>
  629. * Any {@link Component} type fields in the root component which are not
  630. * assigned (i.e. are null) are mapped to corresponding components in the
  631. * design. Matching is done based on field name in the component class and
  632. * id/local id/caption in the design file.
  633. * <p>
  634. * If rootComponent is not null, its type must match the type of the root
  635. * element in the design
  636. *
  637. * @param stream
  638. * The stream to read the design from
  639. * @param rootComponent
  640. * The root component of the layout
  641. * @return The design context used in the load operation
  642. * @throws DesignException
  643. * If the design could not be loaded
  644. */
  645. public static DesignContext read(InputStream stream, Component rootComponent) {
  646. if (stream == null) {
  647. throw new DesignException("Stream cannot be null");
  648. }
  649. Document doc = parse(stream);
  650. DesignContext context = designToComponentTree(doc, rootComponent);
  651. return context;
  652. }
  653. /**
  654. * Loads a design from the given input stream
  655. *
  656. * @param design
  657. * The stream to read the design from
  658. * @return The root component of the design
  659. */
  660. public static Component read(InputStream design) {
  661. DesignContext context = read(design, null);
  662. return context.getRootComponent();
  663. }
  664. /**
  665. * Writes the given component tree in design format to the given output
  666. * stream.
  667. *
  668. * @param component
  669. * the root component of the component tree, null can be used for
  670. * generating an empty design
  671. * @param outputStream
  672. * the output stream to write the design to. The design is always
  673. * written as UTF-8
  674. * @throws IOException
  675. * if writing fails
  676. */
  677. public static void write(Component component, OutputStream outputStream)
  678. throws IOException {
  679. DesignContext dc = new DesignContext();
  680. dc.setRootComponent(component);
  681. write(dc, outputStream);
  682. }
  683. /**
  684. * Writes the component, given in the design context, in design format to
  685. * the given output stream. The design context is used for writing local ids
  686. * and other information not available in the component tree.
  687. *
  688. * @param designContext
  689. * The DesignContext object specifying the component hierarchy
  690. * and the local id values of the objects. If
  691. * designContext.getRootComponent() is null, an empty design will
  692. * be generated.
  693. * @param outputStream
  694. * the output stream to write the design to. The design is always
  695. * written as UTF-8
  696. * @throws IOException
  697. * if writing fails
  698. */
  699. public static void write(DesignContext designContext,
  700. OutputStream outputStream) throws IOException {
  701. Document doc = createHtml(designContext);
  702. write(doc, outputStream);
  703. }
  704. /**
  705. * Writes the given jsoup document to the output stream (in UTF-8)
  706. *
  707. * @param doc
  708. * the document to write
  709. * @param outputStream
  710. * the stream to write to
  711. * @throws IOException
  712. * if writing fails
  713. */
  714. private static void write(Document doc, OutputStream outputStream)
  715. throws IOException {
  716. doc.outputSettings().indentAmount(4);
  717. doc.outputSettings().syntax(Syntax.html);
  718. doc.outputSettings().prettyPrint(true);
  719. outputStream.write(doc.html().getBytes(UTF8));
  720. }
  721. }