public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            var baseApiUri = endPointDescriptor.ComponentPath;
            var location = endPointDescriptor.GetUriProperty("location", "");
            var resultHeader = endPointDescriptor.GetUriProperty("resultHeader");
            var lat = endPointDescriptor.GetUriProperty("lat");
            var lon = endPointDescriptor.GetUriProperty("lon");

            using (var client = new WebClient())
            {
                if (!string.IsNullOrEmpty(lat))
                    client.QueryString.Add("lat", lat);
                if (!string.IsNullOrEmpty(lon))
                    client.QueryString.Add("lon", lon);

                var finaUrl = string.Format("{0}?q={1}", baseApiUri, location);
                var result = client.DownloadString(finaUrl);

                if (!string.IsNullOrEmpty(resultHeader))
                    exchange.InMessage.SetHeader("resultHeader", result);
                else
                {
                    exchange.InMessage.Body = result;
                }
            }
            return exchange;
        }
        public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            try
            {
                var inReverse = endPointDescriptor.GetUriProperty("reverse", false);
                var useOut = endPointDescriptor.GetUriProperty("useout", false);

                var body = useOut ? exchange.OutMessage.Body.ToString() : exchange.InMessage.Body.ToString();

                if (!inReverse)
                {
                    var doc = new XmlDocument();
                    doc.LoadXml(body);
                    var jsonText = JsonConvert.SerializeXmlNode(doc);
                    exchange.InMessage.Body = jsonText;
                }
                else
                {
                    var doc = JsonConvert.DeserializeXmlNode(body);
                    exchange.InMessage.Body = doc.InnerXml;
                }
                Camel.TryLog(exchange, "processor", endPointDescriptor.ComponentName);
            }
            catch (Exception exception)
            {

            }
            return base.Process(exchange, endPointDescriptor);
        }
Exemple #3
0
        public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            try
            {
                var hostname = endPointDescriptor.GetUriProperty("hostname", "localhost");
                var queue    = endPointDescriptor.GetUriProperty("queue", "systemQueue");
                var port     = endPointDescriptor.GetUriProperty("port", 5672);
                var channel  = GetChannel(string.Format("{0}::{1}::{2}", hostname, port, queue), queue, hostname);

                channel.QueueDeclare(queue: queue,
                                     durable: true,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                var msg  = exchange.InMessage.Body.ToString();
                var body = Encoding.UTF8.GetBytes(msg);

                //send
                channel.BasicPublish(exchange: "",
                                     routingKey: queue,
                                     basicProperties: null,
                                     body: body);
            }
            catch (Exception exception)
            {
                var msg = exception.Message;
            }

            return(exchange);
        }
        public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            try
            {
                Camel.TryLog(exchange, "provider", endPointDescriptor.ComponentName);

                var dbHost = endPointDescriptor.ComponentPath;
                var port = endPointDescriptor.GetUriProperty<int>("port");
                var couchDbDatabase = exchange.InMessage.GetHeader("CouchDbDatabase");
                var createDb = endPointDescriptor.GetUriProperty<bool>("createDb");
                var document = exchange.InMessage.Body;

                var dbUrl = string.Format("http://{0}:{1}", dbHost, port);
                var conn = new Connection(new Uri(dbUrl));

                if (createDb && !conn.ListDatabases().Contains(couchDbDatabase))
                {
                    conn.CreateDatabase(couchDbDatabase.ToString());
                }
            }
            catch (Exception exception)
            {
            }

            return base.Process(exchange, endPointDescriptor);
        }
        /// <summary>
        /// Process
        /// </summary>
        /// <param name="exchange"></param>
        /// <param name="endPointDescriptor"></param>
        /// <returns></returns>
        public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            try
            {
                if (exchange.InMessage.Body == null || exchange.InMessage.Body.ToString() == string.Empty)
                {
                    return(exchange);
                }

                //can create dir
                var createOnMissingDir = endPointDescriptor.GetUriProperty <bool>("create");

                //create dir if not found
                if (!Directory.Exists(endPointDescriptor.ComponentPath))
                {
                    if (createOnMissingDir)
                    {
                        Directory.CreateDirectory(endPointDescriptor.ComponentPath);
                    }
                    else
                    {
                        return(exchange);
                    }
                }

                //get details.
                var filePath      = exchange.InMessage.GetHeader <string>("filePath") ?? endPointDescriptor.ComponentPath;
                var fileExtension = endPointDescriptor.GetUriProperty <string>("fileExtension");

                //change_file_path
                var originalExt = Path.GetExtension(filePath);
                filePath = Path.ChangeExtension(filePath, fileExtension ?? originalExt);
                var newExt = Path.GetExtension(filePath);

                //new path
                var fileNameWithExt = Path.GetFileName(filePath);
                if (fileNameWithExt != null)
                {
                    filePath = Path.Combine(endPointDescriptor.ComponentPath, fileNameWithExt);
                }

                filePath = Path.ChangeExtension(filePath, string.Format("{0}{1}", DateTime.Now.Ticks, newExt));

                //write
                File.AppendAllText(filePath, exchange.InMessage.Body.ToString());
            }
            catch (Exception exception)
            {
                var msg = exception.Message;
            }

            //done
            return(exchange);
        }
        public override Exchange Process(Exchange exchange, UriDescriptor uriDescriptor)
        {
            try
            {
                var showOut = uriDescriptor.GetUriProperty("show-out", false);
                var filePathToLogTo = uriDescriptor.GetUriProperty("file");
                var additionalMessage = uriDescriptor.GetUriProperty("message", "");

                //in data
                var inHeaderBuilder = new StringBuilder();
                exchange.InMessage.HeaderCollection.ToList().ForEach(c => inHeaderBuilder.AppendFormat("{0}='{1}', ", c.Key, c.Value.ToString()));

                var propertyBuilder = new StringBuilder();
                exchange.PropertyCollection.ToList().ForEach(c => propertyBuilder.AppendFormat("{0}='{1}',", c.Key, c.Value.ToString()));
                var inBody = exchange.InMessage.Body.ToString();

                var msg = string.Format("Exchange:  Id: {0}, MEP={5}. >> Route: ID({1}), Properties [{3}], In Message: [Headers: {2} Body: {4}]",
                    exchange.ExchangeId, exchange.Route.RouteId, inHeaderBuilder, propertyBuilder, inBody, exchange.MepPattern);

                //out data
                if (exchange.MepPattern == Exchange.Mep.InOut)
                {
                    var outHeaderBuilder = new StringBuilder();
                    exchange.OutMessage.HeaderCollection.ToList().ForEach(c => outHeaderBuilder.AppendFormat("{0}='{1}', ", c.Key, c.Value.ToString()));
                    var outBody = exchange.OutMessage.Body.ToString();
                    msg = string.Format("{0}, Out Message: [Headers: {1} Body: {2}]", msg, outHeaderBuilder, outBody);
                }

                var errors = exchange.DequeueAllErrors;
                if (errors.Count > 0)
                {
                    var errorListing = new StringBuilder();
                    errors.ForEach(c => errorListing.AppendFormat("[ error-message?: {0}, any-stack-trace?: {1} ]", c.Message, c.StackTrace));
                    msg = string.Format("{0}, {1}", msg, errorListing);
                }

                var starTime = DateTime.Now;
                if (!string.IsNullOrEmpty(filePathToLogTo))
                    Log(filePathToLogTo, msg, uriDescriptor);

                var interval = DateTime.Now - starTime;
                return exchange;
            }
            catch (AggregateException exception)
            {

            }
            catch (Exception exception)
            {

            }

            return exchange;
        }
        public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            try
            {
                var port = endPointDescriptor.GetUriProperty("port", 7000, exchange);
                var receivetimeout = endPointDescriptor.GetUriProperty("receivetimeout", 10000, exchange);
                var sendtimeout = endPointDescriptor.GetUriProperty("sendtimeout", 5000, exchange);
                var ip = endPointDescriptor.ComponentPath;

                var client = new TcpClient();
                client.Connect(ip, port);

                if (client.Connected)
                {
                    var bodyMsg = exchange.InMessage.Body.ToString();
                    var buffer = Encoding.ASCII.GetBytes(bodyMsg);

                    Camel.TryLog(exchange, "producer", endPointDescriptor.ComponentName);

                    client.Client.ReceiveTimeout = receivetimeout;
                    client.Client.SendTimeout = sendtimeout;
                    client.Client.Send(buffer);

                    using (var networkStream = client.GetStream())
                    {
                        if (networkStream.CanRead)
                        {
                            // Buffer to store the response bytes.
                            var readBuffer = new byte[client.ReceiveBufferSize];
                            using (var writer = new MemoryStream())
                            {
                                do
                                {
                                    var numberOfBytesRead = networkStream.Read(readBuffer, 0, readBuffer.Length);
                                    if (numberOfBytesRead <= 0)
                                    {
                                        break;
                                    }
                                    writer.Write(readBuffer, 0, numberOfBytesRead);
                                } while (networkStream.DataAvailable);
                                exchange.InMessage.Body = Encoding.UTF8.GetString(writer.ToArray());
                            }
                        }
                    }
                }
            }
            catch (System.Exception exception)
            {
                Console.WriteLine(exception.StackTrace);
            }
            return exchange;
        }
        public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            try
            {
                var protocol = endPointDescriptor.GetUriProperty<string>("protocol");

                switch (protocol)
                {
                    case "smtp":
                        Task.Factory.StartNew(() => SendMail(endPointDescriptor, exchange));
                        break;
                    case "imap":
                        break;
                }
            }
            catch (AggregateException aggregateException)
            {
                Console.WriteLine("aggr-error sending mail: {0}", aggregateException.Message);
            }
            catch (Exception exception)
            {
                Console.WriteLine("error sending mail: {0}", exception.Message);
            }

            return base.Process(exchange, endPointDescriptor);
        }
        public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            try
            {
                var method = endPointDescriptor.GetUriProperty("method");
                var objectTypePath = endPointDescriptor.ComponentPath;
                var objectType = Type.GetType(objectTypePath);

                if (objectType != null)
                {
                    var objectInstance = Activator.CreateInstance(objectType, null);
                    if (!string.IsNullOrEmpty(method))
                    {
                        //process normalizer method
                        var methodMember = objectInstance.GetType()
                            .GetMethod(method, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                        methodMember.Invoke(objectInstance, null);
                    }
                }
            }
            catch (Exception exception)
            {

            }

            return base.Process(exchange, endPointDescriptor);
        }
        public override Exchange Process(Exchange exchange, UriDescriptor uriInformation)
        {
            var name = uriInformation.ComponentPath;
            var role = uriInformation.GetUriProperty("role");
            var sharedKey = uriInformation.GetUriProperty("sharedKey");

            var claims = new Dictionary<string, string>
            {
                {"name", name},
                {"role", role},
            };

            var token = JWT.JsonWebToken.Encode(claims, sharedKey, JWT.JwtHashAlgorithm.HS256);
            exchange.InMessage.SetHeader(uriInformation.ComponentPath, token);
            Camel.TryLog(exchange, "producer", uriInformation.ComponentName);

            return exchange;
        }
        public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            try
            {
                var host = endPointDescriptor.GetUriProperty("host");
                var isBodyXml = endPointDescriptor.GetUriProperty<bool>("isBodyXml");
                var database = endPointDescriptor.GetUriProperty("database");
                var collection = endPointDescriptor.GetUriProperty("collection");
                var createCollection = endPointDescriptor.GetUriProperty<bool>("createCollection");
                var operation = endPointDescriptor.GetUriProperty<OperationType>("operation");

                var client = new MongoClient("mongodb://" + host);
                var db = client.GetServer().GetDatabase(database);

                if (!db.CollectionExists(collection) && createCollection)
                    db.CreateCollection(collection);

                var bson = exchange.InMessage.Body.ToString();

                if (isBodyXml)
                {
                    var doc = new XmlDocument();
                    doc.LoadXml(exchange.InMessage.Body.ToString());
                    bson = JsonConvert.SerializeXmlNode(doc);
                }
                var bsonDoc = BsonDocument.Parse(bson);
                ServeOperation(db, exchange, endPointDescriptor, bsonDoc, operation, collection);
            }
            catch (Exception exception)
            {
                Console.WriteLine("{0}-{1}", exception.Message, exception.StackTrace);
            }
            return exchange;
        }
        public override Exchange Process(Exchange exchange, UriDescriptor endPointDescriptor)
        {
            try
            {
                var connection = CreateConnection(endPointDescriptor);
                var queue = endPointDescriptor.GetUriProperty("queue", "test_queue." + DateTime.Now.Ticks);
                var requestTimeOut = endPointDescriptor.GetUriProperty("timeout", new TimeSpan(0, 10, 0));

                using (var session = connection.CreateSession())
                {
                    IDestination temporaryDestination = session.CreateTemporaryQueue();

                    var topic = session.GetQueue(queue);
                    var producer = session.CreateProducer(topic);
                    producer.RequestTimeout = requestTimeOut;

                    //create message
                    var messageSer = JsonConvert.SerializeObject(exchange);
                    var message = session.CreateTextMessage(messageSer);

                    message.NMSCorrelationID = exchange.ExchangeId.ToString();
                    message.NMSReplyTo = temporaryDestination;
                    producer.Send(message);
                }
            }
            catch (AggregateException)
            {

            }
            catch (Exception exception)
            {
                Console.WriteLine("{0}-{1}", exception.Message, exception.StackTrace);
                exchange.SetException(new Exception("error connecting to amq", exception));
            }

            return exchange;
        }
        private static void SendMail(UriDescriptor endPointDescriptor, Exchange exchange)
        {
            try
            {
                var toAddress = endPointDescriptor.GetUriProperty("to");
                var from = endPointDescriptor.GetUriProperty("from");
                var port = endPointDescriptor.GetUriProperty<int>("port");
                var host = endPointDescriptor.ComponentPath;
                var subject = endPointDescriptor.GetUriProperty<string>("subject");
                var body = endPointDescriptor.GetUriProperty<string>("body");
                var username = endPointDescriptor.GetUriProperty<string>("username");
                var password = endPointDescriptor.GetUriProperty<string>("password");

                var mail = new MailMessage();
                var client = new SmtpClient
                {
                    Port = port,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Host = host,
                };

                if (!string.IsNullOrEmpty(username) &&
                    !string.IsNullOrEmpty(password))
                {
                    client.Credentials = new NetworkCredential(username, password);
                }

                mail.To.Add(new MailAddress(toAddress));
                mail.From = new MailAddress(@from);
                mail.IsBodyHtml = true;
                mail.Body = exchange.InMessage.Body.ToString();

                mail.Subject = subject;

                Camel.TryLog(exchange, "producer", endPointDescriptor.ComponentName);
                client.Send(mail);
            }
            catch (Exception exception)
            {

            }
        }
        public override Exchange Process(Exchange exchange, UriDescriptor descriptor)
        {
            Camel.TryLog(exchange, "producer", descriptor.ComponentName);

            var connectionTimeOut = descriptor.GetUriProperty<int>("connectionTimeOut");
            var noHeaderPolicy = descriptor.GetUriProperty<bool>("noHeaderPolicy");
            var httpMethod = exchange.InMessage.GetHeader(CamelConstant.HttpMethod) as string;
            var httpUri = exchange.InMessage.GetHeader(CamelConstant.HttpUri);
            var httpQuery = exchange.InMessage.GetHeader(CamelConstant.HttpQuery) as string;

            var httpContentType = exchange.InMessage.GetHeader(CamelConstant.HttpContentType, "application/x-www-form-urlencoded");
            var path = !string.IsNullOrEmpty((descriptor.ComponentPath)) ? descriptor.ComponentPath : httpUri as string;

            path = string.Format("{0}", path);

            try
            {
                using (var client = new WebCamelClient())
                {
                    client.Timeout = connectionTimeOut > 1000 ? connectionTimeOut : 1000;

                    switch (httpMethod)
                    {
                        case "POST":
                            if (exchange.InMessage.Body != null)
                            {
                                var payLoad = exchange.InMessage.Body != null
                                    ? exchange.InMessage.Body.ToString()
                                    : string.Empty;
                                client.Headers[HttpRequestHeader.ContentType] = httpContentType as string;
                                client.ContentType = httpContentType;

                                if(noHeaderPolicy)
                                    client.Headers.Clear();
                                client.UploadString(path, payLoad);
                            }
                            break;
                        case "PUT":
                            if (exchange.InMessage.Body != null)
                            {
                                var payLoad = exchange.InMessage.Body != null
                                    ? exchange.InMessage.Body.ToString()
                                    : string.Empty;

                                if (noHeaderPolicy)
                                    client.Headers.Clear();
                                client.UploadData(path, "PUT", Encoding.ASCII.GetBytes(payLoad));
                            }
                            break;
                        case "GET":
                            var queryKeyValue = UriDescriptor.BuildKeyValueListWithEquality(httpQuery);
                            if (queryKeyValue != null)
                                queryKeyValue.ForEach(c => client.QueryString.Add(c.Key, c.Value));

                            if (noHeaderPolicy)
                                client.Headers.Clear();

                            var response = client.DownloadString(path);
                            exchange.InMessage.Body = response;
                            break;
                        case "TRACE":
                            var queryKeyValueTrace = UriDescriptor.BuildKeyValueListWithEquality(httpQuery);
                            if (queryKeyValueTrace != null)
                                queryKeyValueTrace.ForEach(c => client.QueryString.Add(c.Key, c.Value));

                            if (noHeaderPolicy)
                                client.Headers.Clear();

                            var responsetrace = client.DownloadString(path);
                            exchange.InMessage.Body = responsetrace;
                            break;
                    }

                    for (int i = 0; i < client.ResponseHeaders.Count; i++)
                    {
                        var key = client.ResponseHeaders.GetKey(i);
                        var strings = client.ResponseHeaders.GetValues(i);
                        if (strings == null) continue;

                        var value = strings[0];
                        exchange.InMessage.SetHeader("http-response-" + key, value);
                    }

                    Camel.TryLog(exchange, "provider", descriptor.ComponentName);
                }
            }
            catch (WebException exception)
            {
                if (exception.Status == WebExceptionStatus.ProtocolError)
                {
                    exchange.Exception.Push(exception);
                }
            }
            catch (Exception ex)
            {
                exchange.Exception.Push(ex);
            }

            return base.Process(exchange, descriptor);
        }