001package ca.uhn.fhir.rest.client.apache; 002 003/* 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2017 University Health Network 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import java.io.ByteArrayOutputStream; 024import java.io.IOException; 025import java.util.zip.GZIPOutputStream; 026 027import org.apache.http.Header; 028import org.apache.http.HttpEntityEnclosingRequest; 029import org.apache.http.client.methods.HttpRequestBase; 030import org.apache.http.entity.ByteArrayEntity; 031 032import ca.uhn.fhir.rest.client.IClientInterceptor; 033import ca.uhn.fhir.rest.client.api.IHttpRequest; 034import ca.uhn.fhir.rest.client.api.IHttpResponse; 035import ca.uhn.fhir.rest.server.Constants; 036 037/** 038 * Client interceptor which GZip compresses outgoing (POST/PUT) contents being uploaded 039 * from the client to the server. This can improve performance by reducing network 040 * load time. 041 */ 042public class GZipContentInterceptor implements IClientInterceptor { 043 private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(GZipContentInterceptor.class); 044 045 @Override 046 public void interceptRequest(IHttpRequest theRequestInterface) { 047 HttpRequestBase theRequest = ((ApacheHttpRequest) theRequestInterface).getApacheRequest(); 048 if (theRequest instanceof HttpEntityEnclosingRequest) { 049 Header[] encodingHeaders = theRequest.getHeaders(Constants.HEADER_CONTENT_ENCODING); 050 if (encodingHeaders == null || encodingHeaders.length == 0) { 051 HttpEntityEnclosingRequest req = (HttpEntityEnclosingRequest)theRequest; 052 053 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 054 GZIPOutputStream gos; 055 try { 056 gos = new GZIPOutputStream(bos); 057 req.getEntity().writeTo(gos); 058 gos.finish(); 059 } catch (IOException e) { 060 ourLog.warn("Failed to GZip outgoing content", e); 061 return; 062 } 063 064 byte[] byteArray = bos.toByteArray(); 065 ByteArrayEntity newEntity = new ByteArrayEntity(byteArray); 066 req.setEntity(newEntity); 067 req.addHeader(Constants.HEADER_CONTENT_ENCODING, "gzip"); 068 } 069 } 070 071 } 072 073 @Override 074 public void interceptResponse(IHttpResponse theResponse) throws IOException { 075 // nothing 076 } 077 078}