001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 */
020
021package org.nuxeo.ecm.automation.core.util;
022
023import org.codehaus.jackson.node.ObjectNode;
024import org.nuxeo.ecm.core.api.Blob;
025import org.nuxeo.ecm.core.api.Blobs;
026
027/**
028 * Very basic implementation of a Blob decoder Only usable for StringBlobs
029 *
030 * @author Tiry (tdelprat@nuxeo.com)
031 * @since 5.5
032 */
033public class JSONStringBlobDecoder implements JSONBlobDecoder {
034    @Override
035    public Blob getBlobFromJSON(ObjectNode jsonObject) {
036        Blob blob;
037
038        String filename = null;
039        if (jsonObject.has("filename")) {
040            filename = jsonObject.get("filename").getTextValue();
041        }
042        if (filename == null && jsonObject.has("name")) {
043            filename = jsonObject.get("name").getTextValue();
044        }
045        String encoding = "UTF-8";
046        if (jsonObject.has("encoding")) {
047            encoding = jsonObject.get("encoding").getTextValue();
048        }
049
050        String mimetype = "text/plain";
051        if (jsonObject.has("mime-type")) {
052            mimetype = jsonObject.get("mime-type").getTextValue();
053        }
054        String data = null;
055        if (jsonObject.has("data")) {
056            data = jsonObject.get("data").getTextValue();
057            // try to avoid the bug NXP-18488: data contains the blob url
058            // and must not be recognized as a new blob content
059            if (data.startsWith("http")) {
060                data = null;
061            }
062        } else if (jsonObject.has("content")) {
063            data = jsonObject.get("content").getTextValue();
064        }
065        if (data == null) {
066            return null;
067        } else {
068            blob = Blobs.createBlob(data, mimetype, encoding, filename);
069        }
070        return blob;
071    }
072}