001/* 002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl-2.1.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Thomas Roger 016 */ 017 018package org.nuxeo.ecm.automation.client.rest.api; 019 020import java.util.regex.Matcher; 021import java.util.regex.Pattern; 022 023import org.apache.http.impl.client.BasicCookieStore; 024import org.nuxeo.ecm.automation.client.jaxrs.impl.HttpAutomationClient; 025 026import com.sun.jersey.api.client.WebResource; 027import com.sun.jersey.client.apache4.ApacheHttpClient4; 028import com.sun.jersey.client.apache4.ApacheHttpClient4Handler; 029 030/** 031 * REST client used to to requests on the Nuxeo REST API. 032 * 033 * @since 5.8 034 */ 035public class RestClient { 036 037 protected static final String SITE_AUTOMATION_PATH_PATTERN = "(\\/api\\/v1)?(\\/site)?\\/automation"; 038 039 private static final Pattern SITE_AUTOMATION_PATH_PATTERN_COMPILED = Pattern.compile(SITE_AUTOMATION_PATH_PATTERN, 040 Pattern.CASE_INSENSITIVE); 041 042 protected static final String API_PATH = "/api/v1"; 043 044 WebResource service; 045 046 public RestClient(HttpAutomationClient httpAutomationClient) { 047 ApacheHttpClient4Handler handler = new ApacheHttpClient4Handler(httpAutomationClient.http(), 048 new BasicCookieStore(), false); 049 ApacheHttpClient4 client = new ApacheHttpClient4(handler); 050 051 if (httpAutomationClient.getRequestInterceptor() != null) { 052 client.addFilter(httpAutomationClient.getRequestInterceptor()); 053 } 054 055 String apiURL = httpAutomationClient.getBaseUrl(); 056 apiURL = replaceAutomationEndpoint(apiURL); 057 service = client.resource(apiURL); 058 } 059 060 private String replaceAutomationEndpoint(String url) { 061 Matcher matcher = SITE_AUTOMATION_PATH_PATTERN_COMPILED.matcher(url); 062 return matcher.replaceAll(API_PATH); 063 } 064 065 public RestRequest newRequest(String path) { 066 return new RestRequest(service, path); 067 } 068 069}