Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (C) 2011 BonitaSoft S.A. BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 package org.bonitasoft.engine.api;
 import java.util.List;
 import java.util.Map;

Baptiste Mesta
Julien Mege
Elias Ricken de Medeiros
Celine Souchet
 public class HTTPServerAPI implements ServerAPI {
     private static final String UTF_8 = "UTF-8";
     private static final String CLASS_NAME_PARAMETERS = "classNameParameters";
     private static final String OPTIONS = "options";
     private static final String PARAMETERS_VALUES = "parametersValues";
     private static final String BINARY_PARAMETER = "binaryParameter";
     private static final String BYTE_ARRAY = "==ByteArray==";
     private static final char SLASH = '/';
     private static final String SERVER_API = "/serverAPI/";
     private static final long serialVersionUID = 1L;
     private static final String SERVER_URL = "server.url";
     private static final String BASIC_AUTHENTICATION_ACTIVE = "";
     private static final String BASIC_AUTHENTICATION_USERNAME = "basicAuthentication.username";
     private static final String BASIC_AUTHENTICATION_PASSWORD = "basicAuthentication.password";
     private static final String APPLICATION_NAME = "";
     private static final Logger LOGGER = Logger.getLogger(HTTPServerAPI.class.getName());
     private String serverUrl = null;
     private String applicationName = null;
     private boolean basicAuthenticationActive = false;
     private String basicAuthenticationUserName = null;
    private String basicAuthenticationPassword = null;
    private static DefaultHttpClient httpclient;
    private static final XStream xstream;
    private static final ResponseHandler<StringresponseHandler = new BonitaResponseHandler();
    static {
         = new XStream();
    public HTTPServerAPI(final Map<StringStringparameters) {
        // initialize httpclient in the constructor to avoid incompatibility when running tests:
        // class configured for SSLContext:$TLS10Context not a SSLContext
        if ( == null) {
             = new DefaultHttpClient(new PoolingClientConnectionManager());
         = parameters.get();
         = parameters.get();
    public Object invokeMethod(final Map<StringSerializableoptionsfinal String apiInterfaceNamefinal String methodName,
            final List<StringclassNameParametersfinal Object[] parametersValuesthrows ServerWrappedException {
        String response = null;
        try {
            response = executeHttpPost(optionsapiInterfaceNamemethodNameclassNameParametersparametersValues);
            return checkInvokeMethodReturn(response);
        } catch (final UndeclaredThrowableException e) {
            if (.isLoggable(.)) {
                .log(.e.getMessage(), e);
            throw new ServerWrappedException(e);
        } catch (final Throwable e) {
            throw new ServerWrappedException(e.getMessage() + "response= " + responsee);
    private Object checkInvokeMethodReturn(final String responsefinal XStream xstreamthrows Throwable {
        Object invokeMethodReturn = null;
        if (response != null && !response.isEmpty() && !response.equals("null")) {
            invokeMethodReturn = fromXML(responsexstream);
            if (invokeMethodReturn instanceof Throwable) {
                throw (ThrowableinvokeMethodReturn;
        return invokeMethodReturn;
    private String executeHttpPost(final Map<StringSerializableoptionsfinal String apiInterfaceNamefinal String methodName,
            final List<StringclassNameParametersfinal Object[] parametersValuesfinal XStream xstreamthrows UnsupportedEncodingExceptionIOException,
            ClientProtocolException {
        final HttpPost httpost = createHttpPost(optionsapiInterfaceNamemethodNameclassNameParametersparametersValuesxstream);
        return .execute(httpost);
    private HttpPost createHttpPost(final Map<StringSerializableoptionsfinal String apiInterfaceNamefinal String methodName,
            final List<StringclassNameParametersfinal Object[] parametersValuesfinal XStream xstreamthrows UnsupportedEncodingExceptionIOException {
        final HttpEntity httpEntity = buildEntity(optionsclassNameParametersparametersValuesxstream);
        final StringBuilder sBuilder = new StringBuilder();
        final HttpPost httpost = new HttpPost(sBuilder.toString());
        // Basic authentication
        if () {
            StringBuilder credentials = new StringBuilder();
            Base64 encoder = new Base64();
            String encodedCredentials = encoder.encodeAsString(credentials.toString().getBytes());
            httpost.setHeader("Authorization""Basic " + encodedCredentials);
        return httpost;
    private HttpEntity buildEntity(final Map<StringSerializableoptionsfinal List<StringclassNameParametersfinal Object[] parametersValues,
            final XStream xstreamthrows UnsupportedEncodingExceptionIOException {
        final HttpEntity httpEntity;
         * if we have a business archive we use multipart to have the business archive attached as a binary content (it can be big)
        if (classNameParameters.contains(BusinessArchive.class.getName()) || classNameParameters.contains(byte[].class.getName())) {
            final List<ObjectbytearrayParameters = new ArrayList<Object>();
            final MultipartEntity entity = new MultipartEntity();
            entity.addPart(new StringBody(toXML(optionsxstream)));
            entity.addPart(new StringBody(toXML(classNameParametersxstream)));
            for (int i = 0; i < parametersValues.lengthi++) {
                final Object parameterValue = parametersValues[i];
                if (parameterValue instanceof BusinessArchive || parameterValue instanceof byte[]) {
                    parametersValues[i] = ;
            entity.addPart(new StringBody(toXML(parametersValuesxstream)));
            int i = 0;
            for (final Object object : bytearrayParameters) {
                entity.addPart( + inew ByteArrayBody(serialize(object),  + i));
            httpEntity = entity;
        } else {
            final List<NameValuePairnvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair(toXML(optionsxstream)));
            nvps.add(new BasicNameValuePair(toXML(classNameParametersxstream)));
            nvps.add(new BasicNameValuePair(toXML(parametersValuesxstream)));
            httpEntity = new UrlEncodedFormEntity(nvps);
        return httpEntity;
    public byte[] serialize(final Object objthrows IOException {
        final ByteArrayOutputStream b = new ByteArrayOutputStream();
        final ObjectOutputStream o = new ObjectOutputStream(b);
        return b.toByteArray();
    public Object deserialize(final byte[] bytesthrows IOExceptionClassNotFoundException {
        final ByteArrayInputStream b = new ByteArrayInputStream(bytes);
        final ObjectInputStream o = new ObjectInputStream(b);
        return o.readObject();
    private String toXML(final Object optionsfinal XStream xstreamthrows IOException {
        final StringWriter stringWriter = new StringWriter();
        final ObjectOutputStream out = xstream.createObjectOutputStream(stringWriter);
        return stringWriter.toString();
    private <T> T fromXML(final String objectfinal XStream xstream) {
        final StringReader xmlReader = new StringReader(object);
        ObjectInputStream in = null;
        try {
            in = xstream.createObjectInputStream(xmlReader);
            try {
                return (T) in.readObject();
            } catch (final IOException e) {
                throw new BonitaRuntimeException("unable to deserialize object " + objecte);
            } catch (final ClassNotFoundException e) {
                throw new BonitaRuntimeException("unable to deserialize object " + objecte);
            } catch (final CannotResolveClassException e) {
                throw new BonitaRuntimeException("unable to deserialize object " + objecte);
            } finally {
        } catch (final IOException e) {
            throw new BonitaRuntimeException("unable to deserialize object " + objecte);
New to GrepCode? Check out our FAQ X