source: trunk/docx4j/src/main/java/org/docx4j/openpackaging/parts/DocPropsCustomPart.java @ 1490

Revision 1490, 9.4 KB checked in by jharrop, 13 months ago (diff)

Set JAXB Context.

  • Property svn:eol-style set to native
Line 
1/*
2 *  Copyright 2007-2008, Plutext Pty Ltd.
3 *   
4 *  This file is part of docx4j.
5
6    docx4j is licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8
9    You may obtain a copy of the License at
10
11        http://www.apache.org/licenses/LICENSE-2.0
12
13    Unless required by applicable law or agreed to in writing, software
14    distributed under the License is distributed on an "AS IS" BASIS,
15    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16    See the License for the specific language governing permissions and
17    limitations under the License.
18
19 */
20
21package org.docx4j.openpackaging.parts;
22
23
24import javax.xml.bind.JAXBException;
25import javax.xml.bind.Unmarshaller;
26
27import org.apache.log4j.Logger;
28import org.docx4j.docProps.custom.Properties;
29import org.docx4j.jaxb.Context;
30import org.docx4j.openpackaging.exceptions.InvalidFormatException;
31import org.docx4j.openpackaging.parts.relationships.Namespaces;
32
33
34
35/**
36 * @author jharrop
37 *
38 */
39public class DocPropsCustomPart extends JaxbXmlPart<Properties> {
40       
41        /* Specification > Shared ML > Metadata > Custom Properties
42         *
43         */
44               
45       
46        /*
47                <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
48                <Properties
49                        xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
50                        xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
51                        <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="Grouping">
52                                <vt:lpwstr>p</vt:lpwstr>
53                        </property>
54                        <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="CheckinComments">
55                                <vt:lpwstr>true</vt:lpwstr>
56                        </property>
57                </Properties>
58               
59        */
60       
61       
62       
63        private static Logger log = Logger.getLogger(DocPropsCustomPart.class);
64       
65       
66        /* fmtid (Format ID) Uniquely relates a custom property with an OLE property.
67         *
68         * The value of this attribute is a Globally Unique Identifier in the form of
69         * {HHHHHHHH-HHHH-HHHH-HHHH-HHHHHHHH} where each H is a hexidecimal.
70         *
71         *
72         */
73        public static final String fmtidValLpwstr = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
74       
75         /**
76         * @throws InvalidFormatException
77         */
78        public DocPropsCustomPart(PartName partName) throws InvalidFormatException {
79                super(partName);
80                init();
81        }
82
83        public DocPropsCustomPart() throws InvalidFormatException {
84                super(new PartName("/docProps/custom.xml"));
85                init();
86        }
87       
88        public void init() {
89               
90                jc = Context.jcDocPropsCustom;
91               
92                // Used if this Part is added to [Content_Types].xml
93                setContentType(new  org.docx4j.openpackaging.contenttype.ContentType( 
94                                org.docx4j.openpackaging.contenttype.ContentTypes.OFFICEDOCUMENT_CUSTOMPROPERTIES));
95
96                // Used when this Part is added to a rels
97                setRelationshipType(Namespaces.PROPERTIES_CUSTOM);
98
99        }
100
101    /**
102     * Unmarshal XML data from the specified InputStream and return the
103     * resulting content tree.  Validation event location information may
104     * be incomplete when using this form of the unmarshal API.
105     *
106     * <p>
107     * Implements <a href="#unmarshalGlobal">Unmarshal Global Root Element</a>.
108     *
109     * @param is the InputStream to unmarshal XML data from
110     * @return the newly created root object of the java content tree
111     *
112     * @throws JAXBException
113     *     If any unexpected errors occur while unmarshalling
114     */
115        @Override
116    public Properties unmarshal( java.io.InputStream is ) throws JAXBException {
117       
118                try {
119                       
120//                      if (jc==null) {
121//                              setJAXBContext(Context.jc);                             
122//                      }
123                                   
124                        setJAXBContext(org.docx4j.jaxb.Context.jcDocPropsCustom);
125                        Unmarshaller u = jc.createUnmarshaller();
126                       
127                        //u.setSchema(org.docx4j.jaxb.WmlSchema.schema);
128                        u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());
129
130                        log.info("unmarshalling " + this.getClass().getName() );                                                                       
131                                               
132                        jaxbElement = (Properties) u.unmarshal( is );
133                       
134                       
135                        log.info("\n\n" + this.getClass().getName() + " unmarshalled \n\n" );                                                                   
136
137                } catch (Exception e ) {
138                        e.printStackTrace();
139                }
140       
141                return jaxbElement;
142       
143    }
144   
145    public String getProperty(String propName) {
146       
147                // NB, at present this assumes the property is a string
148
149        org.docx4j.docProps.custom.Properties customProps = (org.docx4j.docProps.custom.Properties)getJaxbElement();
150                for (org.docx4j.docProps.custom.Properties.Property prop: customProps.getProperty() ) {
151                       
152                        log.info(prop.getName());
153                       
154                        if (prop.getName().equals(propName)) {
155                                log.info("GOT IT! returning " + prop.getLpwstr());
156                                return prop.getLpwstr();
157                        }
158                       
159                }
160                return null;           
161    }
162   
163    public void setProperty(String propName, String propValue) {
164       
165                // NB, at present this assumes the property is a string
166       
167        // does it exist already?
168        org.docx4j.docProps.custom.Properties.Property newProp = null;
169        org.docx4j.docProps.custom.Properties customProps = (org.docx4j.docProps.custom.Properties)getJaxbElement();
170                for (org.docx4j.docProps.custom.Properties.Property prop: customProps.getProperty() ) {
171                        if (prop.getName().equals(propName)) {
172                                log.warn("Replacing existing property: " + propName);
173                                newProp = prop;
174                                if (!newProp.getFmtid().equals(fmtidValLpwstr )) {
175                                        log.warn("Wrong fmtid?  This might not work...");
176                                }
177                                break;
178                        }                       
179                }
180       
181                // If not, let's add one.
182                if (newProp==null) {
183                        org.docx4j.docProps.custom.ObjectFactory factory = new org.docx4j.docProps.custom.ObjectFactory();
184                        newProp = factory.createPropertiesProperty();
185
186                        newProp.setName(propName);
187                        newProp.setFmtid(fmtidValLpwstr ); // Magic string
188                        newProp.setPid( getNextPid() ); 
189                       
190                        customProps.getProperty().add(newProp);
191                }
192               
193                // set the value
194                newProp.setLpwstr(propValue);
195                       
196    }
197   
198    /**
199     * Find the first available Pid
200     * 
201     * @return
202     */
203    public int getNextPid() {
204       
205        int highestSeen = 1; // Lowest number Word 2007 seems to like is 2 (!)
206       
207        org.docx4j.docProps.custom.Properties customProps = (org.docx4j.docProps.custom.Properties)getJaxbElement();
208                for (org.docx4j.docProps.custom.Properties.Property prop: customProps.getProperty() ) {                 
209                        if (prop.getPid()>highestSeen) {
210                                highestSeen =prop.getPid();                             
211                        }
212                }
213                log.debug("Returning " +  highestSeen+1);
214                return highestSeen+1;           
215    }
216       
217               
218//      /* Create a Java object tree from the XML document
219//       */
220//      public void unmarshall(Document doc) {
221//             
222//              String name;
223//              String value;
224//             
225//              try {
226//                      //debugPrint(doc);
227//                  Element root = doc.getRootElement();
228//                  Iterator elementIterator = root.elementIterator();
229//                  while(elementIterator.hasNext()){
230//                    Element element = (Element)elementIterator.next();
231//                   
232//                        if (element.getName()=="property" ) {
233//                               
234////                                    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="Grouping">
235////                                            <vt:lpwstr>p</vt:lpwstr>
236////                                    </property>
237//                               
238//                                name = element.attributeValue("name");
239//                               
240//                                if (element.element("lpwstr")!=null ) {
241//                                        value = element.element("lpwstr").getText();
242//                                        setProperty(name, value);                                       
243//                                        log.info("Registering property " + name + "=" + value);
244//                                } else {
245//                                              // TODO - handle
246//                                        log.warn("Handle " + name );
247//                                        debugPrint(doc);
248//                                       
249//                                }
250//                        } else {
251//                            log.warn("Encountered unexpected element '" + element.getName() + "'");
252//                        }
253//                  }
254//              } catch (Exception e ) {
255//                      e.printStackTrace();
256//              }
257//             
258//      }
259//     
260//
261//             
262//     
263//      /* Create an XML document from the Java object tree
264//       * 
265//       */
266//      private Document marshall() {
267//
268////            <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
269////            <Properties
270////                    xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
271////                    xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
272////                    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="Grouping">
273////                            <vt:lpwstr>p</vt:lpwstr>
274////                    </property>
275////                    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="CheckinComments">
276////                            <vt:lpwstr>true</vt:lpwstr>
277////                    </property>
278////            </Properties>
279//
280//              Document doc = DocumentHelper.createDocument();
281//
282//              // Note carefully how namespaces are handled here.
283//              // It seems we have to be syntactically identical to how
284//              // Word does it - semantic equivalence is not enough!
285//             
286//              Namespace docPropsVTypes = new Namespace("vt",
287//                              "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
288//             
289//              Element elDocument = doc.addElement("Properties",
290//                              "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
291//              elDocument.addNamespace("vt",
292//                              "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
293//
294//              Integer pid = 2; // NB @pid="1" will cause Word to regard the document as corrupt.
295//              Iterator i = properties.entrySet().iterator();
296//              while (i.hasNext()) {
297//                      Map.Entry e = (Map.Entry)i.next();     
298//                      Element property = elDocument.addElement("property",
299//                      "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
300//                      property.addAttribute( "fmtid", fmtidVal);
301//                      property.addAttribute( "pid", pid.toString() );
302//                      property.addAttribute( "name", (String)e.getKey() );
303//                      Element lpwstr = new DefaultElement(new QName("lpwstr", docPropsVTypes));
304//                      lpwstr.setText( (String)e.getValue() );
305//                      property.add(lpwstr);
306//                      pid++;
307//              }
308//              return doc;
309//      }
310                       
311       
312}
313
314       
Note: See TracBrowser for help on using the repository browser.