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

Java tutorial

Introduction

Here is the source code for com.brightcove.com.uploader.helper.MediaAPIHelper.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.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
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.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;

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

/**
 * MediaAPIHelper will execute media api call and respond with a JsonNode object.
 * @author storpey
 *
 */
public class MediaAPIHelper {

    private BrightcoveLog mLog = BrightcoveLog.getLogger(this.getClass());

    private ObjectMapper mapper = new ObjectMapper();

    /**
     * Downloads and parses the response stream of an http call.
     * 
     * @param entity
     * @return Parsed JsonNode object
     * @throws MediaAPIError
     * @throws IOException 
     * @throws IllegalStateException 
     */
    private JsonNode getJSONFromEntity(HttpEntity entity) throws MediaAPIError, IllegalStateException, IOException {
        if (entity == null) {
            return null;
        }

        String output = "";
        String buffer = "";
        InputStream instream;

        instream = entity.getContent();

        String charSet = "UTF-8";

        buffer = IOUtils.toString(instream, charSet);

        // Parse JSON
        JsonNode jsonObj = null;
        if (buffer.equals("null")) {
            buffer = "{\"result\":null}";
        }
        jsonObj = mapper.readTree(buffer);

        return jsonObj;
    }

    /**
     * Executes a non file upload write api call against the given URI
     * @param json the json representation of the call you are making
     * @param uri the api servlet you want to execute against
     * @return json response from api
     * @throws BadEnvironmentException
     * @throws MediaAPIError
     */
    public JsonNode executeWrite(JsonNode json, URI uri) throws BadEnvironmentException, MediaAPIError {
        return executeWrite(json, null, uri);
    }

    /**
     * Executes a file upload write api call against the given URI.
     * This is useful for create_video and add_image
     * @param json the json representation of the call you are making
     * @param file the file you are uploading
     * @param uri the api servlet you want to execute against
     * @return json response from api
     * @throws BadEnvironmentException
     * @throws MediaAPIError
     */
    public JsonNode executeWrite(JsonNode json, File file, URI uri) throws BadEnvironmentException, MediaAPIError {

        mLog.debug("using " + uri.getHost() + " on port " + uri.getPort() + " for api write");

        HttpPost method = new HttpPost(uri);
        MultipartEntity entityIn = new MultipartEntity();
        FileBody fileBody = null;

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

        try {
            entityIn.addPart("JSON-RPC", new StringBody(json.toString(), Charset.forName("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            throw new BadEnvironmentException("UTF-8 no longer supported");
        }

        if (file != null) {
            entityIn.addPart(file.getName(), fileBody);
        }
        method.setEntity(entityIn);

        return executeCall(method);
    }

    /**
     * Executes a media read api call against a given environment.
     * @param pEnv Environment to execute against
     * @param parameters query parameters representing the read api call
     * @return json response from api
     * @throws URISyntaxException
     * @throws MediaAPIError
     */
    public JsonNode executeRead(Environment pEnv, List<NameValuePair> parameters)
            throws URISyntaxException, MediaAPIError {
        return executeRead(pEnv.getAPIServer(), pEnv.getAPIPort(), parameters);
    }

    /**
     * Executes a media read api call against a given server.
     * @param server application server you want to execute against
     * @param port port number api servlet is listening on
     * @param parameters query parameters representing the read api call
     * @return json response from api
     * @throws URISyntaxException
     * @throws MediaAPIError
     */
    public JsonNode executeRead(String server, int port, List<NameValuePair> parameters)
            throws URISyntaxException, MediaAPIError {
        mLog.debug("using " + server + " on port " + port + " for api read");

        URI commandUrl = URIUtils.createURI("http", server, port, "services/library",
                URLEncodedUtils.format(parameters, "UTF-8"), null);

        // Make the request
        HttpGet httpGet = new HttpGet(commandUrl);
        return executeCall(httpGet);
    }

    public JsonNode executeRead(String url) throws MediaAPIError {
        HttpGet httpGet = new HttpGet(url);
        return executeCall(httpGet);
    }

    /**
     * Executes HTTP get or post request and returns json response from api
     * @param httpCall  Get or Post method
     * @return json response from api
     * @throws MediaAPIError
     */
    protected JsonNode executeCall(HttpRequestBase httpCall) throws MediaAPIError {
        JsonNode jsonObj;
        try {
            HttpResponse response = null;
            DefaultHttpClient httpAgent = new DefaultHttpClient();
            response = httpAgent.execute(httpCall);

            // Make sure the HTTP communication was OK (not the same as an error in the Media API reponse)
            Integer statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpAgent.getConnectionManager().shutdown();
                throw new MediaAPIError("Response code from HTTP server: '" + statusCode + "'");
            }

            // Parse the response
            HttpEntity entity = response.getEntity();
            jsonObj = getJSONFromEntity(entity);
            httpAgent.getConnectionManager().shutdown();

        } catch (IllegalStateException ise) {
            throw new MediaAPIError("Exception: '" + ise + "'");
        } catch (ClientProtocolException cpe) {
            throw new MediaAPIError("Exception: '" + cpe + "'");
        } catch (IOException ioe) {
            throw new MediaAPIError("Exception: '" + ioe + "'");
        }
        return jsonObj;
    }

    /**
     * Makes JsonNode obect for get_upload_status call
     * @param pToken api write token
     * @param id video id
     * @return json to execute call
     */
    public JsonNode makeUploadStatusJson(String pToken, Long id) {

        JsonNode params = mapper.createObjectNode();
        ((ObjectNode) params).put("token", pToken);
        ((ObjectNode) params).put("video_id", id);

        return makeWriteAPIJson("get_upload_status", params);
    }

    /**
     * Makes JsonNode object containing data to make a create video call, with file upload.
     * @param pVideoFile file to upload
     * @param pToken media api write token
     * @return json to execute call
     */
    public JsonNode makeCreateJson(IngestFile pVideoFile, String pToken) {

        JsonNode params = mapper.createObjectNode();
        JsonNode video = mapper.createObjectNode();
        Options opts = pVideoFile.getOptions();
        ((ObjectNode) params).put("token", pToken);
        ((ObjectNode) video).put("name", pVideoFile.getDisplayName());
        ((ObjectNode) video).put("shortDescription", pVideoFile.getMetaData().getShortDescription());
        if (!(pVideoFile.getRefId().equals("")) || !pVideoFile.getRefId().isEmpty()) {
            ((ObjectNode) video).put("referenceId", pVideoFile.getRefId());
        }
        ArrayNode tags = mapper.createArrayNode();
        for (String t : pVideoFile.getMetaData().getTags()) {
            tags.add(t);
        }
        ((ObjectNode) video).put("tags", tags);
        ((ObjectNode) params).put("video", video);
        ((ObjectNode) params).put("create_multiple_renditions", opts.isMBR());
        ((ObjectNode) params).put("preserve_source_rendition", opts.isPreserveSource());
        if (!opts.getIsVideoFileTypeFLV()) {
            ((ObjectNode) params).put("encode_to", opts.getTargetCodec());
        }
        return makeWriteAPIJson("create_video", params);
    }

    /**
     * Json convenience method, wraps call in method and params section
     * @param method method to call
     * @param params params to pass in
     * @return json to execute call
     */
    public JsonNode makeWriteAPIJson(String method, JsonNode params) {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.createObjectNode();
        ((ObjectNode) rootNode).put("method", method);

        ((ObjectNode) rootNode).put("params", params);

        return rootNode;
    }

    public JsonNode makeUploadStatusJson(String pToken, String refId) {
        JsonNode params = mapper.createObjectNode();
        ((ObjectNode) params).put("token", pToken);
        ((ObjectNode) params).put("reference_id", refId);

        return makeWriteAPIJson("get_upload_status", params);

    }
}