BitlyURLShortener.java

/*
 * Copyright 2019 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.genesys.server.service.impl;

import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.genesys.server.service.UrlShortenerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Component("bitlyURLShortener")
public class BitlyURLShortener implements UrlShortenerService {

	private static final Logger LOG = LoggerFactory.getLogger(BitlyURLShortener.class);

	@Value("${bitly.access.token}")
	private String accessToken;

	@Value("${bitly.group.guid}")
	private String groupGuid;

	@Value("${bitly.url.shortener}")
	private String bitlyUrlShortener;

	private RestTemplate restTemplate;

	public BitlyURLShortener() {
		this.restTemplate = new RestTemplate();
	}

	@Override
	public String shortenUrl(URL url) {
		LOG.info("Shortening {}", url);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.set("Authorization", accessToken);

		Map<String, String> request = new HashMap<String, String>();
		request.put("long_url", url.toString());
		request.put("group_guid", groupGuid);

		HttpEntity<Object> requestEntity = new HttpEntity<Object>(request, headers);

		try {
			LinkedHashMap<String, Object> linkedHashMap = restTemplate.postForObject(bitlyUrlShortener, requestEntity, LinkedHashMap.class);
			if (LOG.isDebugEnabled() && linkedHashMap != null) {
				for (var entry : linkedHashMap.entrySet()) {
					LOG.debug("{}: {}", entry.getKey(), entry.getValue());
				}
			}
			return "https://" + (String) linkedHashMap.get("id");
		} catch (final HttpStatusCodeException e) {
			LOG.error("bit.ly HTTP error {} {}", e.getResponseBodyAsString(), e.getMessage());
		} catch (final RestClientException e) {
			LOG.error(e.getMessage(), e);
		}

		return null;
	}
}