001/*
002 * (C) Copyright 2013 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 *     Antoine Taillefer <ataillefer@nuxeo.com>
018 */
019package org.nuxeo.drive.operations;
020
021import java.io.IOException;
022
023import javax.mail.internet.ContentType;
024import javax.mail.internet.ParseException;
025
026import org.apache.commons.lang.StringUtils;
027import org.codehaus.jackson.JsonGenerationException;
028import org.codehaus.jackson.map.JsonMappingException;
029import org.codehaus.jackson.map.ObjectMapper;
030import org.nuxeo.ecm.core.api.Blob;
031import org.nuxeo.ecm.core.api.impl.blob.StringBlob;
032
033/**
034 * Helper for Nuxeo Drive operations.
035 *
036 * @author Antoine Taillefer
037 */
038public final class NuxeoDriveOperationHelper {
039
040    private NuxeoDriveOperationHelper() {
041        // Helper class
042    }
043
044    public static void normalizeMimeTypeAndEncoding(Blob blob) throws ParseException {
045
046        String mimeType = blob.getMimeType();
047        if (!StringUtils.isEmpty(mimeType) && !"null".equals(mimeType)) {
048            ContentType contentType = new ContentType(mimeType);
049            blob.setMimeType(contentType.getBaseType());
050            if (StringUtils.isEmpty(blob.getEncoding())) {
051                String charset = contentType.getParameter("charset");
052                if (!StringUtils.isEmpty(charset)) {
053                    blob.setEncoding(charset);
054                }
055            }
056        }
057    }
058
059    public static Blob asJSONBlob(Object value) throws JsonGenerationException, JsonMappingException, IOException {
060        return new StringBlob(new ObjectMapper().writeValueAsString(value), "application/json");
061    }
062
063}