com.brightcove.zartan.common.helper.MediaAPIHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.brightcove.zartan.common.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.zartan.common.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.ObjectNode;

import com.brightcove.common.logging.BrightcoveLog;
import com.brightcove.zartan.common.catalog.Video;
import com.brightcove.zartan.common.environment.BcEnvironment;
import com.brightcove.zartan.common.upload.UploadOptions;
import com.brightcove.zartan.exception.BadEnvironmentException;
import com.brightcove.zartan.exception.MediaAPIException;

/**
 * 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 MediaAPIException
     * @throws IOException
     * @throws IllegalStateException
     */
    private JsonNode getJSONFromEntity(HttpEntity entity)
            throws MediaAPIException, IllegalStateException, IOException {
        if (entity == null) {
            return null;
        }

        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 MediaAPIException
     */
    public JsonNode executeWrite(JsonNode json, URI uri) throws BadEnvironmentException, MediaAPIException {
        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 MediaAPIException
     */
    public JsonNode executeWrite(JsonNode json, File file, URI uri)
            throws BadEnvironmentException, MediaAPIException {

        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 MediaAPIException
     */
    public JsonNode executeRead(BcEnvironment pEnv, List<NameValuePair> parameters)
            throws URISyntaxException, MediaAPIException {
        return executeRead(pEnv.getApiUrl(), 80, 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 MediaAPIException
     */
    public JsonNode executeRead(String server, int port, List<NameValuePair> parameters)
            throws URISyntaxException, MediaAPIException {
        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 MediaAPIException {
        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 MediaAPIException
     */
    protected JsonNode executeCall(HttpRequestBase httpCall) throws MediaAPIException {
        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 response
             */
            Integer statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpAgent.getConnectionManager().shutdown();
                throw new MediaAPIException("Response code from HTTP server: '" + statusCode + "'");
            }

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

        } catch (IllegalStateException ise) {
            throw new MediaAPIException("Exception: '" + ise + "'");
        } catch (ClientProtocolException cpe) {
            throw new MediaAPIException("Exception: '" + cpe + "'");
        } catch (IOException ioe) {
            throw new MediaAPIException("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(Video pVideoFile, UploadOptions opts, String pToken, boolean sourceFLV) {

        JsonNode params = mapper.createObjectNode();
        JsonNode video = mapper.createObjectNode();
        ((ObjectNode) params).put("token", pToken);
        ((ObjectNode) video).put("name", pVideoFile.getDisplayName());
        ((ObjectNode) video).put("shortDescription", pVideoFile.getShortDescription());
        if (!(pVideoFile.getRefId().equals("")) || !pVideoFile.getRefId().isEmpty()) {
            ((ObjectNode) video).put("referenceId", pVideoFile.getRefId());
        }
        ((ObjectNode) params).put("video", video);
        ((ObjectNode) params).put("create_multiple_renditions", opts.isMbr());
        ((ObjectNode) params).put("preserve_source_rendition", opts.isPreserveSource());
        if (!sourceFLV) {
            ((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);
    }
}