001/* 002 * Copyright (c) 2006-2012 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 * Bogdan Stefanescu 011 * Florent Guillaume 012 * Nicolas Chapurlat <nchapurlat@nuxeo.com> 013 */ 014package org.nuxeo.ecm.core.schema.types.primitives; 015 016import java.io.ByteArrayInputStream; 017import java.io.IOException; 018import java.io.InputStream; 019 020import org.apache.commons.lang.StringUtils; 021import org.apache.commons.logging.Log; 022import org.apache.commons.logging.LogFactory; 023import org.nuxeo.common.utils.FileUtils; 024import org.nuxeo.ecm.core.schema.types.PrimitiveType; 025import org.nuxeo.ecm.core.schema.types.constraints.Constraint; 026import org.nuxeo.ecm.core.schema.types.constraints.NotNullConstraint; 027 028/** 029 * The binary type handles values of type InputStream. 030 */ 031public final class BinaryType extends PrimitiveType { 032 033 private static final long serialVersionUID = 1L; 034 035 private static final Log log = LogFactory.getLog(BinaryType.class); 036 037 public static final String ID = "binary"; 038 039 public static final BinaryType INSTANCE = new BinaryType(); 040 041 private BinaryType() { 042 super(ID); 043 } 044 045 @Override 046 public boolean validate(Object object) { 047 return true; 048 } 049 050 @Override 051 public Object convert(Object value) { 052 if (value instanceof CharSequence) { 053 return new ByteArrayInputStream(value.toString().getBytes()); 054 } else if (value instanceof byte[]) { 055 return new ByteArrayInputStream((byte[]) value); 056 } else if (value instanceof InputStream) { 057 return value; 058 } 059 return null; 060 } 061 062 public static Object parseString(String str) { 063 return new ByteArrayInputStream(str.getBytes()); 064 } 065 066 protected Object readResolve() { 067 return INSTANCE; 068 } 069 070 @Override 071 public Object decode(String str) { 072 if (StringUtils.isEmpty(str)) { 073 return null; 074 } 075 return new ByteArrayInputStream(str.getBytes()); 076 } 077 078 @Override 079 public String encode(Object object) { 080 if (object instanceof InputStream) { 081 try { 082 return FileUtils.read((InputStream) object); 083 } catch (IOException e) { 084 log.error(e, e); 085 return null; 086 } 087 } 088 return object.toString(); 089 } 090 091 @Override 092 public boolean support(Class<? extends Constraint> constraint) { 093 if (NotNullConstraint.class.equals(constraint)) { 094 return true; 095 } 096 return false; 097 } 098 099}