001/* 002 * (C) Copyright 2013 Nuxeo SA (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.client.rest.api; 021 022import java.util.regex.Matcher; 023import java.util.regex.Pattern; 024 025import org.apache.http.impl.client.BasicCookieStore; 026import org.nuxeo.ecm.automation.client.jaxrs.impl.HttpAutomationClient; 027 028import com.sun.jersey.api.client.WebResource; 029import com.sun.jersey.client.apache4.ApacheHttpClient4; 030import com.sun.jersey.client.apache4.ApacheHttpClient4Handler; 031 032/** 033 * REST client used to to requests on the Nuxeo REST API. 034 * 035 * @since 5.8 036 */ 037public class RestClient { 038 039 protected static final String SITE_AUTOMATION_PATH_PATTERN = "(\\/api\\/v1)?(\\/site)?\\/automation"; 040 041 private static final Pattern SITE_AUTOMATION_PATH_PATTERN_COMPILED = Pattern.compile(SITE_AUTOMATION_PATH_PATTERN, 042 Pattern.CASE_INSENSITIVE); 043 044 protected static final String API_PATH = "/api/v1"; 045 046 WebResource service; 047 048 public RestClient(HttpAutomationClient httpAutomationClient) { 049 ApacheHttpClient4Handler handler = new ApacheHttpClient4Handler(httpAutomationClient.http(), 050 new BasicCookieStore(), false); 051 ApacheHttpClient4 client = new ApacheHttpClient4(handler); 052 053 if (httpAutomationClient.getRequestInterceptor() != null) { 054 client.addFilter(httpAutomationClient.getRequestInterceptor()); 055 } 056 057 String apiURL = httpAutomationClient.getBaseUrl(); 058 apiURL = replaceAutomationEndpoint(apiURL); 059 service = client.resource(apiURL); 060 } 061 062 private String replaceAutomationEndpoint(String url) { 063 Matcher matcher = SITE_AUTOMATION_PATH_PATTERN_COMPILED.matcher(url); 064 return matcher.replaceAll(API_PATH); 065 } 066 067 public RestRequest newRequest(String path) { 068 return new RestRequest(service, path); 069 } 070 071}