001/* 002 * (C) Copyright 2018 Nuxeo (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 * Thomas Roger 018 */ 019 020package org.nuxeo.ecm.automation.core.util; 021 022import javax.servlet.http.HttpServletResponse; 023 024import org.apache.logging.log4j.LogManager; 025import org.apache.logging.log4j.Logger; 026import org.nuxeo.ecm.core.api.Blob; 027import org.nuxeo.ecm.core.api.NuxeoException; 028import org.nuxeo.ecm.core.io.download.DownloadService; 029import org.nuxeo.ecm.platform.web.common.RequestContext; 030import org.nuxeo.ecm.platform.web.common.vh.VirtualHostHelper; 031import org.nuxeo.runtime.api.Framework; 032 033import com.fasterxml.jackson.databind.node.ObjectNode; 034 035/** 036 * Blob decoder resolving a Blob from a given download URL. 037 * <p> 038 * Format is: 039 * 040 * <pre> 041 * { 042 * "data": "http://localhost:8080/nuxeo/nxfile/REPOSITORY/DOC_ID/file:content" 043 * } 044 * </pre> 045 * 046 * @since 10.3 047 */ 048public class JSONObjectBlobDecoder implements JSONBlobDecoder { 049 050 private static final Logger log = LogManager.getLogger(JSONObjectBlobDecoder.class); 051 052 public static final String DATA_FIELD_NAME = "data"; 053 054 @Override 055 public Blob getBlobFromJSON(ObjectNode jsonObject) { 056 if (!jsonObject.has(DATA_FIELD_NAME)) { 057 return null; 058 } 059 060 String data = jsonObject.get(DATA_FIELD_NAME).textValue(); 061 if (data != null && data.startsWith("http")) { 062 return getBlobFromURL(data); 063 } 064 return null; 065 } 066 067 protected Blob getBlobFromURL(String url) { 068 RequestContext activeContext = RequestContext.getActiveContext(); 069 if (activeContext == null) { 070 return null; 071 } 072 073 String baseURL = VirtualHostHelper.getBaseURL(activeContext.getRequest()); 074 String path = url.replace(baseURL, ""); 075 Blob blob = Framework.getService(DownloadService.class).resolveBlobFromDownloadUrl(path); 076 if (blob == null) { 077 // document does not exist / no READ permission / no blob 078 log.debug("No Blob found for: {}", url); 079 throw new NuxeoException(HttpServletResponse.SC_BAD_REQUEST); 080 } 081 return blob; 082 } 083}