Skip to content

Encode URLs in API calls #186

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jan 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions cloudinary-core/src/main/java/com/cloudinary/Api.java
Original file line number Diff line number Diff line change
Expand Up @@ -244,15 +244,15 @@ public ApiResponse updateUploadPreset(String name, Map options) throws Exception
if (options == null) options = ObjectUtils.emptyMap();
Map params = Util.buildUploadParams(options);
Util.clearEmpty(params);
params.putAll(ObjectUtils.only(options, "unsigned", "disallow_public_id","live"));
params.putAll(ObjectUtils.only(options, "unsigned", "disallow_public_id", "live"));
return callApi(HttpMethod.PUT, Arrays.asList("upload_presets", name), params, options);
}

public ApiResponse createUploadPreset(Map options) throws Exception {
if (options == null) options = ObjectUtils.emptyMap();
Map params = Util.buildUploadParams(options);
Util.clearEmpty(params);
params.putAll(ObjectUtils.only(options, "name", "unsigned", "disallow_public_id","live"));
params.putAll(ObjectUtils.only(options, "name", "unsigned", "disallow_public_id", "live"));
return callApi(HttpMethod.POST, Arrays.asList("upload_presets"), params, options);
}

Expand All @@ -268,6 +268,13 @@ public ApiResponse subFolders(String ofFolderPath, Map options) throws Exception
return callApi(HttpMethod.GET, Arrays.asList("folders", ofFolderPath), ObjectUtils.emptyMap(), options);
}

//Creates an empty folder
public ApiResponse createFolder(String folderName, Map options) throws Exception {
if (options == null)
options = ObjectUtils.emptyMap();
return callApi(HttpMethod.POST, Arrays.asList("folders", folderName), ObjectUtils.emptyMap(), options);
}

public ApiResponse restore(Iterable<String> publicIds, Map options) throws Exception {
if (options == null)
options = ObjectUtils.emptyMap();
Expand Down Expand Up @@ -583,7 +590,7 @@ private ApiResponse updateResourcesAccessMode(String accessMode, String byKey, O
*/
public ApiResponse addMetadataField(MetadataField field) throws Exception {
return callApi(HttpMethod.POST, Collections.singletonList("metadata_fields"),
ObjectUtils.toMap(field), ObjectUtils.asMap ("content_type", "json"));
ObjectUtils.toMap(field), ObjectUtils.asMap("content_type", "json"));
}

/**
Expand Down Expand Up @@ -639,7 +646,7 @@ public ApiResponse updateMetadataFieldDatasource(String fieldExternalId, List<Me
*/
public ApiResponse deleteDatasourceEntries(String fieldExternalId, List<String> entriesExternalId) throws Exception {
List<String> uri = Arrays.asList("metadata_fields", fieldExternalId, "datasource");
return callApi(HttpMethod.DELETE, uri,Collections.singletonMap("external_ids", entriesExternalId) , Collections.emptyMap());
return callApi(HttpMethod.DELETE, uri, Collections.singletonMap("external_ids", entriesExternalId), Collections.emptyMap());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,9 @@ public static Configuration from(String cloudinaryUrl) {
static protected Map parseConfigUrl(String cloudinaryUrl) {
Map params = new HashMap();
URI cloudinaryUri = URI.create(cloudinaryUrl);
if (cloudinaryUri.getScheme() == null || !cloudinaryUri.getScheme().equalsIgnoreCase("cloudinary")){
throw new IllegalArgumentException("Invalid CLOUDINARY_URL scheme. Expecting to start with 'cloudinary://'");
}
params.put("cloud_name", cloudinaryUri.getHost());
if (cloudinaryUri.getUserInfo() != null) {
String[] creds = cloudinaryUri.getUserInfo().split(":");
Expand Down Expand Up @@ -427,4 +430,4 @@ public Builder from(Configuration other) {
return this;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,31 @@

import com.cloudinary.Api;
import com.cloudinary.Api.HttpMethod;
import com.cloudinary.SmartUrlEncoder;
import com.cloudinary.api.ApiResponse;

import com.cloudinary.utils.StringUtils;
import java.util.Arrays;
import java.util.Map;


public abstract class AbstractApiStrategy {
protected Api api;

public void init(Api api) {
this.api = api;
}

protected String createApiUrl (Iterable<String> uri, String prefix, String cloudName){

String apiUrl = StringUtils.join(Arrays.asList(prefix, "v1_1", cloudName), "/");
for (String component : uri) {
component = SmartUrlEncoder.encode(component);
apiUrl = apiUrl + "/" + component;

}
return apiUrl;
}

@SuppressWarnings("rawtypes")
public abstract ApiResponse callApi(HttpMethod method, Iterable<String> uri, Map<String, ? extends Object> params, Map options) throws Exception;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1230,6 +1230,24 @@ public void testConfiguration() throws IllegalAccessException {
assertFieldsEqual(config, copy);
}

@Test
public void testCloudinaryUrlValidScheme() {
String cloudinaryUrl = "cloudinary://123456789012345:ALKJdjklLJAjhkKJ45hBK92baj3@test";
Configuration.from(cloudinaryUrl);
}

@Test(expected = IllegalArgumentException.class)
public void testCloudinaryUrlInvalidScheme() {
String cloudinaryUrl = "https://123456789012345:ALKJdjklLJAjhkKJ45hBK92baj3@test";
Configuration.from(cloudinaryUrl);
}

@Test(expected = IllegalArgumentException.class)
public void testCloudinaryUrlEmptyScheme() {
String cloudinaryUrl = " ";
Configuration.from(cloudinaryUrl);
}

private void assertFieldsEqual(Object a, Object b) throws IllegalAccessException {
assertEquals("Two objects must be the same class", a.getClass(), b.getClass());
Field[] fields = a.getClass().getFields();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,7 @@ public ApiResponse callApi(HttpMethod method, Iterable<String> uri, Map<String,
if (apiSecret == null) throw new IllegalArgumentException("Must supply api_secret");
String contentType = ObjectUtils.asString(options.get("content_type"), "urlencoded");
int timeout = ObjectUtils.asInteger(options.get("timeout"), this.api.cloudinary.config.timeout);
String apiUrl = StringUtils.join(Arrays.asList(prefix, "v1_1", cloudName), "/");

for (String component : uri) {
apiUrl = apiUrl + "/" + component;
}
String apiUrl = createApiUrl(uri, prefix, cloudName);

return getApiResponse(method, params, apiKey, apiSecret, contentType, timeout, apiUrl);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,7 @@ public ApiResponse callApi(HttpMethod method, Iterable<String> uri, Map<String,
if (apiSecret == null) throw new IllegalArgumentException("Must supply api_secret");


String apiUrl = StringUtils.join(Arrays.asList(prefix, "v1_1", cloudName), "/");
for (String component : uri) {
apiUrl = apiUrl + "/" + component;
}
String apiUrl = createApiUrl(uri, prefix, cloudName);
HttpUriRequest request = prepareRequest(method, apiUrl, params, options);

request.setHeader("Authorization", "Basic " + Base64Coder.encodeString(apiKey + ":" + apiSecret));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,7 @@ public ApiResponse callApi(HttpMethod method, Iterable<String> uri, Map<String,
if (apiSecret == null) throw new IllegalArgumentException("Must supply api_secret");


String apiUrl = StringUtils.join(Arrays.asList(prefix, "v1_1", cloudName), "/");
for (String component : uri) {
apiUrl = apiUrl + "/" + component;
}
String apiUrl = createApiUrl(uri, prefix, cloudName);
HttpUriRequest request = prepareRequest(method, apiUrl, params, options);

request.setHeader("Authorization", "Basic " + Base64Coder.encodeString(apiKey + ":" + apiSecret));
Expand Down Expand Up @@ -204,4 +201,4 @@ private HttpUriRequest prepareRequest(HttpMethod method, String apiUrl, Map<Stri
setTimeouts(request, options);
return request;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ abstract public class AbstractApiTest extends MockableTest {
public static final Transformation DELETE_TRANSFORMATION = new Transformation().width(100).crop("scale").overlay(new TextLayer().text(SUFFIX + "_delete").fontFamily("Arial").fontSize(60));
public static final String TEST_KEY = "test-key" + SUFFIX;
public static final String API_TEST_RESTORE = "api_test_restore" + SUFFIX;
public static final Set<String> createdFolders = new HashSet<String>();

protected Api api;

Expand Down Expand Up @@ -119,6 +120,12 @@ public static void tearDownClass() {
api.deleteUploadPreset(API_TEST_UPLOAD_PRESET_4, ObjectUtils.emptyMap());
} catch (Exception ignored) {
}
try {
for (String folder : createdFolders) {
api.deleteFolder(folder, ObjectUtils.emptyMap());
}
} catch (Exception ignored) {
}

}

Expand Down Expand Up @@ -484,7 +491,8 @@ public void testListTransformationByNamed() throws Exception {
} finally {
try {
api.deleteTransformation(name, null);
} catch (Exception ignored){}
} catch (Exception ignored) {
}
}
}

Expand Down Expand Up @@ -653,7 +661,7 @@ public void testGetUploadPreset() throws Exception {
String[] tags = {"a", "b", "c"};
Map context = ObjectUtils.asMap("a", "b", "c", "d");
Map result = api.createUploadPreset(ObjectUtils.asMap("unsigned", true, "folder", "folder", "transformation", EXPLICIT_TRANSFORMATION, "tags", tags, "context",
context,"live",true));
context, "live", true));
String name = result.get("name").toString();
Map preset = api.uploadPreset(name, ObjectUtils.emptyMap());
assertEquals(preset.get("name"), name);
Expand Down Expand Up @@ -693,7 +701,7 @@ public void testUpdateUploadPreset() throws Exception {
String name = api.createUploadPreset(ObjectUtils.asMap("folder", "folder")).get("name").toString();
Map preset = api.uploadPreset(name, ObjectUtils.emptyMap());
Map settings = (Map) preset.get("settings");
settings.putAll(ObjectUtils.asMap("colors", true, "unsigned", true, "disallow_public_id", true,"live",true));
settings.putAll(ObjectUtils.asMap("colors", true, "unsigned", true, "disallow_public_id", true, "live", true));
api.updateUploadPreset(name, settings);
settings.remove("unsigned");
preset = api.uploadPreset(name, ObjectUtils.emptyMap());
Expand Down Expand Up @@ -758,6 +766,14 @@ public void testFolderApi() throws Exception {
api.deleteResourcesByPrefix("test_folder", ObjectUtils.emptyMap());
}

@Test
public void testCreateFolder() throws Exception {
String apTestCreateFolder = "api_test_create_folder" + "_" + SUFFIX;
createdFolders.add(apTestCreateFolder);
Map result = api.createFolder("apTestCreateFolder", null);
assertTrue((Boolean) result.get("success"));
}

@Test
public void testRestore() throws Exception {
// should support restoring resources
Expand All @@ -777,6 +793,14 @@ public void testRestore() throws Exception {
assertEquals(resource.get("bytes"), 3381);
}

@Test
public void testEncodeUrlInApiCall() throws Exception {
String apiTestEncodeUrlInApiCall = "sub^folder test";
createdFolders.add(apiTestEncodeUrlInApiCall);
Map result = api.createFolder(apiTestEncodeUrlInApiCall, null);
assertEquals("sub^folder test", result.get("path"));
}

@Test
public void testUploadMapping() throws Exception {
String aptTestUploadMapping = "api_test_upload_mapping" + SUFFIX;
Expand Down Expand Up @@ -946,7 +970,7 @@ public void testDeleteFolder() throws Exception {
Thread.sleep(5000);
api.deleteResources(Collections.singletonList(uploadResult.get("public_id").toString()), emptyMap());
ApiResponse result = api.deleteFolder(toDelete, emptyMap());
assertTrue(((ArrayList)result.get("deleted")).contains(toDelete));
assertTrue(((ArrayList) result.get("deleted")).contains(toDelete));

// should throw exception (folder not found):
api.deleteFolder(cloudinary.randomPublicId(), emptyMap());
Expand All @@ -958,4 +982,4 @@ public void testCinemagraphAnalysisResource() throws Exception {
ApiResponse res = api.resource(API_TEST, Collections.singletonMap("cinemagraph_analysis", true));
assertNotNull(res.get("cinemagraph_analysis"));
}
}
}