added json and xml support to ahc

This commit is contained in:
Sebastian Sdorra
2015-05-03 15:51:21 +02:00
parent 722d2616a8
commit 1f4524bb20
19 changed files with 1222 additions and 81 deletions

View File

@@ -157,6 +157,11 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import sonia.scm.net.ahc.AdvancedHttpClient;
import sonia.scm.net.ahc.ContentTransformer;
import sonia.scm.net.ahc.DefaultAdvancedHttpClient;
import sonia.scm.net.ahc.JsonContentTransformer;
import sonia.scm.net.ahc.XmlContentTransformer;
import sonia.scm.web.UserAgentParser;
/**
@@ -219,7 +224,7 @@ public class ScmServletModule extends ServletModule
PATTERN_STYLESHEET, "*.json", "*.xml", "*.txt" };
/** Field description */
private static Logger logger =
private static final Logger logger =
LoggerFactory.getLogger(ScmServletModule.class);
//~--- constructors ---------------------------------------------------------
@@ -315,6 +320,13 @@ public class ScmServletModule extends ServletModule
// bind httpclient
bind(HttpClient.class, URLHttpClient.class);
// bind ahc
Multibinder<ContentTransformer> transformers =
Multibinder.newSetBinder(binder(), ContentTransformer.class);
transformers.addBinding().to(XmlContentTransformer.class);
transformers.addBinding().to(JsonContentTransformer.class);
bind(AdvancedHttpClient.class).to(DefaultAdvancedHttpClient.class);
// bind resourcemanager
if (context.getStage() == Stage.DEVELOPMENT)

View File

@@ -65,12 +65,14 @@ import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
/**
* Default implementation of the {@link AdvancedHttpClient}. The default
* Default implementation of the {@link AdvancedHttpClient}. The default
* implementation uses {@link HttpURLConnection}.
*
* @author Sebastian Sdorra
@@ -79,16 +81,10 @@ import javax.net.ssl.TrustManager;
public class DefaultAdvancedHttpClient extends AdvancedHttpClient
{
/** credential separator */
private static final String CREDENTIAL_SEPARATOR = ":";
/** proxy authorization header */
@VisibleForTesting
static final String HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization";
/** basic authentication prefix */
private static final String PREFIX_BASIC_AUTHENTICATION = "Basic ";
/** connection timeout */
@VisibleForTesting
static final int TIMEOUT_CONNECTION = 30000;
@@ -97,6 +93,12 @@ public class DefaultAdvancedHttpClient extends AdvancedHttpClient
@VisibleForTesting
static final int TIMEOUT_RAED = 1200000;
/** credential separator */
private static final String CREDENTIAL_SEPARATOR = ":";
/** basic authentication prefix */
private static final String PREFIX_BASIC_AUTHENTICATION = "Basic ";
/**
* the logger for DefaultAdvancedHttpClient
*/
@@ -110,17 +112,20 @@ public class DefaultAdvancedHttpClient extends AdvancedHttpClient
*
*
* @param configuration scm-manager main configuration
* @param contentTransformers content transformer
*/
@Inject
public DefaultAdvancedHttpClient(ScmConfiguration configuration)
public DefaultAdvancedHttpClient(ScmConfiguration configuration,
Set<ContentTransformer> contentTransformers)
{
this.configuration = configuration;
this.contentTransformers = contentTransformers;
}
//~--- methods --------------------------------------------------------------
/**
* Creates a new {@link HttpURLConnection} from the given {@link URL}. The
* Creates a new {@link HttpURLConnection} from the given {@link URL}. The
* method is visible for testing.
*
*
@@ -157,6 +162,34 @@ public class DefaultAdvancedHttpClient extends AdvancedHttpClient
address));
}
/**
* {@inheritDoc}
*/
@Override
protected ContentTransformer createTransformer(Class<?> type, String contentType)
{
ContentTransformer responsible = null;
for (ContentTransformer transformer : contentTransformers)
{
if (transformer.isResponsible(type, contentType))
{
responsible = transformer;
break;
}
}
if (responsible == null)
{
throw new ContentTransformerNotFoundException(
"could not find content transformer for content type ".concat(
contentType));
}
return responsible;
}
/**
* Executes the given request and returns the server response.
*
@@ -210,7 +243,7 @@ public class DefaultAdvancedHttpClient extends AdvancedHttpClient
applyContent(connection, content);
}
return new DefaultAdvancedHttpResponse(connection,
return new DefaultAdvancedHttpResponse(this, connection,
connection.getResponseCode(), connection.getResponseMessage());
}
@@ -359,4 +392,7 @@ public class DefaultAdvancedHttpClient extends AdvancedHttpClient
/** scm-manager main configuration */
private final ScmConfiguration configuration;
/** set of content transformers */
private final Set<ContentTransformer> contentTransformers;
}

View File

@@ -62,14 +62,15 @@ public class DefaultAdvancedHttpResponse extends AdvancedHttpResponse
/**
* Constructs a new {@link DefaultAdvancedHttpResponse}.
*
*
* @param client ahc
* @param connection http connection
* @param status response status code
* @param statusText response status text
*/
DefaultAdvancedHttpResponse(HttpURLConnection connection, int status,
String statusText)
DefaultAdvancedHttpResponse(DefaultAdvancedHttpClient client,
HttpURLConnection connection, int status, String statusText)
{
this.client = client;
this.connection = connection;
this.status = status;
this.statusText = statusText;
@@ -126,6 +127,18 @@ public class DefaultAdvancedHttpResponse extends AdvancedHttpResponse
return statusText;
}
//~--- methods --------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
protected ContentTransformer createTransformer(Class<?> type,
String contentType)
{
return client.createTransformer(type, contentType);
}
//~--- inner classes --------------------------------------------------------
/**
@@ -196,6 +209,9 @@ public class DefaultAdvancedHttpResponse extends AdvancedHttpResponse
//~--- fields ---------------------------------------------------------------
/** Field description */
private final DefaultAdvancedHttpClient client;
/** http connection */
private final HttpURLConnection connection;

View File

@@ -0,0 +1,149 @@
/**
* Copyright (c) 2014, Sebastian Sdorra All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. 2. Redistributions in
* binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution. 3. Neither the name of SCM-Manager;
* nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.net.ahc;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.io.ByteSource;
import org.codehaus.jackson.map.ObjectMapper;
import sonia.scm.plugin.ext.Extension;
import sonia.scm.util.IOUtil;
//~--- JDK imports ------------------------------------------------------------
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.core.MediaType;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
/**
* {@link ContentTransformer} for json. The {@link JsonContentTransformer} uses
* jacksons {@link ObjectMapper} to marshalling/unmarshalling.
*
* @author Sebastian Sdorra
* @since 1.46
*/
@Extension
public class JsonContentTransformer implements ContentTransformer
{
public JsonContentTransformer()
{
this.mapper = new ObjectMapper();
AnnotationIntrospector jackson = new JacksonAnnotationIntrospector();
AnnotationIntrospector jaxb = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospector.Pair(jackson, jaxb);
this.mapper.setAnnotationIntrospector(pair);
}
/**
* {@inheritDoc}
*/
@Override
public ByteSource marshall(Object object)
{
ByteSource source = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
mapper.writeValue(baos, object);
source = ByteSource.wrap(baos.toByteArray());
}
catch (IOException ex)
{
throw new ContentTransformerException("could not marshall object", ex);
}
return source;
}
/**
* {@inheritDoc}
*/
@Override
public <T> T unmarshall(Class<T> type, ByteSource content)
{
T object = null;
InputStream stream = null;
try
{
stream = content.openBufferedStream();
object = mapper.readValue(stream, type);
}
catch (IOException ex)
{
throw new ContentTransformerException("could not unmarshall content", ex);
}
finally
{
IOUtil.close(stream);
}
return object;
}
//~--- get methods ----------------------------------------------------------
/**
* Returns {@code true}, if the content type is compatible with
* application/json.
*
*
* @param type object type
* @param contentType content type
*
* @return {@code true}, if the content type is compatible with
* application/json
*/
@Override
public boolean isResponsible(Class<?> type, String contentType)
{
return MediaType.valueOf(contentType).isCompatible(
MediaType.APPLICATION_JSON_TYPE);
}
//~--- fields ---------------------------------------------------------------
/** object mapper */
private final ObjectMapper mapper;
}

View File

@@ -0,0 +1,134 @@
/**
* Copyright (c) 2014, Sebastian Sdorra All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. 2. Redistributions in
* binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution. 3. Neither the name of SCM-Manager;
* nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.net.ahc;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.io.ByteSource;
import sonia.scm.plugin.ext.Extension;
import sonia.scm.util.IOUtil;
//~--- JDK imports ------------------------------------------------------------
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.DataBindingException;
import javax.xml.bind.JAXB;
/**
* {@link ContentTransformer} for xml. The {@link XmlContentTransformer} uses
* jaxb to marshalling/unmarshalling.
*
* @author Sebastian Sdorra
* @since 1.46
*/
@Extension
public class XmlContentTransformer implements ContentTransformer
{
/**
* {@inheritDoc}
*/
@Override
public ByteSource marshall(Object object)
{
ByteSource source = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
JAXB.marshal(object, baos);
source = ByteSource.wrap(baos.toByteArray());
}
catch (DataBindingException ex)
{
throw new ContentTransformerException("could not marshall object", ex);
}
return source;
}
/**
* {@inheritDoc}
*/
@Override
public <T> T unmarshall(Class<T> type, ByteSource content)
{
T object = null;
InputStream stream = null;
try
{
stream = content.openBufferedStream();
object = JAXB.unmarshal(stream, type);
}
catch (IOException ex)
{
throw new ContentTransformerException("could not unmarshall content", ex);
}
catch (DataBindingException ex)
{
throw new ContentTransformerException("could not unmarshall content", ex);
}
finally
{
IOUtil.close(stream);
}
return object;
}
//~--- get methods ----------------------------------------------------------
/**
* Returns {@code true}, if the content type is compatible with
* application/xml.
*
*
* @param type object type
* @param contentType content type
*
* @return {@code true}, if the content type is compatible with
* application/xml
*/
@Override
public boolean isResponsible(Class<?> type, String contentType)
{
return MediaType.valueOf(contentType).isCompatible(
MediaType.APPLICATION_XML_TYPE);
}
}