com.brightcove.zartan.common.verifier.VideoResponse.java Source code

Java tutorial

Introduction

Here is the source code for com.brightcove.zartan.common.verifier.VideoResponse.java

Source

/**
 * Copyright (C) 2012 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.verifier;

import static org.junit.Assert.assertNotNull;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.JsonNode;

import com.brightcove.common.logging.BrightcoveLog;
import com.brightcove.zartan.common.account.ApiCredentials;
import com.brightcove.zartan.common.account.Credentials;
import com.brightcove.zartan.common.catalog.Video;
import com.brightcove.zartan.common.helper.MediaAPIHelper;
import com.brightcove.zartan.exception.MediaAPIException;

public class VideoResponse extends Response {
    private static BrightcoveLog mLog = BrightcoveLog.getLogger(VideoResponse.class);

    private JsonNode httpResponseJson;
    private JsonNode iosResponseJson;
    private JsonNode rtmpResponseJson;

    public static enum MediaDeliveryType {
        DEFAULT("default"), HTTP("http"), HTTP_IOS("http_ios");

        private final String deliveryType;

        private MediaDeliveryType(String deliveryType) {
            this.deliveryType = deliveryType;
        }

        public String toString() {
            return deliveryType;
        }
    }

    public VideoResponse(VerifiableUpload upload) {
        httpResponseJson = setResponseJson(upload, MediaDeliveryType.HTTP.toString());
        rtmpResponseJson = setResponseJson(upload, MediaDeliveryType.DEFAULT.toString());
        iosResponseJson = setResponseJson(upload, MediaDeliveryType.HTTP_IOS.toString());
    }

    public VideoResponse(JsonNode httpResponseJson, JsonNode iosResponseJson, JsonNode rtmpResponseJson) {
        this.httpResponseJson = httpResponseJson;
        this.iosResponseJson = iosResponseJson;
        this.rtmpResponseJson = rtmpResponseJson;
    }

    private JsonNode setResponseJson(VerifiableUpload upload, String mediaDeliveryType) {
        JsonNode responseJson = getJsonForDelivery(upload,
                new BasicNameValuePair("media_delivery", mediaDeliveryType));
        mLog.info(mediaDeliveryType + " response: " + responseJson);

        if (responseJson.get("result") != null && responseJson.get("result").isNull()) {
            responseJson = null;
        }

        return responseJson;
    }

    /**
     * @return true only if all renditions were successfully deleted
     * @throws Throwable
     */
    public boolean deleteDownloadedRenditions(List<Throwable> throwables) throws Throwable {
        boolean anyFailed = false;

        for (String localPath : renditionFiles.values()) {
            try {
                anyFailed = ((!new File(localPath).delete()) || anyFailed);
            } catch (Throwable t) {
                mLog.error("Downloaded rendition file " + localPath
                        + " failed to get deleted, because an instance of " + t.getClass() + " was thrown. ", t);
                throwables.add(t);
            }
        }

        return (!anyFailed);
    }

    public String getFileForRendition(JsonNode primaryRend) throws MalformedURLException {
        String urlNodeText = primaryRend.get("url").getTextValue();
        assertNotNull(urlNodeText);
        String urlPath = new URL(urlNodeText).getPath();
        if (renditionFiles == null) {
            renditionFiles = new HashMap<String, String>();
        }
        if (renditionFiles.get(urlNodeText) != null) {
            return renditionFiles.get(urlNodeText);
        } else {
            String filename = urlPath.substring(urlPath.lastIndexOf("/") + 1);
            String tmpDir = System.getProperty("java.io.tmpdir", "/tmp");

            if (!tmpDir.endsWith(File.separator)) {
                tmpDir += File.separator;
            }

            String localPath = tmpDir + filename;
            downloadFile(urlNodeText, localPath);
            renditionFiles.put(urlNodeText, localPath);
            return localPath;
        }
    }

    public JsonNode getJsonForDelivery(VerifiableUpload upload, BasicNameValuePair delivery) {

        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        Video v = upload.getUploadInfo().getVideo();

        if (v.getVideoId() != null) {
            parameters.add(new BasicNameValuePair("command", "find_video_by_id"));
            parameters.add(new BasicNameValuePair("videoId", v.getVideoId().toString()));
        } else {
            parameters.add(new BasicNameValuePair("command", "find_video_by_reference_id"));
            parameters.add(new BasicNameValuePair("reference_id", v.getRefId()));
        }
        String readtoken = null;
        for (Credentials c : upload.getAccount().getCredentials()) {
            if (c instanceof ApiCredentials) {
                readtoken = ((ApiCredentials) c).getReadToken();
            }
        }

        // TODO: throw if token is null

        parameters.add(new BasicNameValuePair("token", readtoken));
        parameters.add(delivery);
        parameters.add(new BasicNameValuePair("fields",
                "thumbnailURL,videoStillURL," + "shortDescription,tags,customFields,id,length,"
                        + "creationDate,publishedDate,startDate,endDate,linkURL,referenceId,"
                        + "linkText,videoFullLength,longDescription,accountId,"
                        + "itemState,lastModifiedDate,economics,adKeys,geoRestricted,"
                        + "geoFilteredCountries,geoFilterExclude,cuePoints,playsTotal,"
                        + "playsTrailingWeek,FLVURL,renditions,iosrenditions,name"));

        JsonNode result = null;
        try {
            result = (new MediaAPIHelper()).executeRead(upload.getEnvironment(), parameters);
        } catch (URISyntaxException uriSyntaxException) {
            uriSyntaxException.printStackTrace();
        } catch (MediaAPIException e) {
            e.printStackTrace();
        }
        return result;
    }
}