com.brightcove.com.uploader.helper.MediaManagerHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.brightcove.com.uploader.helper.MediaManagerHelper.java

Source

/**
 * Copyright (C) 2011 Brightcove Inc. All Rights Reserved. No use, copying or distribution of this
 * work may be made except in accordance with a valid license agreement from Brightcove Inc. This
 * notice must be included on all copies, modifications and derivatives of this work.
 * 
 * Brightcove Inc MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. BRIGHTCOVE SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS
 * SOFTWARE OR ITS DERIVATIVES.
 * 
 * "Brightcove" is a registered trademark of Brightcove Inc.
 */
package com.brightcove.com.uploader.helper;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.httpclient.HttpException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.brightcove.common.logging.BrightcoveLog;
import com.brightcove.uploader.config.Account;
import com.brightcove.uploader.config.Environment;
import com.brightcove.uploader.exception.BadEnvironmentException;
import com.brightcove.uploader.exception.MediaAPIError;
import com.brightcove.uploader.input.MediaAPI;
import com.brightcove.uploader.upload.IngestFile;
import com.brightcove.uploader.upload.Options;
import com.brightcove.uploader.upload.TitleMetaData;

public class MediaManagerHelper {
    private BrightcoveLog mLog = BrightcoveLog.getLogger(this.getClass());

    /**
     * Creates a Media Manager upload URI  
     * @return The mediaupload URI with request parameters based on passed-in specifications 
     * 
     * Example of sniffed URL for an SBR upload with MP4 selected as output 
     * option for H.264 source and FLV selected as output option for "Other" 
     * source:
     *     http://console.brightcove.com/services/mediaupload
     *     ?validation-token=6D7gcVoN5R5ZrzMTijg_pLr23_CXlvwwM_y1Q3L61xh9n1hXo7wSdXdHIIWbTIaj
     *     &source=80
     *     &name=fishtank
     *     &file-name=fishtank.mp4
     *     &file-size=1070258
     *     &pub-id=263785096
     *     &media-type=0
     *     &economics-type=1
     *     &item-state=0
     *     &transcode-options=H264%3DH264%2COTHER%3DVP6
     *        
     * @throws HttpException
     * @throws IOException
     * @throws URISyntaxException
     * @throws ParserConfigurationException
     * @throws SAXException
     */
    public URI createUploadUrl(Environment pEnvironment, IngestFile pVideoFile, Account pAccount, String pToken)
            throws HttpException, IOException, URISyntaxException, ParserConfigurationException, SAXException {
        File f = pVideoFile.getFile();
        Options options = pVideoFile.getOptions();
        TitleMetaData titleMetaData = pVideoFile.getMetaData();
        String callArgs;
        ArrayList<String> tags = titleMetaData.getTags();
        String displayName = pVideoFile.getDisplayName();

        callArgs = "?validation-token=" + pToken;

        //source UploadTypeEnum... like really i can change this
        callArgs += "&source=80";

        //set display name
        callArgs += "&name=" + URLEncoder.encode((displayName != null) ? displayName : f.getName(), "UTF-8");

        if (tags != null) {
            for (String t : tags) {
                callArgs += "&tag=" + t;
            }
        }

        //Get and add file attributes
        callArgs += "&file-name=" + f.getName();
        callArgs += "&file-size=" + f.length();

        //set pub id
        callArgs += "&pub-id=" + pAccount.getId();

        //media-type: 0=video(not-MBR), 2=digital master(MBR)
        callArgs += "&media-type=" + (options.isMBR() ? 2 : 0);

        callArgs += "&economics-type=1";

        //item-state: 0=active 1=inactive
        callArgs += "&item-state=" + (titleMetaData.isActive() ? 0 : 1);

        if (!options.getIsVideoFileTypeFLV()) {
            String encodeTo = options.getTargetCodec().equalsIgnoreCase("MP4") ? "H264" : "VP6";

            callArgs += "&transcode-options=H264%3D" + encodeTo
                    + (options.isPreserveSource() ? "%2CH264ASRENDITION" : "") + "%2COTHER%3D" + encodeTo;

            /* TODO: SBR uploads with "No processing" selected should have 
             * "NOP" in place of encodeTo value for H264 source files; consider 
             * supporting this if needed.
             */
        }

        return new URL("http", pEnvironment.getMediaUploadServer(), pEnvironment.getMediaUploadPort(),
                "/services/mediaupload" + callArgs).toURI();
    }

    public void checkComplete(Account pAccount, Environment pEnvironment, Long result)
            throws BadEnvironmentException, MediaAPIError, JSONException, MalformedURLException,
            URISyntaxException {
        //Use API for now
        MediaAPI ma = new MediaAPI();
        URI targetURL = new URL("http", pEnvironment.getAPIServer(), pEnvironment.getAPIPort(), "/services/post")
                .toURI();

        ma.waitForCompletion(pAccount.getDefaultWriteToken(), targetURL, result);
    }

    public Long uploadFile(URI uri, File f, DefaultHttpClient client)
            throws HttpException, IOException, URISyntaxException, ParserConfigurationException, SAXException {
        mLog.info("using " + uri.getHost() + " on port " + uri.getPort() + " for MM upload");

        HttpPost method = new HttpPost(uri);
        MultipartEntity entityIn = new MultipartEntity();
        entityIn.addPart("FileName", new StringBody(f.getName(), Charset.forName("UTF-8")));

        FileBody fileBody = null;

        if (f != null) {
            fileBody = new FileBody(f);
        }

        if (f != null) {
            entityIn.addPart(f.getName(), fileBody);
        }

        entityIn.addPart("Upload", new StringBody("Submit Query", Charset.forName("UTF-8")));
        method.setEntity(entityIn);

        if (client != null) {
            return executeUpload(method, client);
        }

        return null;
    }

    private Long executeUpload(HttpPost method, DefaultHttpClient client)
            throws IOException, ClientProtocolException, ParserConfigurationException, SAXException {
        HttpResponse response = client.execute(method);
        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        DefaultHandler dh = new MMHandler();

        saxParser.parse(instream, dh);
        mLog.info("id: " + ((MMHandler) dh).getMediaId());

        return ((MMHandler) dh).getMediaId();
    }

    private class MMHandler extends DefaultHandler {
        boolean success = false;
        Long assetId;
        Long mediaId;
        Long pubId;
        Long uploadId;

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if (qName.equalsIgnoreCase("response")) {
                success = attributes.getValue("status").equals("success");
            }

            if (qName.equalsIgnoreCase("MediaUploadResponse")) {
                assetId = Long.valueOf(attributes.getValue("primary-asset-id"));
                mediaId = Long.valueOf(attributes.getValue("primary-media-object-id"));
                pubId = Long.valueOf(attributes.getValue("publisher-id"));
                uploadId = Long.valueOf(attributes.getValue("upload-state-id"));
            }
        }

        public boolean isSuccess() {
            return success;
        }

        public Long getAssetId() {
            return assetId;
        }

        public Long getMediaId() {
            return mediaId;
        }

        public Long getPubId() {
            return pubId;
        }

        public Long getUploadId() {
            return uploadId;
        }
    }
}