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.client.model; 013 014import java.io.ByteArrayInputStream; 015import java.io.IOException; 016import java.io.InputStream; 017 018import org.nuxeo.ecm.automation.client.jaxrs.util.Base64; 019 020/** 021 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 022 */ 023public abstract class Blob implements OperationInput { 024 025 private static final long serialVersionUID = 1L; 026 027 public static Blob fromBase64String(String fileName, String content) { 028 return fromBase64String(fileName, content, null); 029 } 030 031 public static Blob fromBase64String(String fileName, String content, String mimeType) { 032 return new StreamBlob(new ByteArrayInputStream(Base64.decode(content)), fileName, mimeType); 033 } 034 035 protected String mimeType; 036 037 protected String fileName; 038 039 protected Blob() { 040 041 } 042 043 public Blob(String fileName) { 044 this(fileName, null); 045 } 046 047 public Blob(String fileName, String mimeType) { 048 this.fileName = fileName; 049 setMimeType(mimeType); 050 } 051 052 public String getMimeType() { 053 return mimeType; 054 } 055 056 public String getFileName() { 057 return fileName; 058 } 059 060 public void setFileName(String fileName) { 061 this.fileName = fileName; 062 } 063 064 public void setMimeType(String mimeType) { 065 this.mimeType = mimeType == null ? "application/octet-stream" : mimeType; 066 } 067 068 public int getLength() { 069 return -1; 070 } 071 072 public String getInputType() { 073 return "blob"; 074 } 075 076 public String getInputRef() { 077 return null; 078 } 079 080 public boolean isBinary() { 081 return true; 082 } 083 084 public abstract InputStream getStream() throws IOException; 085 086 protected String formatLength(int len) { 087 int k = len / 1024; 088 if (k <= 0) { 089 return len + " B"; 090 } else if (k < 1024) { 091 return k + " K"; 092 } else { 093 return (k / 1024) + " M"; 094 } 095 } 096 097 @Override 098 public String toString() { 099 return fileName + " - " + mimeType + " - " + formatLength(getLength()); 100 } 101}