001/*
002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Antoine Taillefer <ataillefer@nuxeo.com>
016 */
017package org.nuxeo.drive.operations;
018
019import java.io.IOException;
020
021import javax.mail.internet.ContentType;
022import javax.mail.internet.ParseException;
023
024import org.apache.commons.lang.StringUtils;
025import org.codehaus.jackson.JsonGenerationException;
026import org.codehaus.jackson.map.JsonMappingException;
027import org.codehaus.jackson.map.ObjectMapper;
028import org.nuxeo.ecm.core.api.Blob;
029import org.nuxeo.ecm.core.api.impl.blob.StringBlob;
030
031/**
032 * Helper for Nuxeo Drive operations.
033 *
034 * @author Antoine Taillefer
035 */
036public final class NuxeoDriveOperationHelper {
037
038    private NuxeoDriveOperationHelper() {
039        // Helper class
040    }
041
042    public static void normalizeMimeTypeAndEncoding(Blob blob) throws ParseException {
043
044        String mimeType = blob.getMimeType();
045        if (!StringUtils.isEmpty(mimeType) && !"null".equals(mimeType)) {
046            ContentType contentType = new ContentType(mimeType);
047            blob.setMimeType(contentType.getBaseType());
048            if (StringUtils.isEmpty(blob.getEncoding())) {
049                String charset = contentType.getParameter("charset");
050                if (!StringUtils.isEmpty(charset)) {
051                    blob.setEncoding(charset);
052                }
053            }
054        }
055    }
056
057    public static Blob asJSONBlob(Object value) throws JsonGenerationException, JsonMappingException, IOException {
058        return new StringBlob(new ObjectMapper().writeValueAsString(value), "application/json");
059    }
060
061}