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.impl.adapters; 013 014import org.nuxeo.ecm.automation.OperationContext; 015import org.nuxeo.ecm.automation.TypeAdaptException; 016import org.nuxeo.ecm.automation.TypeAdapter; 017import org.nuxeo.ecm.automation.core.scripting.Scripting; 018import org.nuxeo.ecm.core.api.DocumentModel; 019import org.nuxeo.ecm.core.api.DocumentRef; 020import org.nuxeo.ecm.core.api.IdRef; 021import org.nuxeo.ecm.core.api.NuxeoException; 022import org.nuxeo.ecm.core.api.PathRef; 023 024/** 025 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 026 */ 027public class StringToDocRef implements TypeAdapter { 028 029 @Override 030 public DocumentRef getAdaptedValue(OperationContext ctx, Object objectToAdapt) throws TypeAdaptException { 031 try { 032 String value = (String) objectToAdapt; 033 if (value.startsWith(".")) { 034 Object obj = Scripting.newExpression("Document.resolvePathAsRef(\"" + value + "\")").eval(ctx); 035 if (obj instanceof DocumentModel) { 036 return ((DocumentModel) obj).getRef(); 037 } else if (obj instanceof DocumentRef) { 038 return (DocumentRef) obj; 039 } 040 throw new TypeAdaptException(String.format("Cannot adapt value '%s' to a DocumentRef instance", value)); 041 } 042 return createRef(value); 043 } catch (TypeAdaptException e) { 044 throw e; 045 } catch (NuxeoException e) { 046 throw new TypeAdaptException(e); 047 } 048 } 049 050 public static DocumentRef createRef(String value) { 051 return value.startsWith("/") ? new PathRef(value) : new IdRef(value); 052 } 053 054}