merge with branch issue-709

This commit is contained in:
Sebastian Sdorra
2015-05-17 14:06:43 +02:00
47 changed files with 5013 additions and 101 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

@@ -74,7 +74,9 @@ import sonia.scm.util.HttpUtil;
/**
*
* @author Sebastian Sdorra
* @deprecated use {@link sonia.scm.net.ahc.AdvancedHttpClient}
*/
@Deprecated
public class URLHttpClient implements HttpClient
{

View File

@@ -0,0 +1,398 @@
/**
* 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.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
*/
@Inject
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
* 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);
}
}
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;
}

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,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);
}
}

View File

@@ -40,21 +40,18 @@ import com.google.common.collect.ImmutableSet.Builder;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.ConfigChangedListener;
import sonia.scm.ConfigurationException;
import sonia.scm.SCMContext;
import sonia.scm.SCMContextProvider;
import sonia.scm.cache.Cache;
import sonia.scm.cache.CacheManager;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.io.ZipUnArchiver;
import sonia.scm.net.HttpClient;
import sonia.scm.util.AssertUtil;
import sonia.scm.util.IOUtil;
import sonia.scm.util.SecurityUtil;
@@ -79,9 +76,7 @@ import java.util.Map;
import java.util.Set;
import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import sonia.scm.net.ahc.AdvancedHttpClient;
/**
*
@@ -122,18 +117,18 @@ public class DefaultPluginManager
* @param configuration
* @param pluginLoader
* @param cacheManager
* @param clientProvider
* @param httpClient
*/
@Inject
public DefaultPluginManager(SCMContextProvider context,
ScmConfiguration configuration, PluginLoader pluginLoader,
CacheManager cacheManager, Provider<HttpClient> clientProvider)
CacheManager cacheManager, AdvancedHttpClient httpClient)
{
this.context = context;
this.configuration = configuration;
this.cache = cacheManager.getCache(String.class, PluginCenter.class,
CACHE_NAME);
this.clientProvider = clientProvider;
this.httpClient = httpClient;
installedPlugins = new HashMap<String, Plugin>();
for (Plugin plugin : pluginLoader.getInstalledPlugins())
@@ -146,16 +141,6 @@ public class DefaultPluginManager
}
}
try
{
unmarshaller =
JAXBContext.newInstance(PluginCenter.class).createUnmarshaller();
}
catch (JAXBException ex)
{
throw new ConfigurationException(ex);
}
File file = findAdvancedConfiguration();
if (file.exists())
@@ -654,21 +639,9 @@ public class DefaultPluginManager
if (Util.isNotEmpty(pluginUrl))
{
InputStream input = null;
try
{
input = clientProvider.get().get(pluginUrl).getContent();
/*
* TODO: add gzip support
*
* if (gzip)
* {
* input = new GZIPInputStream(input);
* }
*/
center = (PluginCenter) unmarshaller.unmarshal(input);
center = httpClient.get(pluginUrl).request().contentFromXml(PluginCenter.class);
preparePlugins(center);
cache.put(PluginCenter.class.getName(), center);
@@ -690,10 +663,6 @@ public class DefaultPluginManager
{
logger.error("could not load plugins from plugin center", ex);
}
finally
{
IOUtil.close(input);
}
}
if (center == null)
@@ -794,7 +763,7 @@ public class DefaultPluginManager
private Cache<String, PluginCenter> cache;
/** Field description */
private Provider<HttpClient> clientProvider;
private AdvancedHttpClient httpClient;
/** Field description */
private ScmConfiguration configuration;
@@ -807,7 +776,4 @@ public class DefaultPluginManager
/** Field description */
private AetherPluginHandler pluginHandler;
/** Field description */
private Unmarshaller unmarshaller;
}