This project has retired. For details please refer to its Attic page.
CreateDocumentDialog xref
View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.chemistry.opencmis.workbench;
20  
21  import java.awt.BorderLayout;
22  import java.awt.Cursor;
23  import java.awt.Dimension;
24  import java.awt.FlowLayout;
25  import java.awt.Frame;
26  import java.awt.event.ActionEvent;
27  import java.awt.event.ActionListener;
28  import java.awt.event.ItemEvent;
29  import java.awt.event.ItemListener;
30  import java.io.BufferedInputStream;
31  import java.io.File;
32  import java.io.InputStream;
33  import java.text.NumberFormat;
34  
35  import javax.swing.Box;
36  import javax.swing.BoxLayout;
37  import javax.swing.ButtonGroup;
38  import javax.swing.JButton;
39  import javax.swing.JCheckBox;
40  import javax.swing.JComboBox;
41  import javax.swing.JFileChooser;
42  import javax.swing.JFormattedTextField;
43  import javax.swing.JOptionPane;
44  import javax.swing.JPanel;
45  import javax.swing.JRadioButton;
46  import javax.swing.JTextField;
47  import javax.swing.SwingConstants;
48  import javax.swing.event.DocumentEvent;
49  import javax.swing.event.DocumentListener;
50  
51  import org.apache.chemistry.opencmis.client.api.Document;
52  import org.apache.chemistry.opencmis.client.api.ObjectId;
53  import org.apache.chemistry.opencmis.client.api.ObjectType;
54  import org.apache.chemistry.opencmis.commons.data.ContentStream;
55  import org.apache.chemistry.opencmis.commons.definitions.DocumentTypeDefinition;
56  import org.apache.chemistry.opencmis.commons.enums.BaseTypeId;
57  import org.apache.chemistry.opencmis.commons.enums.VersioningState;
58  import org.apache.chemistry.opencmis.commons.impl.IOUtils;
59  import org.apache.chemistry.opencmis.workbench.icons.NewDocumentIcon;
60  import org.apache.chemistry.opencmis.workbench.model.ClientModel;
61  import org.apache.chemistry.opencmis.workbench.model.ClientSession;
62  import org.apache.chemistry.opencmis.workbench.swing.CreateDialog;
63  
64  public class CreateDocumentDialog extends CreateDialog {
65  
66      private static final long serialVersionUID = 1L;
67  
68      private JRadioButton unfiledButton;
69      private JRadioButton currentPathButton;
70      private JTextField nameField;
71      private JComboBox<ObjectTypeItem> typeBox;
72      private JTextField filenameField;
73      private JFormattedTextField generateContentSizeField;
74      private JComboBox<String> generateContentUnitField;
75      private JRadioButton versioningStateNoneButton;
76      private JRadioButton versioningStateMajorButton;
77      private JRadioButton versioningStateMinorButton;
78      private JRadioButton versioningStateCheckedoutButton;
79  
80      private JCheckBox verifyAfterUploadButton;
81  
82      public CreateDocumentDialog(Frame owner, ClientModel model) {
83          this(owner, model, null);
84      }
85  
86      public CreateDocumentDialog(Frame owner, ClientModel model, File file) {
87          super(owner, "Create Document", model);
88          createGUI(file);
89      }
90  
91      private void createGUI(File file) {
92          final CreateDocumentDialog thisDialog = this;
93  
94          boolean hasCurrentFolder = getClientModel().getCurrentFolder() != null;
95  
96          unfiledButton = new JRadioButton("create unfiled");
97          unfiledButton.setSelected(!hasCurrentFolder);
98  
99          currentPathButton = new JRadioButton("create in the current folder: "
100                 + (hasCurrentFolder ? getClientModel().getCurrentFolder().getPath() : ""));
101         currentPathButton.setSelected(hasCurrentFolder);
102         currentPathButton.setEnabled(hasCurrentFolder);
103 
104         ButtonGroup filedGroup = new ButtonGroup();
105         filedGroup.add(unfiledButton);
106         filedGroup.add(currentPathButton);
107 
108         JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
109         buttonPanel.add(unfiledButton);
110         buttonPanel.add(currentPathButton);
111 
112         createRow("", buttonPanel, 0);
113 
114         nameField = new JTextField(60);
115         createRow("Name:", nameField, 1);
116 
117         ObjectTypeItem[] types = getTypes(BaseTypeId.CMIS_DOCUMENT.value());
118         if (types.length == 0) {
119             JOptionPane.showMessageDialog(this, "No creatable type!", "Creatable Types", JOptionPane.ERROR_MESSAGE);
120             thisDialog.dispose();
121             return;
122         }
123 
124         typeBox = new JComboBox<ObjectTypeItem>(types);
125         typeBox.setSelectedIndex(0);
126         typeBox.addItemListener(new ItemListener() {
127             @Override
128             public void itemStateChanged(ItemEvent e) {
129                 DocumentTypeDefinition type = (DocumentTypeDefinition) ((ObjectTypeItem) typeBox.getSelectedItem())
130                         .getObjectType();
131                 if (type.isVersionable()) {
132                     versioningStateMajorButton.setSelected(true);
133                 } else {
134                     versioningStateNoneButton.setSelected(true);
135                 }
136                 updateMandatoryOrOnCreateFields(type);
137             }
138         });
139 
140         ObjectTypeItem type = (ObjectTypeItem) typeBox.getSelectedItem();
141         updateMandatoryOrOnCreateFields(type.getObjectType());
142 
143         createRow("Type:", typeBox, 2);
144 
145         JPanel filePanel = new JPanel(new BorderLayout());
146 
147         filenameField = new JTextField(30);
148         filenameField.getDocument().addDocumentListener(new DocumentListener() {
149             @Override
150             public void removeUpdate(DocumentEvent e) {
151                 adjustGenerateContentComponents();
152             }
153 
154             @Override
155             public void insertUpdate(DocumentEvent e) {
156                 adjustGenerateContentComponents();
157             }
158 
159             @Override
160             public void changedUpdate(DocumentEvent e) {
161             }
162 
163             private void adjustGenerateContentComponents() {
164                 if (filenameField.getText().length() == 0) {
165                     generateContentSizeField.setEnabled(true);
166                     generateContentUnitField.setEnabled(true);
167                 } else {
168                     generateContentSizeField.setEnabled(false);
169                     generateContentUnitField.setEnabled(false);
170                 }
171             }
172         });
173 
174         filePanel.add(filenameField, BorderLayout.CENTER);
175 
176         JButton browseButton = new JButton("Browse");
177         browseButton.addActionListener(new ActionListener() {
178             @Override
179             public void actionPerformed(ActionEvent event) {
180                 JFileChooser fileChooser = new JFileChooser();
181                 int chooseResult = fileChooser.showDialog(filenameField, "Select");
182                 if (chooseResult == JFileChooser.APPROVE_OPTION) {
183                     if (fileChooser.getSelectedFile().isFile()) {
184                         setFile(fileChooser.getSelectedFile());
185                     }
186                 }
187             }
188         });
189         filePanel.add(browseButton, BorderLayout.LINE_END);
190 
191         createRow("File:", filePanel, 4);
192 
193         JPanel generateContentPanel = new JPanel();
194         generateContentPanel.setLayout(new BoxLayout(generateContentPanel, BoxLayout.X_AXIS));
195 
196         generateContentSizeField = new JFormattedTextField(NumberFormat.getIntegerInstance());
197         generateContentSizeField.setValue(0L);
198         generateContentSizeField.setColumns(8);
199         generateContentSizeField.setHorizontalAlignment(SwingConstants.RIGHT);
200         generateContentSizeField.setMaximumSize(generateContentSizeField.getPreferredSize());
201         generateContentPanel.add(generateContentSizeField);
202 
203         generateContentUnitField = new JComboBox<String>(new String[] { "Bytes", "KiB", "MiB", "GiB" });
204         generateContentUnitField.setMaximumSize(new Dimension((int) generateContentUnitField.getPreferredSize()
205                 .getWidth() + 200, (int) generateContentUnitField.getPreferredSize().getHeight()));
206         generateContentPanel.add(generateContentUnitField);
207 
208         generateContentPanel.add(Box.createHorizontalGlue());
209 
210         createRow("Generate content:", generateContentPanel, 5);
211 
212         versioningStateNoneButton = new JRadioButton("none");
213         versioningStateMajorButton = new JRadioButton("major");
214         versioningStateMinorButton = new JRadioButton("minor");
215         versioningStateCheckedoutButton = new JRadioButton("checked out");
216 
217         ButtonGroup versioningStateGroup = new ButtonGroup();
218         versioningStateGroup.add(versioningStateNoneButton);
219         versioningStateGroup.add(versioningStateMajorButton);
220         versioningStateGroup.add(versioningStateMinorButton);
221         versioningStateGroup.add(versioningStateCheckedoutButton);
222 
223         JPanel versioningStatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
224         versioningStatePanel.add(versioningStateNoneButton);
225         versioningStatePanel.add(versioningStateMajorButton);
226         versioningStatePanel.add(versioningStateMinorButton);
227         versioningStatePanel.add(versioningStateCheckedoutButton);
228 
229         if (((DocumentTypeDefinition) ((ObjectTypeItem) typeBox.getSelectedItem()).getObjectType()).isVersionable()) {
230             versioningStateMajorButton.setSelected(true);
231         } else {
232             versioningStateNoneButton.setSelected(true);
233         }
234         createRow("Versioning State:", versioningStatePanel, 6);
235 
236         verifyAfterUploadButton = new JCheckBox("Verify content after upload");
237         createRow("", verifyAfterUploadButton, 7);
238 
239         JButton createButton = new JButton("Create Document", new NewDocumentIcon(ClientHelper.BUTTON_ICON_SIZE,
240                 ClientHelper.BUTTON_ICON_SIZE));
241         createButton.addActionListener(new ActionListener() {
242             @Override
243             public void actionPerformed(ActionEvent event) {
244                 String name = nameField.getText();
245                 ObjectType type = ((ObjectTypeItem) typeBox.getSelectedItem()).getObjectType();
246                 String filename = filenameField.getText();
247 
248                 try {
249                     setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
250 
251                     VersioningState versioningState = VersioningState.NONE;
252                     if (versioningStateMajorButton.isSelected()) {
253                         versioningState = VersioningState.MAJOR;
254                     } else if (versioningStateMinorButton.isSelected()) {
255                         versioningState = VersioningState.MINOR;
256                     } else if (versioningStateCheckedoutButton.isSelected()) {
257                         versioningState = VersioningState.CHECKEDOUT;
258                     }
259 
260                     ObjectId objectId = null;
261                     if (filename.length() > 0) {
262                         // create a document from a file
263                         objectId = getClientModel()
264                                 .createDocument(name, type.getId(), filename,
265                                         getMandatoryOrOnCreatePropertyValues(type), versioningState,
266                                         unfiledButton.isSelected());
267 
268                         if (verifyAfterUploadButton.isSelected()) {
269                             ContentStream contentStream = getClientModel().createContentStream(filename);
270                             verifyContentStreams(contentStream, objectId);
271                         }
272                     } else {
273                         // create a document with random data
274                         long seed = System.currentTimeMillis();
275                         long length = ((Number) generateContentSizeField.getValue()).longValue();
276                         if (length < 0) {
277                             length = 0;
278                         } else {
279                             for (int i = 0; i < generateContentUnitField.getSelectedIndex(); i++) {
280                                 length = length * 1024;
281                             }
282                         }
283 
284                         objectId = getClientModel().createDocument(name, type.getId(),
285                                 getMandatoryOrOnCreatePropertyValues(type), length, seed, versioningState,
286                                 unfiledButton.isSelected());
287 
288                         if (verifyAfterUploadButton.isSelected()) {
289                             ContentStream contentStream = getClientModel().createContentStream("", length, seed);
290                             verifyContentStreams(contentStream, objectId);
291                         }
292                     }
293 
294                     if (objectId != null) {
295                         getClientModel().loadObject(objectId.getId());
296                     }
297 
298                     thisDialog.setVisible(false);
299                     thisDialog.dispose();
300                 } catch (Exception e) {
301                     ClientHelper.showError(null, e);
302                 } finally {
303                     setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
304 
305                     try {
306                         getClientModel().reloadFolder();
307                     } catch (Exception e) {
308                         ClientHelper.showError(null, e);
309                     }
310                 }
311             }
312         });
313         createActionRow("", createButton, 7);
314 
315         if (file != null) {
316             setFile(file);
317         }
318 
319         getRootPane().setDefaultButton(createButton);
320 
321         showDialog();
322     }
323 
324     private void setFile(File file) {
325         filenameField.setText(file.getAbsolutePath());
326         if (nameField.getText().trim().length() == 0) {
327             nameField.setText(file.getName());
328         }
329     }
330 
331     private void verifyContentStreams(ContentStream sourceContentStream, ObjectId objectId) {
332         // download content from repository
333         ClientSession clientSession = getClientModel().getClientSession();
334         Document doc = (Document) clientSession.getSession().getObject(objectId,
335                 clientSession.getObjectOperationContext());
336         ContentStream docContentStream = doc.getContentStream();
337 
338         // compare
339         if (docContentStream == null) {
340             if (sourceContentStream.getLength() == 0) {
341                 JOptionPane.showMessageDialog(getOwner(), "Source file and document content are both empty.",
342                         "Verification successful", JOptionPane.INFORMATION_MESSAGE);
343             } else {
344                 JOptionPane.showMessageDialog(getOwner(), "Document has no conent but the source file is not empty!",
345                         "Verification failed", JOptionPane.ERROR_MESSAGE);
346             }
347             return;
348         }
349 
350         InputStream sourceContent = null;
351         InputStream docContent = null;
352         try {
353             sourceContent = new BufferedInputStream(sourceContentStream.getStream(), 64 * 1024);
354             docContent = new BufferedInputStream(docContentStream.getStream(), 64 * 1024);
355 
356             int fb = 0;
357             int db = 0;
358             long pos = 0;
359             while (fb > -1 && db > -1) {
360                 fb = sourceContent.read();
361                 db = docContent.read();
362 
363                 if (fb != db) {
364                     if (fb == -1) {
365                         JOptionPane.showMessageDialog(getOwner(),
366                                 "The document content is bigger than the source file!", "Verification failed",
367                                 JOptionPane.ERROR_MESSAGE);
368                     } else if (db == -1) {
369                         JOptionPane.showMessageDialog(getOwner(),
370                                 "The source file is bigger than the document content!", "Verification failed",
371                                 JOptionPane.ERROR_MESSAGE);
372                     } else {
373                         JOptionPane.showMessageDialog(getOwner(), "Contents differ at byte " + pos + "!",
374                                 "Verification failed", JOptionPane.ERROR_MESSAGE);
375                     }
376 
377                     return;
378                 }
379 
380                 pos++;
381             }
382 
383             JOptionPane.showMessageDialog(getOwner(), "Source file and document content are identical.",
384                     "Verification successful", JOptionPane.INFORMATION_MESSAGE);
385         } catch (Exception e) {
386             JOptionPane.showMessageDialog(getOwner(), "Content test exception: " + e.getMessage(),
387                     "Verification failed", JOptionPane.ERROR_MESSAGE);
388         } finally {
389             IOUtils.closeQuietly(sourceContent);
390             IOUtils.consumeAndClose(docContent);
391         }
392     }
393 }