Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright 2014 Cisco Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 
 
 
 
 package com.cisco.oss.foundation.directory.impl;
 
 import java.util.List;
 import java.util.Map;
 
 
 import static java.net.HttpURLConnection.HTTP_MULT_CHOICE;
 import static java.net.HttpURLConnection.HTTP_OK;
 import static java.net.HttpURLConnection.HTTP_CREATED;
 
 
 import static com.cisco.oss.foundation.directory.utils.JsonSerializer.*;
 import static com.cisco.oss.foundation.directory.ServiceDirectory.getServiceDirectoryConfig;

This is the client object to invoke the remote service in ServiceDirectory Server Node. It implements the HTTP transportation for ServiceDirectoryService, and hides the HTTPClient details from the upper application layer.
 
 public class DirectoryServiceClient{
     
     private static final Logger LOGGER = LoggerFactory.getLogger(DirectoryServiceClient.class);

    
The http client read timeout property.
 
     public static final String SD_API_HTTPCLIENT_READ_TIMEOUT_PROPERTY = "com.cisco.oss.foundation.directory.httpclient.read.timeout";

    
The http client default read timeout value.
 
     public static final int SD_API_HTTPCLIENT_READ_TIMEOUT_DEFAULT = 5;

    
The Service Directory server FQDN property name.
 
     public static final String SD_API_SD_SERVER_FQDN_PROPERTY = "com.cisco.oss.foundation.directory.server.fqdn";

    
The default Service Directory server FQDN name.
 
     public static final String SD_API_SD_SERVER_FQDN_DEFAULT = "vcsdirsvc";

    
The Service Directory server port property name.
 
     public static final String SD_API_SD_SERVER_PORT_PROPERTY = "com.cisco.oss.foundation.directory.server.port";

    
The default Service Directory server port.
 
     public static final int SD_API_SD_SERVER_PORT_DEFAULT = 2013;

    
The HTTP invoker to access remote ServiceDirectory node.
    private DirectoryInvoker invoker;

    
Constructor.
    public DirectoryServiceClient() {
        this. = new DirectoryInvoker();
    }

    
Register a ServiceInstance.

Parameters:
instance the ProvidedServiceInstance.
Throws:
com.cisco.oss.foundation.directory.exception.ServiceException
    public void registerInstance(ProvidedServiceInstance instance){
        String body = _serialize(instance);
        HttpResponse result = .invoke(toInstanceUri(instance.getServiceName(), instance.getProviderId()), body,
                .);
        if (result.getHttpCode() != ) {
            throw new ServiceException(.,
                    "HTTP Code is not OK, code=%s",result.getHttpCode());
        }
    }
    private String toInstanceUri(String serviceNameString providerId) {
        return "/service/" + serviceName + "/" + providerId;
    }

    
Update a ServiceInstance.

Parameters:
instance the ProvidedServiceInstance.
    public void updateInstance(ProvidedServiceInstance instance){
        String body = _serialize(instance);
        HttpResponse result = .invoke(toInstanceUri(instance.getServiceName(),instance.getProviderId()), body,
                .);
        if (result.getHttpCode() != ) {
            throw new ServiceException(.,
                    "HTTP Code is not OK, code=%s",result.getHttpCode());
        }
    }

    
Update the ServiceInstance OperationalStatus by serviceName and instanceId.

Parameters:
serviceName the service name.
instanceId the instance id.
status the ServiceInstance OperationalStatus.
isOwned whether the DirectoryAPI owns this ServiceProvider.
    public void updateInstanceStatus(String serviceNameString instanceIdOperationalStatus statusboolean isOwned){
        String uri = toInstanceUri(serviceNameinstanceId)+"/status";
        String body = null;
        try {
            body = "status=" + URLEncoder.encode(status.toString(), "UTF-8") + "&isOwned=" + isOwned;
        } catch (UnsupportedEncodingException e) {
            .error("UTF-8 not supported. "e);
        }
        Map<StringStringheaders = new HashMap<StringString>();
        headers.put("Content-Type""application/x-www-form-urlencoded");
        HttpResponse result = .invoke(uribody,
                .headers);
        if (result.getHttpCode() != ) {
            throw new ServiceException(.,
                    "HTTP Code is not OK, code=%s"result.getHttpCode());
        }
    }



    
Update the ServiceInstance attribute "uri".

Parameters:
serviceName the service name.
instanceId the instance id.
uri the ServiceInstance URI.
isOwned whether the DirectoryAPI owns this ServiceProvider.
    public void updateInstanceUri(String serviceNameString instanceIdString uriboolean isOwned){
        String serviceUri = toInstanceUri(serviceNameinstanceId) + "/uri" ;
        String body = null;
        try {
            body = "uri=" + URLEncoder.encode(uri"UTF-8") + "&isOwned=" + isOwned;
        } catch (UnsupportedEncodingException e) {
            .error("UTF-8 not supported. "e);
        }
        Map<StringStringheaders = new HashMap<StringString>();
        headers.put("Content-Type""application/x-www-form-urlencoded");
        HttpResponse result = .invoke(serviceUribody,
                .headers);
        if (result.getHttpCode() != ) {
            throw new ServiceException(.,
                    "HTTP Code is not OK, code=%s"result.getHttpCode());
        }
    }

    
Unregister a ServiceInstance.

Parameters:
serviceName service name.
instanceId the instance id.
isOwned whether the DirectoryAPI owns this ServiceProvider.
    public void unregisterInstance(String serviceNameString instanceIdboolean isOwned){
        String uri = toInstanceUri(serviceNameinstanceId) + "/" + isOwned;
        HttpResponse result = .invoke(urinull,
                .);
        if (result.getHttpCode() != ) {
            throw new ServiceException(.,
                    "HTTP Code is not OK, code=%s"result.getHttpCode());
        }
    }

    
Send ServiceInstance heartbeats.

Parameters:
heartbeatMap the ServiceInstances heartbeat Map.
        String body = _serialize(heartbeatMap);
        HttpResponse result = .invoke("/service/heartbeat"body,
                .);
        if (result.getHttpCode() != ) {
                    "HTTP Code is not OK, code=%s"result.getHttpCode());
        }
        Map<StringOperationResult<String>> operateResult = _deserialize(
                result.getRetBody(), new TypeReference<Map<StringOperationResult<String>>>(){});
        return operateResult;
    }

    
Lookup a Service by serviceName.

Parameters:
serviceName the service name.
Returns:
the ModelService.
    public ModelService lookupService(String serviceName){
        HttpResponse result = .invoke("/service/" + serviceName , null.);
        if (result.getHttpCode() != ) {
            throw new ServiceException(.,
                    "HTTP Code is not OK, code=%s"result.getHttpCode());
        }
        ModelService service = _deserialize(result.getRetBody(), ModelService.class);
        return service;
    }

    
Get all service instances.

Returns:
the ModelServiceInstance list.
        HttpResponse result = .invoke("/service" , null.);
        if (result.getHttpCode() != ) {
                    "HTTP Code is not OK, code=%s"result.getHttpCode());
        }
        List<ModelServiceInstanceallInstances = _deserialize(result.getRetBody(), new TypeReference<List<ModelServiceInstance>>(){});
        return allInstances;
    }

    
Get ModelMetadataKey, which is an object holding a list of service instances that contain the key name in the service metadata.

Parameters:
keyName the key name.
Returns:
the ModelMetadataKey.
    public ModelMetadataKey getMetadataKey(String keyName){
        HttpResponse result = .invoke("/metadatakey/" + keyName , null.);
        if (result.getHttpCode() != ) {
                    "HTTP Code is not OK, code=%s"result.getHttpCode());
        }
        ModelMetadataKey key = _deserialize(
                    result.getRetBody(), ModelMetadataKey.class);
        return key;
    }

    
Get the changed services list.

Parameters:
services the Service list.
Returns:
the list of Services that have been changed.
Throws:
com.cisco.oss.foundation.directory.exception.ServiceException
        String body = _serialize(services);
        HttpResponse result = .invoke("/service/changing" , body.);
        if (result.getHttpCode() != ) {
            throw new ServiceException(.,
                    "HTTP Code is not OK, code=%s"result.getHttpCode());
        }
        Map<StringOperationResult<ModelService>> changedServices = _deserialize(
                    result.getRetBody(), new TypeReference<Map<StringOperationResult<ModelService>>>(){});
        return changedServices;
    }

    
Get the changed MetadataKey list.

Parameters:
keys the MetadataKey List.
Returns:
the list of ModelMetadataKeys that have been changed.
        String body = _serialize(keys);
        HttpResponse result = .invoke("/metadatakey/changing" , body.);
        if (result.getHttpCode() != ) {
            throw new ServiceException(.,
                    "HTTP Code is not OK, code=%s"result.getHttpCode());
        }
        Map<StringOperationResult<ModelMetadataKey>> changedKeys = _deserialize(
                    result.getRetBody(), new TypeReference<Map<StringOperationResult<ModelMetadataKey>>>(){});
        return changedKeys;
    }

    
Deserialize a JSON String to the target object.

Parameters:
body the JSON String.
clazz the Object class name deserialized to.
Returns:
the deserialized Object instance.
Throws:
java.io.IOException
com.fasterxml.jackson.databind.JsonMappingException
com.fasterxml.jackson.core.JsonParseException
    <T> T _deserialize(String bodyClass<T> clazz) {
        if(body == null || body.isEmpty()){
                     ..getMessageTemplate(),
                    "the message body is empty");
        }
        try {
            return deserialize(body.getBytes(), clazz);
        } catch (IOException e) {
            throw new ServiceException(.e,
                    ..getMessageTemplate(),
                    "unrecognized message, deserialize failed.");
        }
    }

    
Deserialize a JSON String to a generic object. This method is used when the target object is generic.

Parameters:
body the JSON String.
typeRef the generic type.
Returns:
the deserialized object instance.
Throws:
java.io.IOException
com.fasterxml.jackson.databind.JsonMappingException
com.fasterxml.jackson.core.JsonParseException
    <T> T _deserialize(String bodyTypeReference<T> typeRef) {
        if (body == null || body.isEmpty()) {
            throw new ServiceException(.,
                    .
                            .getMessageTemplate(), "the message body is empty");
        }
        try {
            return deserialize(body.getBytes(), typeRef);
        } catch (IOException e) {
            throw new ServiceException(.e,
                    ..getMessageTemplate(),
                    "unrecognized message, deserialize failed.");
        }
    }

    
Serialize a object to JSON String.

Parameters:
o the target object.
Returns:
the JSON String.
    String _serialize(Object o) {
        String body = null;
            try {
                body = new String(serialize(o));
            } catch (IOException e) {
                throw new ServiceException(.,
                        ..getMessageTemplate(),
                        "serialize failed.");
            }
        return body;
    }

    
Keep it default for unit test.

Returns:
the DirectoryInvoker
        return ;
    }
    public void setInvoker(DirectoryInvoker invoker) {
        this. = invoker;
    }

    
It is the HTTP invoker to the ServiceDirectory Server Node. It wraps the complexity of HttpClient and exposes an easy method to invoke RESTful services.
    public static class DirectoryInvoker {
        /* The remote ServiceDirectory node address array, in the format of http://<host>:<port> */
        public String directoryAddresses;

        
Constructor.
        public DirectoryInvoker() {
            this. = "http://" + sdFQDN + ":" + port;
        }

        
Invoke the HTTP RESTful Service.

Parameters:
uri The URI of the RESTful service.
payload The HTTP body String.
method The HTTP method.
Returns:
the HttpResponse.
        public HttpResponse invoke(String uriString payloadHttpMethod method) {
            HttpResponse result = null;
            String url =  + uri;
            try {
                if (method == null || method == .) {
                    result = HttpUtils.getJson(url);
                } else if (method == .) {
                    result = HttpUtils.postJson(urlpayload);
                } else if (method == .) {
                    result = HttpUtils.putJson(urlpayload);
                } else if (method == .) {
                    result = HttpUtils.deleteJson(url);
                }
            } catch (IOException e) {
                String errMsg = "Send HTTP Request to remote Directory Server failed";
                throw new ServiceException(.,e,errMsg);
            }
            // HTTP_OK 200, HTTP_MULT_CHOICE 300
            if (result.getHttpCode() <  || result.getHttpCode() >= ) {
                String errorBody = result.getRetBody();
                if(errorBody == null || errorBody.isEmpty()){
                    throw new ServiceException(.,
                            ..getMessageTemplate(),
                            "Error Message body is empty.");
                }
                //TODO, server-side support of SDError
                ServiceDirectoryError sde = null;
                try {
                    sde =  deserialize(errorBody.getBytes(), ServiceDirectoryError.class);
                } catch (IOException  e) {
                    String errMsg = "Deserialize error body message failed";
                    throw new ServiceException(.,e,errMsg);
                }
                if (sde != null) {
                    throw new ServiceException(sde.getExceptionCode(),sde.getErrorMessage());
                }
            }
            return result;
        }

        
Invoke the HTTP RESTful Service.

Parameters:
uri The URI of the RESTful service.
payload The HTTP body string.
method The HTTP method.
headers The HTTP headers.
Returns:
the HttpResponse.
        public HttpResponse invoke(String uriString payloadHttpMethod methodMap<StringStringheaders) {
            HttpResponse result = null;
            String url =  + uri;
            try {
                if (method == .) {
                    result = HttpUtils.put(urlpayloadheaders);
                }
            } catch (IOException e) {
                String errMsg = "Send HTTP Request to remote Directory Server failed";
                throw new ServiceException(.,e,errMsg);
            }
            // HTTP_OK 200, HTTP_MULT_CHOICE 300
            if (result.getHttpCode() <  || result.getHttpCode() >= 300) {
                String errorBody = result.getRetBody();
                if(errorBody == null || errorBody.isEmpty()) {
                    throw new ServiceException(.,
                            ..getMessageTemplate(),
                            "Error Message body is empty.");
                }
                ServiceDirectoryError sde = null;
                try {
                    sde = deserialize(errorBody.getBytes(),
                                    ServiceDirectoryError.class);
                } catch (IOException  e) {
                    String errMsg = "Deserialize error body message failed";
                    throw new ServiceException(.,e,errMsg);
                }
                if (sde != null) {
                    throw new ServiceException(sde.getExceptionCode(),sde.getErrorMessage());
                }
            }
            return result;
        }
    }
New to GrepCode? Check out our FAQ X