001/* 002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * bstefanescu 011 */ 012package org.nuxeo.ecm.automation.core.operations.document; 013 014import java.io.Serializable; 015 016import org.nuxeo.ecm.automation.OperationException; 017import org.nuxeo.ecm.automation.core.Constants; 018import org.nuxeo.ecm.automation.core.annotations.Context; 019import org.nuxeo.ecm.automation.core.annotations.Operation; 020import org.nuxeo.ecm.automation.core.annotations.OperationMethod; 021import org.nuxeo.ecm.automation.core.annotations.Param; 022import org.nuxeo.ecm.automation.core.collectors.DocumentModelCollector; 023import org.nuxeo.ecm.core.api.CoreSession; 024import org.nuxeo.ecm.core.api.DocumentModel; 025import org.nuxeo.ecm.core.api.model.Property; 026import org.nuxeo.ecm.core.schema.types.SimpleType; 027import org.nuxeo.ecm.core.schema.types.Type; 028 029/** 030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 031 */ 032@Operation(id = SetDocumentProperty.ID, category = Constants.CAT_DOCUMENT, label = "Update Property", description = "Set a single property value on the input document. The property is specified using its xpath. The document is automatically saved if 'save' parameter is true. If you unset the 'save' you need to save it later using Save Document operation. Return the modified document.") 033public class SetDocumentProperty { 034 035 public static final String ID = "Document.SetProperty"; 036 037 @Context 038 protected CoreSession session; 039 040 @Param(name = "xpath") 041 protected String xpath; 042 043 @Param(name = "value", required = false) 044 protected Serializable value; 045 046 @Param(name = "save", required = false, values = "true") 047 protected boolean save = true; 048 049 @OperationMethod(collector = DocumentModelCollector.class) 050 public DocumentModel run(DocumentModel doc) throws OperationException { 051 Property p = doc.getProperty(xpath); 052 Type type = p.getField().getType(); 053 if (!type.isSimpleType()) { 054 throw new OperationException("Only scalar types can be set using update operation"); 055 } 056 if (value == null) { 057 p.setValue(null); 058 } else if (value.getClass() == String.class) { 059 p.setValue(((SimpleType) type).getPrimitiveType().decode((String) value)); 060 } else { 061 p.setValue(value); 062 } 063 if (save) { 064 doc = session.saveDocument(doc); 065 } 066 067 return doc; 068 } 069 070}