Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (C) 2011, 2014 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;
 
 

Author(s):
Baptiste Mesta
Julien Mege
Elias Ricken de Medeiros
Celine Souchet
 
 public class HTTPServerAPI implements ServerAPI {
 
     private static final long serialVersionUID = -3375874140999200702L;
 
     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/";
 
     static final String SERVER_URL = "server.url";
 
     private static final String BASIC_AUTHENTICATION_ACTIVE = "basicAuthentication.active";
 
     private static final String BASIC_AUTHENTICATION_USERNAME = "basicAuthentication.username";
 
     private static final String BASIC_AUTHENTICATION_PASSWORD = "basicAuthentication.password";
 
     static final String APPLICATION_NAME = "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 Charset UTF8 = Charset.forName("UTF-8");
    private static final ResponseHandler<StringRESPONSE_HANDLER = new BonitaResponseHandler();
    static {
         = new XStream();
    }
    public HTTPServerAPI(final Map<StringStringparameters) {
        // initialize httpclient in the constructor to avoid incompatibility when running tests:
        // java.security.NoSuchAlgorithmException: class configured for SSLContext: sun.security.ssl.SSLContextImpl$TLS10Context not a SSLContext
        if ( == null) {
             = new DefaultHttpClient(new PoolingClientConnectionManager());
        }
         = parameters.get();
         = parameters.get();
    }
    @Override
    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) {
            final StackTraceElement[] stackTrace = new Exception().getStackTrace();
            StackTraceTransformer.addStackTo(estackTrace);
            throw new ServerWrappedException(e.getMessage() + "response= " + responsee);
        }
    }
    private Object checkInvokeMethodReturn(final String responsefinal XStream xstreamthrows Throwable {
        Object invokeMethodReturn = null;
        if (response != null && !response.isEmpty() && !"null".equals(response)) {
            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);
        try {
            return .execute(httpost);
        } catch (final ClientProtocolException e) {
            if (.isLoggable(.)) {
                .log(.e.getMessage() + System.getProperty("line.separator") + "httpost = <" + httpost + ">");
            }
            throw e;
        }
    }
    private final 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();
        sBuilder.append().append().append().append(apiInterfaceName).append().append(methodName);
        final HttpPost httpost = new HttpPost(sBuilder.toString());
        httpost.setEntity(httpEntity);
        // Basic authentication
        if () {
            final StringBuilder credentials = new StringBuilder();
            final Base64 encoder = new Base64();
            final String encodedCredentials = encoder.encodeAsString(credentials.toString().getBytes());
            httpost.setHeader("Authorization""Basic " + encodedCredentials);
        }
        return httpost;
    }
    final 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(nullnull);
            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] = ;
                    bytearrayParameters.add(parameterValue);
                }
            }
            entity.addPart(new StringBody(toXML(parametersValuesxstream), ));
            int i = 0;
            for (final Object object : bytearrayParameters) {
                entity.addPart( + inew ByteArrayBody(serialize(object),  + i));
                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);
        o.writeObject(obj);
        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);
        out.writeObject(options);
        out.close();
        return stringWriter.toString();
    }
    @SuppressWarnings("unchecked")
    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 {
                in.close();
                xmlReader.close();
            }
        } catch (final IOException e) {
            throw new BonitaRuntimeException("unable to deserialize object " + objecte);
        }
    }
New to GrepCode? Check out our FAQ X