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 * Nuxeo - initial API and implementation 011 * 012 */ 013 014package org.nuxeo.ecm.core.api.blobholder; 015 016import java.io.IOException; 017 018import org.nuxeo.ecm.core.api.Blob; 019import org.nuxeo.ecm.core.api.Blobs; 020import org.nuxeo.ecm.core.api.DocumentModel; 021import org.nuxeo.ecm.core.api.NuxeoException; 022 023/** 024 * {@link BlobHolder} implemention based on a {@link DocumentModel} and a Xpath pointing to a String fields. (Typical 025 * use case is the Note DocType). 026 * 027 * @author tiry 028 */ 029public class DocumentStringBlobHolder extends DocumentBlobHolder { 030 031 protected String mt; 032 033 public DocumentStringBlobHolder(DocumentModel doc, String path) { 034 super(doc, path); 035 } 036 037 public DocumentStringBlobHolder(DocumentModel doc, String path, String mime_type) { 038 super(doc, path); 039 this.mt = mime_type; 040 } 041 042 @Override 043 public Blob getBlob() { 044 String string = (String) doc.getProperty(xPath).getValue(); 045 if (string == null) { 046 return null; 047 } 048 Blob blob = Blobs.createBlob(string, mt); 049 String ext = ".txt"; 050 if ("text/html".equals(mt)) { 051 ext = ".html"; 052 } else if ("text/xml".equals(mt)) { 053 ext = ".xml"; 054 } else if ("text/x-web-markdown".equals(mt)) { 055 ext = ".md"; 056 } 057 String title = doc.getTitle(); 058 if (!title.endsWith(ext)) { 059 title = title.concat(ext); 060 } 061 blob.setFilename(title); 062 return blob; 063 } 064 065 @Override 066 public void setBlob(Blob blob) { 067 if (blob == null) { 068 doc.getProperty(xPath).setValue(null); 069 mt = null; 070 } else { 071 String string; 072 try { 073 string = blob.getString(); 074 } catch (IOException e) { 075 throw new NuxeoException(e); 076 } 077 // strip '\0 chars from text 078 if (string.indexOf('\0') >= 0) { 079 string = string.replace("\0", ""); 080 } 081 doc.getProperty(xPath).setValue(string); 082 mt = blob.getMimeType(); 083 } 084 } 085 086}