merge with branch 1.x

This commit is contained in:
Sebastian Sdorra
2017-01-12 19:50:39 +01:00
250 changed files with 16399 additions and 1573 deletions

View File

@@ -0,0 +1,89 @@
/**
* 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;
import com.google.common.base.Throwables;
import com.google.inject.Inject;
import java.security.NoSuchAlgorithmException;
import javax.inject.Named;
import javax.inject.Provider;
import javax.net.ssl.SSLContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provider for {@link SSLContext}. The provider will first try to retrieve the {@link SSLContext} from an "default"
* named optional provider, if this fails the provider will return the jvm default context.
*
* @author Sebastian Sdorra
* @version 1.47
*/
public final class SSLContextProvider implements Provider<SSLContext>
{
/**
* the logger for SSLContextProvider
*/
private static final Logger logger = LoggerFactory.getLogger(SSLContextProvider.class);
@Named("default")
@Inject(optional = true)
private Provider<SSLContext> sslContextProvider;
@Override
public SSLContext get()
{
SSLContext context = null;
if (sslContextProvider != null)
{
context = sslContextProvider.get();
}
if (context == null)
{
try
{
logger.trace("could not find ssl context provider, use jvm default");
context = SSLContext.getDefault();
}
catch (NoSuchAlgorithmException ex)
{
throw Throwables.propagate(ex);
}
}
else
{
logger.trace("use custom ssl context from provider");
}
return context;
}
}

View File

@@ -48,8 +48,10 @@ import sonia.scm.util.Util;
//~--- JDK imports ------------------------------------------------------------
import com.sun.jersey.core.util.Base64;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
@@ -67,11 +69,14 @@ import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import sonia.scm.util.HttpUtil;
/**
*
* @author Sebastian Sdorra
* @deprecated use {@link sonia.scm.net.ahc.AdvancedHttpClient}
*/
@Deprecated
public class URLHttpClient implements HttpClient
{
@@ -152,6 +157,9 @@ public class URLHttpClient implements HttpClient
url);
connection.setRequestMethod(METHOD_POST);
// send empty content-length
// see issue #701 http://goo.gl/oyTdrA
setContentLength(connection, 0);
return new URLHttpResponse(connection);
}
@@ -347,41 +355,85 @@ public class URLHttpClient implements HttpClient
{
if (Util.isNotEmpty(parameters))
{
// use a ByteArrayOutputStream in order to get the final content-length
// see issue #701 http://goo.gl/oyTdrA
connection.setDoOutput(true);
OutputStreamWriter writer = null;
ByteArrayOutputStream baos = null;
try
{
writer = new OutputStreamWriter(connection.getOutputStream());
baos = new ByteArrayOutputStream();
writer = new OutputStreamWriter(baos);
Iterator<Map.Entry<String, List<String>>> it =
parameters.entrySet().iterator();
while (it.hasNext())
{
Map.Entry<String, List<String>> p = it.next();
List<String> values = p.getValue();
if (Util.isNotEmpty(values))
{
String key = encode(p.getKey());
for (String value : values)
{
writer.append(key).append("=").append(encode(value));
}
if (it.hasNext())
{
writer.write("&");
}
}
}
appendPostParameters(writer, parameters);
}
finally
{
IOUtil.close(writer);
IOUtil.close(baos);
}
if ( baos != null ){
byte[] data = baos.toByteArray();
appendBody(connection, data);
}
}
else
{
setContentLength(connection, 0);
}
}
private void appendBody(HttpURLConnection connection, byte[] body) throws IOException
{
int length = body.length;
logger.trace("write {} bytes to output", length);
setContentLength(connection, length);
connection.setFixedLengthStreamingMode(length);
OutputStream os = null;
try {
os = connection.getOutputStream();
os.write(body);
} finally {
IOUtil.close(os);
}
}
private void setContentLength(HttpURLConnection connection, int length)
{
connection.setRequestProperty(HttpUtil.HEADER_CONTENT_LENGTH, String.valueOf(length));
}
private void appendPostParameters(OutputStreamWriter writer, Map<String, List<String>> parameters) throws IOException
{
Iterator<Map.Entry<String, List<String>>> it = parameters.entrySet().iterator();
while (it.hasNext())
{
Map.Entry<String, List<String>> p = it.next();
List<String> values = p.getValue();
if (Util.isNotEmpty(values))
{
String key = encode(p.getKey());
Iterator<String> valueIt = values.iterator();
while(valueIt.hasNext())
{
String value = valueIt.next();
writer.append(key).append("=").append(encode(value));
if ( valueIt.hasNext() ){
writer.write("&");
}
}
if (it.hasNext())
{
writer.write("&");
}
}
}
}

View File

@@ -0,0 +1,409 @@
/**
* 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.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.collect.Multimap;
import com.google.common.io.Closeables;
import com.google.inject.Inject;
import org.apache.shiro.codec.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.net.Proxies;
import sonia.scm.net.TrustAllHostnameVerifier;
import sonia.scm.net.TrustAllTrustManager;
import sonia.scm.util.HttpUtil;
//~--- JDK imports ------------------------------------------------------------
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Set;
import javax.inject.Provider;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
/**
* Default implementation of the {@link AdvancedHttpClient}. The default
* implementation uses {@link HttpURLConnection}.
*
* @author Sebastian Sdorra
* @since 1.46
*/
public class DefaultAdvancedHttpClient extends AdvancedHttpClient
{
/** proxy authorization header */
@VisibleForTesting
static final String HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization";
/** connection timeout */
@VisibleForTesting
static final int TIMEOUT_CONNECTION = 30000;
/** read timeout */
@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
*/
private static final Logger logger =
LoggerFactory.getLogger(DefaultAdvancedHttpClient.class);
//~--- constructors ---------------------------------------------------------
/**
* Constructs a new {@link DefaultAdvancedHttpClient}.
*
*
* @param configuration scm-manager main configuration
* @param contentTransformers content transformer
* @param sslContextProvider ssl context provider
*/
@Inject
public DefaultAdvancedHttpClient(ScmConfiguration configuration,
Set<ContentTransformer> contentTransformers, Provider<SSLContext> sslContextProvider)
{
this.configuration = configuration;
this.contentTransformers = contentTransformers;
this.sslContextProvider = sslContextProvider;
}
//~--- methods --------------------------------------------------------------
/**
* Creates a new {@link HttpURLConnection} from the given {@link URL}. The
* method is visible for testing.
*
*
* @param url url
*
* @return new {@link HttpURLConnection}
*
* @throws IOException
*/
@VisibleForTesting
protected HttpURLConnection createConnection(URL url) throws IOException
{
return (HttpURLConnection) url.openConnection();
}
/**
* Creates a new proxy {@link HttpURLConnection} from the given {@link URL}
* and {@link SocketAddress}. The method is visible for testing.
*
*
* @param url url
* @param address proxy socket address
*
* @return new proxy {@link HttpURLConnection}
*
* @throws IOException
*/
@VisibleForTesting
protected HttpURLConnection createProxyConnecton(URL url,
SocketAddress address)
throws IOException
{
return (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP,
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.
*
*
* @param request http request
*
* @return server response
*
* @throws IOException
*/
@Override
protected AdvancedHttpResponse request(BaseHttpRequest<?> request)
throws IOException
{
HttpURLConnection connection = openConnection(request,
new URL(request.getUrl()));
applyBaseSettings(request, connection);
if (connection instanceof HttpsURLConnection)
{
applySSLSettings(request, (HttpsURLConnection) connection);
}
Content content = null;
if (request instanceof AdvancedHttpRequestWithBody)
{
AdvancedHttpRequestWithBody ahrwb = (AdvancedHttpRequestWithBody) request;
content = ahrwb.getContent();
if (content != null)
{
content.prepare(ahrwb);
}
else
{
request.header(HttpUtil.HEADER_CONTENT_LENGTH, "0");
}
}
else
{
request.header(HttpUtil.HEADER_CONTENT_LENGTH, "0");
}
applyHeaders(request, connection);
if (content != null)
{
applyContent(connection, content);
}
return new DefaultAdvancedHttpResponse(this, connection,
connection.getResponseCode(), connection.getResponseMessage());
}
private void appendProxyAuthentication(HttpURLConnection connection)
{
String username = configuration.getProxyUser();
String password = configuration.getProxyPassword();
if (!Strings.isNullOrEmpty(username) ||!Strings.isNullOrEmpty(password))
{
logger.debug("append proxy authentication header for user {}", username);
String auth = username.concat(CREDENTIAL_SEPARATOR).concat(password);
auth = Base64.encodeToString(auth.getBytes());
connection.addRequestProperty(HEADER_PROXY_AUTHORIZATION,
PREFIX_BASIC_AUTHENTICATION.concat(auth));
}
}
private void applyBaseSettings(BaseHttpRequest<?> request,
HttpURLConnection connection)
throws ProtocolException
{
connection.setRequestMethod(request.getMethod());
connection.setReadTimeout(TIMEOUT_RAED);
connection.setConnectTimeout(TIMEOUT_CONNECTION);
}
private void applyContent(HttpURLConnection connection, Content content)
throws IOException
{
connection.setDoOutput(true);
OutputStream output = null;
try
{
output = connection.getOutputStream();
content.process(output);
}
finally
{
Closeables.close(output, true);
}
}
private void applyHeaders(BaseHttpRequest<?> request,
HttpURLConnection connection)
{
Multimap<String, String> headers = request.getHeaders();
for (String key : headers.keySet())
{
for (String value : headers.get(key))
{
connection.addRequestProperty(key, value);
}
}
}
private void applySSLSettings(BaseHttpRequest<?> request,
HttpsURLConnection connection)
{
if (request.isDisableCertificateValidation())
{
logger.trace("disable certificate validation");
try
{
TrustManager[] trustAllCerts = new TrustManager[] {
new TrustAllTrustManager() };
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
connection.setSSLSocketFactory(sc.getSocketFactory());
}
catch (KeyManagementException ex)
{
logger.error("could not disable certificate validation", ex);
}
catch (NoSuchAlgorithmException ex)
{
logger.error("could not disable certificate validation", ex);
}
}
else
{
logger.trace("set ssl socker factory from provider");
connection.setSSLSocketFactory(sslContextProvider.get().getSocketFactory());
}
if (request.isDisableHostnameValidation())
{
logger.trace("disable hostname validation");
connection.setHostnameVerifier(new TrustAllHostnameVerifier());
}
}
private HttpURLConnection openConnection(BaseHttpRequest<?> request, URL url)
throws IOException
{
HttpURLConnection connection;
if (isProxyEnabled(request))
{
connection = openProxyConnection(request, url);
appendProxyAuthentication(connection);
}
else
{
if (request.isIgnoreProxySettings())
{
logger.trace("ignore proxy settings");
}
logger.debug("fetch {}", url.toExternalForm());
connection = createConnection(url);
}
return connection;
}
private HttpURLConnection openProxyConnection(BaseHttpRequest<?> request,
URL url)
throws IOException
{
if (logger.isDebugEnabled())
{
logger.debug("fetch '{}' using proxy {}:{}", url.toExternalForm(),
configuration.getProxyServer(), configuration.getProxyPort());
}
SocketAddress address =
new InetSocketAddress(configuration.getProxyServer(),
configuration.getProxyPort());
return createProxyConnecton(url, address);
}
//~--- get methods ----------------------------------------------------------
private boolean isProxyEnabled(BaseHttpRequest<?> request)
{
return !request.isIgnoreProxySettings()
&& Proxies.isEnabled(configuration, request.getUrl());
}
//~--- fields ---------------------------------------------------------------
/** scm-manager main configuration */
private final ScmConfiguration configuration;
/** set of content transformers */
private final Set<ContentTransformer> contentTransformers;
/** ssl context provider */
private final Provider<SSLContext> sslContextProvider;
}

View File

@@ -0,0 +1,226 @@
/**
* 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.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//~--- JDK imports ------------------------------------------------------------
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map.Entry;
/**
* Http server response object of {@link DefaultAdvancedHttpClient}.
*
* @author Sebastian Sdorra
* @since 1.46
*/
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(DefaultAdvancedHttpClient client,
HttpURLConnection connection, int status, String statusText)
{
this.client = client;
this.connection = connection;
this.status = status;
this.statusText = statusText;
}
//~--- methods --------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public ByteSource contentAsByteSource() throws IOException
{
return new URLConnectionByteSource(connection);
}
//~--- get methods ----------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Multimap<String, String> getHeaders()
{
if (headers == null)
{
headers = LinkedHashMultimap.create();
for (Entry<String, List<String>> e :
connection.getHeaderFields().entrySet())
{
headers.putAll(e.getKey(), e.getValue());
}
}
return headers;
}
/**
* {@inheritDoc}
*/
@Override
public int getStatus()
{
return status;
}
/**
* {@inheritDoc}
*/
@Override
public String getStatusText()
{
return statusText;
}
//~--- methods --------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
protected ContentTransformer createTransformer(Class<?> type,
String contentType)
{
return client.createTransformer(type, contentType);
}
//~--- inner classes --------------------------------------------------------
/**
* {@link ByteSource} implementation of a http connection.
*/
private static class URLConnectionByteSource extends ByteSource
{
/**
* the logger for URLConnectionByteSource
*/
private static final Logger logger =
LoggerFactory.getLogger(URLConnectionByteSource.class);
//~--- constructors -------------------------------------------------------
/**
* Constructs a new {@link URLConnectionByteSource}.
*
*
* @param connection http connection
*/
private URLConnectionByteSource(HttpURLConnection connection)
{
this.connection = connection;
}
//~--- methods ------------------------------------------------------------
/**
* Opens the input stream of http connection, if an error occurs during
* opening the method will return the error stream instead.
*
*
* @return input or error stream of http connection
*
* @throws IOException
*/
@Override
public InputStream openStream() throws IOException
{
InputStream stream;
try
{
stream = connection.getInputStream();
}
catch (IOException ex)
{
if (logger.isDebugEnabled())
{
logger.debug(
"could not open input stream, open error stream instead", ex);
}
stream = connection.getErrorStream();
}
return stream;
}
//~--- fields -------------------------------------------------------------
/** http connection */
private final HttpURLConnection connection;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private final DefaultAdvancedHttpClient client;
/** http connection */
private final HttpURLConnection connection;
/** server response status */
private final int status;
/** server response text */
private final String statusText;
/** http headers */
private Multimap<String, String> headers;
}

View File

@@ -0,0 +1,157 @@
/**
* 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.AnnotationIntrospector;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
import sonia.scm.plugin.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;
/**
* {@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
{
/**
* Constructs a new {@link JsonContentTransformer}.
*
*/
public JsonContentTransformer()
{
this.mapper = new ObjectMapper();
// allow jackson and jaxb annotations
AnnotationIntrospector jackson = new JacksonAnnotationIntrospector();
AnnotationIntrospector jaxb = new JaxbAnnotationIntrospector();
this.mapper.setAnnotationIntrospector(new AnnotationIntrospector.Pair(jackson, jaxb));
// do not fail on unknown json properties
this.mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
//~--- methods --------------------------------------------------------------
/**
* {@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.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);
}
}