code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Management.Api10 { /// <summary> /// Cloud Service Scheduling Info /// </summary> [DataContract(Name = "CloudServiceSchedulingInfo", Namespace = "http://schemas.lokad.com/lokad-cloud/management/1.0")] public class CloudServiceSchedulingInfo { /// <summary>Name of the service.</summary> [DataMember(Order = 0, IsRequired = true)] public string ServiceName { get; set; } /// <summary>Scheduled trigger interval.</summary> [DataMember(Order = 1, IsRequired = true)] public TimeSpan TriggerInterval { get; set; } /// <summary>Last execution time stamp.</summary> [DataMember(Order = 3, IsRequired = false)] public DateTimeOffset LastExecuted { get; set; } /// <summary>True if the services is worker scoped instead of cloud scoped.</summary> [DataMember(Order = 2, IsRequired = false, EmitDefaultValue = false)] public bool WorkerScoped { get; set; } /// <summary>Owner of the lease.</summary> [DataMember(Order = 4, IsRequired = false)] public Maybe<string> LeasedBy { get; set; } /// <summary>Point of time when the lease was acquired.</summary> [DataMember(Order = 5, IsRequired = false)] public Maybe<DateTimeOffset> LeasedSince { get; set; } /// <summary>Point of time when the lease will timeout.</summary> [DataMember(Order = 6, IsRequired = false)] public Maybe<DateTimeOffset> LeasedUntil { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Api10/CloudServiceSchedulingInfo.cs
C#
bsd
1,660
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Api10 { /// <summary> /// Cloud Assembly Info /// </summary> [DataContract(Name = "CloudAssemblyInfo", Namespace = "http://schemas.lokad.com/lokad-cloud/management/1.0")] public class CloudAssemblyInfo { /// <summary>Name of the cloud assembly.</summary> [DataMember(Order = 0, IsRequired = true)] public string AssemblyName { get; set; } /// <summary>Time stamp of the cloud assembly.</summary> [DataMember(Order = 1)] public DateTime DateTime { get; set; } /// <summary>Version of the cloud assembly.</summary> [DataMember(Order = 2)] public Version Version { get; set; } /// <summary>File size of the cloud assembly, in bytes.</summary> [DataMember(Order = 3)] public long SizeBytes { get; set; } /// <summary>Assembly can be loaded successfully.</summary> [DataMember(Order = 4)] public bool IsValid { get; set; } /// <summary>Assembly symbol store (PDB file) is available.</summary> [DataMember(Order = 5)] public bool HasSymbols { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Api10/CloudAssemblyInfo.cs
C#
bsd
1,272
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Web; namespace Lokad.Cloud.Management.Api10 { using Lokad.Cloud.Application; [ServiceContract(Name = "CloudAssemblies", Namespace = "http://schemas.lokad.com/lokad-cloud/management/1.0")] public interface ICloudAssembliesApi { [OperationContract] [WebGet(UriTemplate = @"assemblies")] List<CloudApplicationAssemblyInfo> GetAssemblies(); [OperationContract] [WebInvoke(UriTemplate = @"upload/dll/{filename}", Method = "POST")] void UploadAssemblyDll(byte[] data, string fileName); [OperationContract] [WebInvoke(UriTemplate = @"upload/zip", Method = "POST")] void UploadAssemblyZipContainer(byte[] data); [OperationContract] [WebInvoke(UriTemplate = @"upload/zip/isvalid", Method = "POST")] bool IsValidZipContainer(byte[] data); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Api10/ICloudAssembliesApi.cs
C#
bsd
1,117
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.ServiceModel; using System.ServiceModel.Web; namespace Lokad.Cloud.Management.Api10 { [ServiceContract(Name = "CloudProvisioning", Namespace = "http://schemas.lokad.com/lokad-cloud/management/1.0")] public interface ICloudProvisioningApi { [OperationContract] [WebGet(UriTemplate = @"instances")] int GetWorkerInstanceCount(); [OperationContract] [WebInvoke(UriTemplate = @"instances/set?newcount={instanceCount}", Method = "POST")] void SetWorkerInstanceCount(int instanceCount); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Api10/ICloudProvisioningApi.cs
C#
bsd
681
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Web; using Lokad.Cloud.Diagnostics; namespace Lokad.Cloud.Management.Api10 { [ServiceContract(Name = "CloudStatistics", Namespace = "http://schemas.lokad.com/lokad-cloud/management/1.0")] public interface ICloudStatisticsApi { [OperationContract] [WebGet(UriTemplate = @"partitions/month?date={monthUtc}")] List<PartitionStatistics> GetPartitionsOfMonth(DateTime? monthUtc); [OperationContract] [WebGet(UriTemplate = @"partitions/day?date={dayUtc}")] List<PartitionStatistics> GetPartitionsOfDay(DateTime? dayUtc); [OperationContract] [WebGet(UriTemplate = @"services/month?date={monthUtc}")] List<ServiceStatistics> GetServicesOfMonth(DateTime? monthUtc); [OperationContract] [WebGet(UriTemplate = @"services/day?date={dayUtc}")] List<ServiceStatistics> GetServicesOfDay(DateTime? dayUtc); [OperationContract] [WebGet(UriTemplate = @"profiles/month?date={monthUtc}")] List<ExecutionProfilingStatistics> GetProfilesOfMonth(DateTime? monthUtc); [OperationContract] [WebGet(UriTemplate = @"profiles/day?date={dayUtc}")] List<ExecutionProfilingStatistics> GetProfilesOfDay(DateTime? dayUtc); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Api10/ICloudStatisticsApi.cs
C#
bsd
1,422
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Web; namespace Lokad.Cloud.Management.Api10 { [ServiceContract(Name = "CloudServiceScheduling", Namespace = "http://schemas.lokad.com/lokad-cloud/management/1.0")] public interface ICloudServiceSchedulingApi { [OperationContract] [WebGet(UriTemplate = @"services")] List<string> GetScheduledServiceNames(); [OperationContract] [WebGet(UriTemplate = @"userservices")] List<string> GetScheduledUserServiceNames(); [OperationContract] [WebGet(UriTemplate = @"services/all")] List<CloudServiceSchedulingInfo> GetSchedules(); [OperationContract] [WebGet(UriTemplate = @"services/{serviceName}")] CloudServiceSchedulingInfo GetSchedule(string serviceName); [OperationContract] [WebInvoke(UriTemplate = @"services/{serviceName}/interval?timespan={triggerInterval}", Method = "POST")] void SetTriggerInterval(string serviceName, TimeSpan triggerInterval); [OperationContract] [WebInvoke(UriTemplate = @"services/{serviceName}/reset", Method = "POST")] void ResetSchedule(string serviceName); [OperationContract] [WebInvoke(UriTemplate = @"services/{serviceName}/release", Method = "POST")] void ReleaseLease(string serviceName); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Api10/ICloudServiceSchedulingApi.cs
C#
bsd
1,466
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Api10 { /// <summary> /// Cloud Service Info /// </summary> [DataContract(Name = "CloudServiceInfo", Namespace = "http://schemas.lokad.com/lokad-cloud/management/1.0")] public class CloudServiceInfo { /// <summary>Name of the service</summary> [DataMember(Order = 0, IsRequired = true)] public string ServiceName { get; set; } /// <summary>Current state of the service</summary> [DataMember(Order = 1)] public bool IsStarted { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Api10/CloudServiceInfo.cs
C#
bsd
703
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Web; namespace Lokad.Cloud.Management.Api10 { [ServiceContract(Name = "CloudServices", Namespace = "http://schemas.lokad.com/lokad-cloud/management/1.0")] public interface ICloudServicesApi { [OperationContract] [WebGet(UriTemplate = @"services")] List<string> GetServiceNames(); [OperationContract] [WebGet(UriTemplate = @"userservices")] List<string> GetUserServiceNames(); [OperationContract] [WebGet(UriTemplate = @"services/all")] List<CloudServiceInfo> GetServices(); [OperationContract] [WebGet(UriTemplate = @"services/{serviceName}")] CloudServiceInfo GetService(string serviceName); [OperationContract] [WebInvoke(UriTemplate = @"services/{serviceName}/enable", Method = "POST")] void EnableService(string serviceName); [OperationContract] [WebInvoke(UriTemplate = @"services/{serviceName}/disable", Method = "POST")] void DisableService(string serviceName); [OperationContract] [WebInvoke(UriTemplate = @"services/{serviceName}/toggle", Method = "POST")] void ToggleServiceState(string serviceName); [OperationContract] [WebInvoke(UriTemplate = @"services/{serviceName}/reset", Method = "POST")] void ResetServiceState(string serviceName); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Api10/ICloudServicesApi.cs
C#
bsd
1,492
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.ServiceModel; using System.ServiceModel.Web; namespace Lokad.Cloud.Management.Api10 { [ServiceContract(Name = "CloudConfiguration", Namespace = "http://schemas.lokad.com/lokad-cloud/management/1.0")] public interface ICloudConfigurationApi { [OperationContract] [WebGet(UriTemplate = @"config")] string GetConfigurationString(); [OperationContract] [WebInvoke(UriTemplate = @"config", Method = "POST")] void SetConfiguration(string configuration); [OperationContract] [WebInvoke(UriTemplate = @"remove", Method = "POST")] void RemoveConfiguration(); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Api10/ICloudConfigurationApi.cs
C#
bsd
761
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.ServiceModel; using System.ServiceModel.Security; using System.Threading; using Lokad.Cloud.Storage.Shared.Policies; namespace Lokad.Cloud.Management.Azure { /// <summary> /// Azure retry policies for corner-situation and server errors. /// </summary> public static class AzureManagementPolicies { /// <summary> /// Retry policy to temporarily back off in case of transient Azure server /// errors, system overload or in case the denial of service detection system /// thinks we're a too heavy user. Blocks the thread while backing off to /// prevent further requests for a while (per thread). /// </summary> public static Storage.Shared.Policies.ActionPolicy TransientServerErrorBackOff { get; private set; } /// <summary> /// Static Constructor /// </summary> static AzureManagementPolicies() { // Initialize Policies TransientServerErrorBackOff = Storage.Shared.Policies.ActionPolicy.With(TransientServerErrorExceptionFilter) .Retry(30, OnTransientServerErrorRetry); } static void OnTransientServerErrorRetry(Exception exception, int count) { // quadratic backoff, capped at 5 minutes var c = count + 1; Thread.Sleep(TimeSpan.FromSeconds(Math.Min(300, c * c))); } static bool TransientServerErrorExceptionFilter(Exception exception) { // NOTE: We observed Azure hiccups that caused transport security // to momentarily fail, causing a MessageSecurity exception (#1405). // We thus tread this exception as a transient error. // In case it is a permanent error it will still show up, // although delayed by the 30 retrials. if (exception is EndpointNotFoundException || exception is TimeoutException || exception is MessageSecurityException) { return true; } return false; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/AzureManagementPolicies.cs
C#
bsd
2,032
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using System.ServiceModel.Web; // TODO: To be replaced with official REST client once available namespace Lokad.Cloud.Management.Azure { public class ManagementClient : IDisposable { readonly X509Certificate2 _certificate; readonly object _sync = new object(); WebChannelFactory<IAzureServiceManagement> _factory; public ManagementClient(X509Certificate2 certificate) { if (certificate == null) { throw new ArgumentNullException("certificate"); } _certificate = certificate; } public IAzureServiceManagement CreateChannel() { // long lock, but should in practice never be accessed // from two threads anyway (just a safeguard) and this way // we avoid multiple sync monitor enters per call lock (_sync) { if (_factory != null) { switch (_factory.State) { case CommunicationState.Closed: case CommunicationState.Closing: // TODO: consider reusing the factory _factory = null; break; case CommunicationState.Faulted: _factory.Close(); _factory = null; break; } } if (_factory == null) { var binding = new WebHttpBinding(WebHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; _factory = new WebChannelFactory<IAzureServiceManagement>(binding, new Uri(ApiConstants.ServiceEndpoint)); _factory.Endpoint.Behaviors.Add(new ClientOutputMessageInspector()); _factory.Credentials.ClientCertificate.Certificate = _certificate; } return _factory.CreateChannel(); } } public void Dispose() { lock (_sync) { if (_factory == null) { return; } _factory.Close(); _factory = null; } } public void CloseChannel(IAzureServiceManagement channel) { var clientChannel = channel as IClientChannel; if (clientChannel != null) { clientChannel.Close(); clientChannel.Dispose(); } } private class ClientOutputMessageInspector : IClientMessageInspector, IEndpointBehavior { public void AfterReceiveReply(ref Message reply, object correlationState) { } public object BeforeSendRequest(ref Message request, IClientChannel channel) { var property = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]; property.Headers.Add(ApiConstants.VersionHeaderName, ApiConstants.VersionHeaderContent); return null; } public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { clientRuntime.MessageInspectors.Add(this); } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { } public void Validate(ServiceEndpoint endpoint) { } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/ManagementClient.cs
C#
bsd
3,385
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion // TODO: To be replaced with official REST client once available using Lokad.Cloud.Management.Azure.Entities; using Lokad.Cloud.Management.Azure.InputParameters; namespace Lokad.Cloud.Management.Azure { /// <summary> /// Synchronous wrappers around the asynchronous web service channel. /// </summary> public static class SynchronousApiExtensionMethods { /// <summary> /// Gets the result of an asynchronous operation. /// </summary> public static Operation GetOperationStatus(this IAzureServiceManagement proxy, string subscriptionId, string operationId) { return proxy.EndGetOperationStatus(proxy.BeginGetOperationStatus(subscriptionId, operationId, null, null)); } /// <summary> /// Swaps the deployment to a production slot. /// </summary> public static void SwapDeployment(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, SwapDeploymentInput input) { proxy.EndSwapDeployment(proxy.BeginSwapDeployment(subscriptionId, serviceName, input, null, null)); } /// <summary> /// Creates a deployment. /// </summary> public static void CreateOrUpdateDeployment(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentSlot, CreateDeploymentInput input) { proxy.EndCreateOrUpdateDeployment(proxy.BeginCreateOrUpdateDeployment(subscriptionId, serviceName, deploymentSlot, input, null, null)); } /// <summary> /// Deletes the specified deployment. This works against either through the deployment name. /// </summary> public static void DeleteDeployment(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentName) { proxy.EndDeleteDeployment(proxy.BeginDeleteDeployment(subscriptionId, serviceName, deploymentName, null, null)); } /// <summary> /// Deletes the specified deployment. This works against either through the slot name. /// </summary> public static void DeleteDeploymentBySlot(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentSlot) { proxy.EndDeleteDeploymentBySlot(proxy.BeginDeleteDeploymentBySlot(subscriptionId, serviceName, deploymentSlot, null, null)); } /// <summary> /// Gets the specified deployment details. /// </summary> public static Deployment GetDeployment(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentName) { return proxy.EndGetDeployment(proxy.BeginGetDeployment(subscriptionId, serviceName, deploymentName, null, null)); } /// <summary> /// Gets the specified deployment details. /// </summary> public static Deployment GetDeploymentBySlot(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentSlot) { return proxy.EndGetDeploymentBySlot(proxy.BeginGetDeploymentBySlot(subscriptionId, serviceName, deploymentSlot, null, null)); } /// <summary> /// Initiates a change to the deployment. This works against through the deployment name. /// </summary> public static void ChangeConfiguration(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentName, ChangeConfigurationInput input) { proxy.EndChangeConfiguration(proxy.BeginChangeConfiguration(subscriptionId, serviceName, deploymentName, input, null, null)); } /// <summary> /// Initiates a change to the deployment. This works against through the slot name. /// </summary> public static void ChangeConfigurationBySlot(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentSlot, ChangeConfigurationInput input) { proxy.EndChangeConfigurationBySlot(proxy.BeginChangeConfigurationBySlot(subscriptionId, serviceName, deploymentSlot, input, null, null)); } /// <summary> /// Initiates a change to the deployment. This works against through the deployment name. /// </summary> public static void UpdateDeploymentStatus(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentName, UpdateDeploymentStatusInput input) { proxy.EndUpdateDeploymentStatus(proxy.BeginUpdateDeploymentStatus(subscriptionId, serviceName, deploymentName, input, null, null)); } /// <summary> /// Initiates a change to the deployment. This works against through the slot name. /// </summary> public static void UpdateDeploymentStatusBySlot(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentSlot, UpdateDeploymentStatusInput input) { proxy.EndUpdateDeploymentStatusBySlot(proxy.BeginUpdateDeploymentStatusBySlot(subscriptionId, serviceName, deploymentSlot, input, null, null)); } /// <summary> /// Initiates an deployment upgrade. /// </summary> public static void UpgradeDeployment(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentName, UpgradeDeploymentInput input) { proxy.EndUpgradeDeployment(proxy.BeginUpgradeDeployment(subscriptionId, serviceName, deploymentName, input, null, null)); } /// <summary> /// Initiates an deployment upgrade through the slot name. /// </summary> public static void UpgradeDeploymentBySlot(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentSlot, UpgradeDeploymentInput input) { proxy.EndUpgradeDeploymentBySlot(proxy.BeginUpgradeDeploymentBySlot(subscriptionId, serviceName, deploymentSlot, input, null, null)); } /// <summary> /// Initiates an deployment upgrade. /// </summary> public static void WalkUpgradeDomain(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentName, WalkUpgradeDomainInput input) { proxy.EndWalkUpgradeDomain(proxy.BeginWalkUpgradeDomain(subscriptionId, serviceName, deploymentName, input, null, null)); } /// <summary> /// Initiates an deployment upgrade through the slot name. /// </summary> public static void WalkUpgradeDomainBySlot(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string deploymentSlot, WalkUpgradeDomainInput input) { proxy.EndWalkUpgradeDomainBySlot(proxy.BeginWalkUpgradeDomainBySlot(subscriptionId, serviceName, deploymentSlot, input, null, null)); } /// <summary> /// Lists the affinity groups associated with the specified subscription. /// </summary> public static AffinityGroupList ListAffinityGroups(this IAzureServiceManagement proxy, string subscriptionId) { return proxy.EndListAffinityGroups(proxy.BeginListAffinityGroups(subscriptionId, null, null)); } /// <summary> /// Get properties for the specified affinity group. /// </summary> public static AffinityGroup GetAffinityGroup(this IAzureServiceManagement proxy, string subscriptionId, string affinityGroupName) { return proxy.EndGetAffinityGroup(proxy.BeginGetAffinityGroup(subscriptionId, affinityGroupName, null, null)); } /// <summary> /// Lists the certificates associated with a given subscription. /// </summary> public static CertificateList ListCertificates(this IAzureServiceManagement proxy, string subscriptionId, string serviceName) { return proxy.EndListCertificates(proxy.BeginListCertificates(subscriptionId, serviceName, null, null)); } /// <summary> /// Gets public data for the given certificate. /// </summary> public static Certificate GetCertificate(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string algorithm, string thumbprint) { return proxy.EndGetCertificate(proxy.BeginGetCertificate(subscriptionId, serviceName, algorithm, thumbprint, null, null)); } /// <summary> /// Adds certificates to the given subscription. /// </summary> public static void AddCertificates(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, CertificateFileInput input) { proxy.EndAddCertificates(proxy.BeginAddCertificates(subscriptionId, serviceName, input, null, null)); } /// <summary> /// Deletes the given certificate. /// </summary> public static void DeleteCertificate(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, string algorithm, string thumbprint) { proxy.EndDeleteCertificate(proxy.BeginDeleteCertificate(subscriptionId, serviceName, algorithm, thumbprint, null, null)); } /// <summary> /// Lists the hosted services associated with a given subscription. /// </summary> public static HostedServiceList ListHostedServices(this IAzureServiceManagement proxy, string subscriptionId) { return proxy.EndListHostedServices(proxy.BeginListHostedServices(subscriptionId, null, null)); } /// <summary> /// Gets the properties for the specified hosted service. /// </summary> public static HostedService GetHostedService(this IAzureServiceManagement proxy, string subscriptionId, string serviceName) { return proxy.EndGetHostedService(proxy.BeginGetHostedService(subscriptionId, serviceName, null, null)); } /// <summary> /// Gets the detailed properties for the specified hosted service. /// </summary> public static HostedService GetHostedServiceWithDetails(this IAzureServiceManagement proxy, string subscriptionId, string serviceName, bool embedDetail) { return proxy.EndGetHostedServiceWithDetails(proxy.BeginGetHostedServiceWithDetails(subscriptionId, serviceName, embedDetail, null, null)); } /// <summary> /// Lists the storage services associated with a given subscription. /// </summary> public static StorageServiceList ListStorageServices(this IAzureServiceManagement proxy, string subscriptionId) { return proxy.EndListStorageServices(proxy.BeginListStorageServices(subscriptionId, null, null)); } /// <summary> /// Gets a storage service. /// </summary> public static StorageService GetStorageService(this IAzureServiceManagement proxy, string subscriptionId, string name) { return proxy.EndGetStorageService(proxy.BeginGetStorageService(subscriptionId, name, null, null)); } /// <summary> /// Gets the key of a storage service. /// </summary> public static StorageService GetStorageKeys(this IAzureServiceManagement proxy, string subscriptionId, string name) { return proxy.EndGetStorageKeys(proxy.BeginGetStorageKeys(subscriptionId, name, null, null)); } /// <summary> /// Regenerates keys associated with a storage service. /// </summary> public static StorageService RegenerateStorageServiceKeys(this IAzureServiceManagement proxy, string subscriptionId, string name, RegenerateKeysInput regenerateKeys) { return proxy.EndRegenerateStorageServiceKeys(proxy.BeginRegenerateStorageServiceKeys(subscriptionId, name, regenerateKeys, null, null)); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/ExtensionMethods.cs
C#
bsd
11,755
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System.Collections.Generic; using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.Entities { /// <summary> /// Role Instance /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class RoleInstance { [DataMember(Order = 1)] public string RoleName { get; set; } [DataMember(Order = 2)] public string InstanceName { get; set; } [DataMember(Order = 3)] public RoleInstanceStatus InstanceStatus { get; set; } public ExtensionDataObject ExtensionData { get; set; } } public enum RoleInstanceStatus { Initializing, Ready, Busy, Stopping, Stopped, Unresponsive } /// <summary> /// List of role instances /// </summary> [CollectionDataContract(Name = "RoleInstanceList", ItemName = "RoleInstance", Namespace = ApiConstants.XmlNamespace)] public class RoleInstanceList : List<RoleInstance> { public RoleInstanceList() { } public RoleInstanceList(IEnumerable<RoleInstance> roles) : base(roles) { } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/Entities/RoleInstance.cs
C#
bsd
1,771
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.Entities { /// <summary> /// Hosted Service /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class HostedService : IExtensibleDataObject { [DataMember(Order = 1)] public Uri Url { get; set; } [DataMember(Order = 2, EmitDefaultValue = false)] public string ServiceName { get; set; } [DataMember(Order = 3, EmitDefaultValue = false)] public HostedServiceProperties HostedServiceProperties { get; set; } [DataMember(Order = 4, EmitDefaultValue = false)] public DeploymentList Deployments { get; set; } public ExtensionDataObject ExtensionData { get; set; } } /// <summary> /// Hosted Service Properties /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class HostedServiceProperties : IExtensibleDataObject { [DataMember(Order = 1)] public string Description { get; set; } [DataMember(Order = 2, EmitDefaultValue = false)] public string AffinityGroup { get; set; } [DataMember(Order = 3, EmitDefaultValue = false)] public string Location { get; set; } /// <remarks>Base64-Encoded</remarks> [DataMember(Order = 4)] public string Label { get; set; } public ExtensionDataObject ExtensionData { get; set; } } /// <summary> /// List of host services /// </summary> [CollectionDataContract(Name = "HostedServices", ItemName = "HostedService", Namespace = ApiConstants.XmlNamespace)] public class HostedServiceList : List<HostedService> { public HostedServiceList() { } public HostedServiceList(IEnumerable<HostedService> hostedServices) : base(hostedServices) { } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/Entities/HostedService.cs
C#
bsd
2,502
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.Entities { /// <summary> /// Certificate /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class Certificate : IExtensibleDataObject { [DataMember(Order = 1, EmitDefaultValue = false)] public Uri CertificateUrl { get; set; } [DataMember(Order = 2, EmitDefaultValue = false)] public string Thumbprint { get; set; } [DataMember(Order = 3, EmitDefaultValue = false)] public string ThumbprintAlgorithm { get; set; } /// <remarks>Base64-Encoded X509</remarks> [DataMember(Order = 4, EmitDefaultValue = false)] public string Data { get; set; } public ExtensionDataObject ExtensionData { get; set; } } /// <summary> /// List of certificates /// </summary> [CollectionDataContract(Name = "Certificates", ItemName = "Certificate", Namespace = ApiConstants.XmlNamespace)] public class CertificateList : List<Certificate> { public CertificateList() { } public CertificateList(IEnumerable<Certificate> certificateList) : base(certificateList) { } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/Entities/Certificate.cs
C#
bsd
1,904
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System.Collections.Generic; using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.Entities { /// <summary> /// Affinity Group /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class AffinityGroup : IExtensibleDataObject { [DataMember(Order = 1, EmitDefaultValue = false)] public string Name { get; set; } /// <remarks>Base64-Encoded</remarks> [DataMember(Order = 2)] public string Label { get; set; } [DataMember(Order = 3)] public string Description { get; set; } [DataMember(Order = 4)] public string Location { get; set; } [DataMember(Order = 5, EmitDefaultValue = false)] public HostedServiceList HostedServices { get; set; } [DataMember(Order = 6, EmitDefaultValue = false)] public StorageServiceList StorageServices { get; set; } public ExtensionDataObject ExtensionData { get; set; } } /// <summary> /// List of affinity groups /// </summary> [CollectionDataContract(Name = "AffinityGroups", ItemName = "AffinityGroup", Namespace = ApiConstants.XmlNamespace)] public class AffinityGroupList : List<AffinityGroup> { public AffinityGroupList() { } public AffinityGroupList(IEnumerable<AffinityGroup> affinityGroups) : base(affinityGroups) { } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/Entities/AffinityGroup.cs
C#
bsd
2,036
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.Entities { /// <summary> /// Deployment /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class Deployment : IExtensibleDataObject { [DataMember(Order = 1, EmitDefaultValue = false)] public string Name { get; set; } [DataMember(Order = 2)] public DeploymentSlot DeploymentSlot { get; set; } [DataMember(Order = 3, EmitDefaultValue = false)] public string PrivateID { get; set; } [DataMember(Order = 4)] public DeploymentStatus Status { get; set; } /// <remarks>Base64-Encoded</remarks> [DataMember(Order = 5, EmitDefaultValue = false)] public string Label { get; set; } [DataMember(Order = 6, EmitDefaultValue = false)] public Uri Url { get; set; } /// <remarks>Base64-Encoded</remarks> [DataMember(Order = 7, EmitDefaultValue = false)] public string Configuration { get; set; } [DataMember(Order = 8, EmitDefaultValue = false)] public RoleInstanceList RoleInstanceList { get; set; } [DataMember(Order = 9, EmitDefaultValue = false)] public RoleList RoleList { get; set; } [DataMember(Order = 10, EmitDefaultValue = false)] public UpgradeStatus UpgradeStatus { get; set; } [DataMember(Order = 11, EmitDefaultValue = false)] public int UpgradeDomainCount { get; set; } public ExtensionDataObject ExtensionData { get; set; } } public enum DeploymentStatus { Running, Suspended, RunningTransitioning, SuspendedTransitioning, Starting, Suspending, Deploying, Deleting, } public enum DeploymentSlot { Staging, Production, } /// <summary> /// Deployment Upgrade Status /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class UpgradeStatus : IExtensibleDataObject { [DataMember(Order = 1)] public UpgradeMode UpgradeType { get; set; } [DataMember(Order = 2)] public UpgradeDomainState CurrentUpgradeDomainState { get; set; } [DataMember(Order = 3)] public int CurrentUpgradeDomain { get; set; } public ExtensionDataObject ExtensionData { get; set; } } public enum UpgradeMode { Auto, Manual } public enum UpgradeDomainState { Before, During } /// <summary> /// List of deployments /// </summary> [CollectionDataContract(Name = "Deployments", ItemName = "Deployment", Namespace = ApiConstants.XmlNamespace)] public class DeploymentList : List<Deployment> { public DeploymentList() { } public DeploymentList(IEnumerable<Deployment> deployments) : base(deployments) { } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/Entities/Deployment.cs
C#
bsd
3,431
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.Entities { /// <summary> /// Storage Service /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class StorageService : IExtensibleDataObject { [DataMember(Order = 1)] public Uri Url { get; set; } [DataMember(Order = 2, EmitDefaultValue = false)] public string ServiceName { get; set; } [DataMember(Order = 3, EmitDefaultValue = false)] public StorageServiceProperties StorageServiceProperties { get; set; } [DataMember(Order = 4, EmitDefaultValue = false)] public StorageServiceKeys StorageServiceKeys { get; set; } public ExtensionDataObject ExtensionData { get; set; } } /// <summary> /// Storage Service Properties /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class StorageServiceProperties : IExtensibleDataObject { [DataMember(Order = 1)] public string Description { get; set; } [DataMember(Order = 2, EmitDefaultValue = false)] public string AffinityGroup { get; set; } [DataMember(Order = 3, EmitDefaultValue = false)] public string Location { get; set; } [DataMember(Order = 4)] public string Label { get; set; } public ExtensionDataObject ExtensionData { get; set; } } /// <summary> /// Storage Service Keys /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class StorageServiceKeys : IExtensibleDataObject { [DataMember(Order = 1)] public string Primary { get; set; } [DataMember(Order = 2)] public string Secondary { get; set; } public ExtensionDataObject ExtensionData { get; set; } } /// <summary> /// List of storage services /// </summary> [CollectionDataContract(Name = "StorageServices", ItemName = "StorageService", Namespace = ApiConstants.XmlNamespace)] public class StorageServiceList : List<StorageService> { public StorageServiceList() { } public StorageServiceList(IEnumerable<StorageService> storageServices) : base(storageServices) { } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/Entities/StorageService.cs
C#
bsd
2,871
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.Entities { /// <summary> /// Asynchronous Operation /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class Operation : IExtensibleDataObject { [DataMember(Name = "ID", Order = 1)] public string OperationTrackingId { get; set; } [DataMember(Order = 2)] public OperationStatus Status { get; set; } [DataMember(Order = 3, EmitDefaultValue = false)] public int HttpStatusCode { get; set; } [DataMember(Order = 4, EmitDefaultValue = false)] public OperationError Error { get; set; } public ExtensionDataObject ExtensionData { get; set; } } public enum OperationStatus { InProgress, Succeeded, Failed, } /// <summary> /// Asynchronous Operation Error /// </summary> [DataContract(Name = "Error", Namespace = ApiConstants.XmlNamespace)] public class OperationError : IExtensibleDataObject { [DataMember(Order = 1)] public OperationErrorCode Code { get; set; } [DataMember(Order = 2)] public string Message { get; set; } public ExtensionDataObject ExtensionData { get; set; } } public enum OperationErrorCode { MissingOrIncorrectVersionHeader, InvalidRequest, InvalidXmlRequest, InvalidContentType, MissingOrInvalidRequiredQueryParameter, InvalidHttpVerb, InternalError, BadRequest, AuthenticationFailed, ResourceNotFound, SubscriptionDisabled, ServerBusy, TooManyRequests, ConflictError, } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/Entities/Operation.cs
C#
bsd
2,260
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System.Collections.Generic; using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.Entities { /// <summary> /// Role Instance /// </summary> [DataContract(Namespace = ApiConstants.XmlNamespace)] public class Role { [DataMember(Order = 1)] public string RoleName { get; set; } [DataMember(Order = 2)] public string OperatingSystemVersion { get; set; } public ExtensionDataObject ExtensionData { get; set; } } /// <summary> /// List of role instances /// </summary> [CollectionDataContract(Name = "RoleList", ItemName = "Role", Namespace = ApiConstants.XmlNamespace)] public class RoleList : List<Role> { public RoleList() { } public RoleList(IEnumerable<Role> roles) : base(roles) { } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/Entities/Role.cs
C#
bsd
1,510
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.InputParameters { [DataContract(Name = "Swap", Namespace = ApiConstants.XmlNamespace)] public class SwapDeploymentInput : IExtensibleDataObject { [DataMember(Order = 1)] public string Production { get; set; } [DataMember(Order = 2)] public string SourceDeployment { get; set; } public ExtensionDataObject ExtensionData { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/InputParameters/SwapDeploymentInput.cs
C#
bsd
1,161
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.InputParameters { [DataContract(Name = "CertificateFile", Namespace = ApiConstants.XmlNamespace)] public class CertificateFileInput : IExtensibleDataObject { [DataMember(Order = 1)] public string Data { get; set; } [DataMember(Order = 2)] public string CertificateFormat { get; set; } [DataMember(Order = 3)] public string Password { get; set; } public ExtensionDataObject ExtensionData { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/InputParameters/CertificateFileInput.cs
C#
bsd
1,237
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.InputParameters { [DataContract(Name = "ChangeConfiguration", Namespace = ApiConstants.XmlNamespace)] public class ChangeConfigurationInput : IExtensibleDataObject { [DataMember(Order = 1)] public string Configuration { get; set; } public ExtensionDataObject ExtensionData { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/InputParameters/ChangeConfigurationInput.cs
C#
bsd
1,107
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.InputParameters { [DataContract(Name = "WalkUpgradeDomain", Namespace = ApiConstants.XmlNamespace)] public class WalkUpgradeDomainInput : IExtensibleDataObject { [DataMember(Order = 1)] public int UpgradeDomain { get; set; } public ExtensionDataObject ExtensionData { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/InputParameters/WalkUpgradeDomainInput.cs
C#
bsd
1,100
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.InputParameters { [DataContract(Name = "RegenerateKeys", Namespace = ApiConstants.XmlNamespace)] public class RegenerateKeysInput : IExtensibleDataObject { [DataMember(Order = 1)] public KeyType KeyType { get; set; } public ExtensionDataObject ExtensionData { get; set; } } public enum KeyType { Primary, Secondary, } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/InputParameters/RegenerateKeysInput.cs
C#
bsd
1,150
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System; using System.Runtime.Serialization; namespace Lokad.Cloud.Management.Azure.InputParameters { [DataContract(Name = "CreateDeployment", Namespace = ApiConstants.XmlNamespace)] public class CreateDeploymentInput : IExtensibleDataObject { [DataMember(Order = 1)] public string Name { get; set; } [DataMember(Order = 2)] public Uri PackageUrl { get; set; } [DataMember(Order = 3)] public string Label { get; set; } [DataMember(Order = 4)] public string Configuration { get; set; } public ExtensionDataObject ExtensionData { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/InputParameters/CreateDeploymentInput.cs
C#
bsd
1,315
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System.Runtime.Serialization; using Lokad.Cloud.Management.Azure.Entities; namespace Lokad.Cloud.Management.Azure.InputParameters { [DataContract(Name = "UpdateDeploymentStatus", Namespace = ApiConstants.XmlNamespace)] public class UpdateDeploymentStatusInput : IExtensibleDataObject { [DataMember(Order = 1)] public DeploymentStatus Status { get; set; } public ExtensionDataObject ExtensionData { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/InputParameters/UpdateDeploymentStatusInput.cs
C#
bsd
1,162
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System; using System.Runtime.Serialization; using Lokad.Cloud.Management.Azure.Entities; namespace Lokad.Cloud.Management.Azure.InputParameters { [DataContract(Name = "UpgradeDeployment", Namespace = ApiConstants.XmlNamespace)] public class UpgradeDeploymentInput : IExtensibleDataObject { [DataMember(Order = 1)] public UpgradeMode Mode { get; set; } [DataMember(Order = 2)] public Uri PackageUrl { get; set; } [DataMember(Order = 3)] public string Configuration { get; set; } [DataMember(Order = 4)] public string Label { get; set; } [DataMember(Order = 5)] public string RoleToUpgrade { get; set; } public ExtensionDataObject ExtensionData { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/InputParameters/UpgradeDeploymentInput.cs
C#
bsd
1,442
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion using System; using System.ServiceModel; using System.ServiceModel.Web; using Lokad.Cloud.Management.Azure.Entities; using Lokad.Cloud.Management.Azure.InputParameters; // TODO: To be replaced with official REST client once available namespace Lokad.Cloud.Management.Azure { /// <summary> /// Windows Azure Service Management API. /// </summary> [ServiceContract(Namespace = ApiConstants.XmlNamespace)] public interface IAzureServiceManagement { /// <summary> /// Gets the result of an asynchronous operation. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/operations/{operationTrackingId}")] IAsyncResult BeginGetOperationStatus(string subscriptionId, string operationTrackingId, AsyncCallback callback, object state); Operation EndGetOperationStatus(IAsyncResult asyncResult); /// <summary> /// Swaps the deployment to a production slot. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}")] IAsyncResult BeginSwapDeployment(string subscriptionId, string serviceName, SwapDeploymentInput input, AsyncCallback callback, object state); void EndSwapDeployment(IAsyncResult asyncResult); /// <summary> /// Creates a deployment. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deploymentslots/{deploymentSlot}")] IAsyncResult BeginCreateOrUpdateDeployment(string subscriptionId, string serviceName, string deploymentSlot, CreateDeploymentInput input, AsyncCallback callback, object state); void EndCreateOrUpdateDeployment(IAsyncResult asyncResult); /// <summary> /// Deletes the specified deployment. This works against through the deployment name. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "DELETE", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deployments/{deploymentName}")] IAsyncResult BeginDeleteDeployment(string subscriptionId, string serviceName, string deploymentName, AsyncCallback callback, object state); void EndDeleteDeployment(IAsyncResult asyncResult); /// <summary> /// Deletes the specified deployment. This works against through the slot name. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "DELETE", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deploymentslots/{deploymentSlot}")] IAsyncResult BeginDeleteDeploymentBySlot(string subscriptionId, string serviceName, string deploymentSlot, AsyncCallback callback, object state); void EndDeleteDeploymentBySlot(IAsyncResult asyncResult); /// <summary> /// Gets the specified deployment details. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deployments/{deploymentName}")] IAsyncResult BeginGetDeployment(string subscriptionId, string serviceName, string deploymentName, AsyncCallback callback, object state); Deployment EndGetDeployment(IAsyncResult asyncResult); /// <summary> /// Gets the specified deployment details. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deploymentslots/{deploymentSlot}")] IAsyncResult BeginGetDeploymentBySlot(string subscriptionId, string serviceName, string deploymentSlot, AsyncCallback callback, object state); Deployment EndGetDeploymentBySlot(IAsyncResult asyncResult); /// <summary> /// Initiates a change to the deployment. This works against through the deployment name. /// This is an asynchronous operation /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deployments/{deploymentName}/?comp=config")] IAsyncResult BeginChangeConfiguration(string subscriptionId, string serviceName, string deploymentName, ChangeConfigurationInput input, AsyncCallback callback, object state); void EndChangeConfiguration(IAsyncResult asyncResult); /// <summary> /// Initiates a change to the deployment. This works against through the slot name. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deploymentslots/{deploymentSlot}/?comp=config")] IAsyncResult BeginChangeConfigurationBySlot(string subscriptionId, string serviceName, string deploymentSlot, ChangeConfigurationInput input, AsyncCallback callback, object state); void EndChangeConfigurationBySlot(IAsyncResult asyncResult); /// <summary> /// Initiates a change to the deployment. This works against through the deployment name. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deployments/{deploymentName}/?comp=status")] IAsyncResult BeginUpdateDeploymentStatus(string subscriptionId, string serviceName, string deploymentName, UpdateDeploymentStatusInput input, AsyncCallback callback, object state); void EndUpdateDeploymentStatus(IAsyncResult asyncResult); /// <summary> /// Initiates a change to the deployment. This works against through the slot name. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deploymentslots/{deploymentSlot}/?comp=status")] IAsyncResult BeginUpdateDeploymentStatusBySlot(string subscriptionId, string serviceName, string deploymentSlot, UpdateDeploymentStatusInput input, AsyncCallback callback, object state); void EndUpdateDeploymentStatusBySlot(IAsyncResult asyncResult); /// <summary> /// Initiates an deployment upgrade. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deployments/{deploymentName}/?comp=upgrade")] IAsyncResult BeginUpgradeDeployment(string subscriptionId, string serviceName, string deploymentName, UpgradeDeploymentInput input, AsyncCallback callback, object state); void EndUpgradeDeployment(IAsyncResult asyncResult); /// <summary> /// Initiates an deployment upgrade through the slot name. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deploymentslots/{deploymentSlot}/?comp=upgrade")] IAsyncResult BeginUpgradeDeploymentBySlot(string subscriptionId, string serviceName, string deploymentSlot, UpgradeDeploymentInput input, AsyncCallback callback, object state); void EndUpgradeDeploymentBySlot(IAsyncResult asyncResult); /// <summary> /// Initiates an deployment upgrade. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deployments/{deploymentName}/?comp=walkupgradedomain")] IAsyncResult BeginWalkUpgradeDomain(string subscriptionId, string serviceName, string deploymentName, WalkUpgradeDomainInput input, AsyncCallback callback, object state); void EndWalkUpgradeDomain(IAsyncResult asyncResult); /// <summary> /// Initiates an deployment upgrade through the slot name. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/deploymentslots/{deploymentSlot}/?comp=walkupgradedomain")] IAsyncResult BeginWalkUpgradeDomainBySlot(string subscriptionId, string serviceName, string deploymentSlot, WalkUpgradeDomainInput input, AsyncCallback callback, object state); void EndWalkUpgradeDomainBySlot(IAsyncResult asyncResult); /// <summary> /// Lists the affinity groups associated with the specified subscription. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/affinitygroups")] IAsyncResult BeginListAffinityGroups(string subscriptionId, AsyncCallback callback, object state); AffinityGroupList EndListAffinityGroups(IAsyncResult asyncResult); /// <summary> /// Get properties for the specified affinity group. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/affinitygroups/{affinityGroupName}")] IAsyncResult BeginGetAffinityGroup(string subscriptionId, string affinityGroupName, AsyncCallback callback, object state); AffinityGroup EndGetAffinityGroup(IAsyncResult asyncResult); /// <summary> /// Lists the certificates associated with a given subscription. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/certificates")] IAsyncResult BeginListCertificates(string subscriptionId, string serviceName, AsyncCallback callback, object state); CertificateList EndListCertificates(IAsyncResult asyncResult); /// <summary> /// Gets public data for the given certificate. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/certificates/{thumbprintalgorithm}-{thumbprint_in_hex}")] IAsyncResult BeginGetCertificate(string subscriptionId, string serviceName, string thumbprintalgorithm, string thumbprint_in_hex, AsyncCallback callback, object state); Certificate EndGetCertificate(IAsyncResult asyncResult); /// <summary> /// Adds certificates to the given subscription. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/certificates")] IAsyncResult BeginAddCertificates(string subscriptionId, string serviceName, CertificateFileInput input, AsyncCallback callback, object state); void EndAddCertificates(IAsyncResult asyncResult); /// <summary> /// Deletes the given certificate. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "DELETE", UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}/certificates/{thumbprintalgorithm}-{thumbprint_in_hex}")] IAsyncResult BeginDeleteCertificate(string subscriptionId, string serviceName, string thumbprintalgorithm, string thumbprint_in_hex, AsyncCallback callback, object state); void EndDeleteCertificate(IAsyncResult asyncResult); /// <summary> /// Lists the hosted services associated with a given subscription. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/services/hostedservices")] IAsyncResult BeginListHostedServices(string subscriptionId, AsyncCallback callback, object state); HostedServiceList EndListHostedServices(IAsyncResult asyncResult); /// <summary> /// Gets the properties for the specified hosted service. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}")] IAsyncResult BeginGetHostedService(string subscriptionId, string serviceName, AsyncCallback callback, object state); HostedService EndGetHostedService(IAsyncResult asyncResult); /// <summary> /// Gets the detailed properties for the specified hosted service. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/services/hostedservices/{serviceName}?embed-detail={embedDetail}")] IAsyncResult BeginGetHostedServiceWithDetails(string subscriptionId, string serviceName, bool embedDetail, AsyncCallback callback, object state); HostedService EndGetHostedServiceWithDetails(IAsyncResult asyncResult); /// <summary> /// Lists the storage services associated with a given subscription. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/services/storageservices")] IAsyncResult BeginListStorageServices(string subscriptionId, AsyncCallback callback, object state); StorageServiceList EndListStorageServices(IAsyncResult asyncResult); /// <summary> /// Gets a storage service. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/services/storageservices/{serviceName}")] IAsyncResult BeginGetStorageService(string subscriptionId, string serviceName, AsyncCallback callback, object state); StorageService EndGetStorageService(IAsyncResult asyncResult); /// <summary> /// Gets the key of a storage service. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/services/storageservices/{serviceName}/keys")] IAsyncResult BeginGetStorageKeys(string subscriptionId, string serviceName, AsyncCallback callback, object state); StorageService EndGetStorageKeys(IAsyncResult asyncResult); /// <summary> /// Regenerates keys associated with a storage service. /// </summary> [OperationContract(AsyncPattern = true)] [WebInvoke(Method = "POST", UriTemplate = @"{subscriptionId}/services/storageservices/{serviceName}/keys?action=regenerate")] IAsyncResult BeginRegenerateStorageServiceKeys(string subscriptionId, string serviceName, RegenerateKeysInput regenerateKeys, AsyncCallback callback, object state); StorageService EndRegenerateStorageServiceKeys(IAsyncResult asyncResult); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/IAzureServiceManagement.cs
C#
bsd
14,526
#region Copyright (c) Lokad 2010, Microsoft // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ // // Based on Microsoft Sample Code from http://code.msdn.microsoft.com/azurecmdlets //--------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- #endregion // TODO: To be replaced with official REST client once available namespace Lokad.Cloud.Management.Azure { internal static class ApiConstants { public const string ServiceEndpoint = "https://management.core.windows.net"; public const string XmlNamespace = "http://schemas.microsoft.com/windowsazure"; public const string VersionHeaderName = "x-ms-version"; public const string OperationTrackingIdHeader = "x-ms-request-id"; public const string VersionHeaderContent = "2009-10-01"; } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/Azure/ApiConstants.cs
C#
bsd
1,227
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.Management; using Lokad.Cloud.ServiceFabric; using Lokad.Cloud.Storage; namespace Lokad.Cloud { /// <summary>IoC argument for <see cref="CloudService"/> and other /// cloud abstractions.</summary> /// <remarks>This argument will be populated through Inversion Of Control (IoC) /// by the Lokad.Cloud framework itself. This class is placed in the /// <c>Lokad.Cloud.Framework</c> for convenience while inheriting a /// <see cref="CloudService"/>.</remarks> public class CloudInfrastructureProviders : CloudStorageProviders { /// <summary>Abstracts the Management API.</summary> public IProvisioningProvider Provisioning { get; set; } /// <summary>IoC constructor.</summary> public CloudInfrastructureProviders( IBlobStorageProvider blobStorage, IQueueStorageProvider queueStorage, ITableStorageProvider tableStorage, Storage.Shared.Logging.ILog log, IProvisioningProvider provisioning, IRuntimeFinalizer runtimeFinalizer) : base(blobStorage, queueStorage, tableStorage, runtimeFinalizer, log) { Provisioning = provisioning; } /// <summary>IoC constructor 2.</summary> public CloudInfrastructureProviders( CloudStorageProviders storageProviders, IProvisioningProvider provisioning) : base(storageProviders) { Provisioning = provisioning; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/CloudInfrastructureProviders.cs
C#
bsd
1,716
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; namespace Lokad.Cloud { /// <summary>Maps types to storage names, and vice-versa.</summary> /// <remarks> /// Spec on queue names: http://msdn.microsoft.com/en-us/library/dd179349.aspx /// Spec on container names: http://msdn.microsoft.com/en-us/library/dd135715.aspx /// </remarks> public static class TypeMapper { public static string GetStorageName(Type type) { var name = type.FullName.ToLowerInvariant().Replace(".", "-"); // TODO: need a smarter behavior with long type name. if(name.Length > 63) { throw new ArgumentOutOfRangeException("type", "Type name is too long for auto-naming."); } return name; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/TypeMapperProvider.cs
C#
bsd
839
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PingPongClient")] [assembly: AssemblyDescription("Sample client for Lokad.Cloud")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PingPongClient")] [assembly: AssemblyCopyright("Copyright © Lokad 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ebfdce4f-1f33-476f-8699-0a1d9a7938fc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zyyin2005-lokad
Samples/Source/PingPong/PingPongClient/Properties/AssemblyInfo.cs
C#
bsd
1,474
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using Lokad.Cloud.Storage; using PingPongClient.Properties; namespace PingPongClient { class Program { static void Main(string[] args) { var queues = CloudStorage.ForAzureConnectionString(Settings.Default.DataConnectionString).BuildQueueStorage(); var input = new[] {0.0, 1.0, 2.0}; // pushing item to the 'ping' queue queues.PutRange("ping", input); foreach(var x in input) { Console.Write("ping={0} ", x); } Console.WriteLine(); Console.WriteLine("Queued 3 items in 'ping'."); // items are going to be processed by the service // getting items from the 'pong' queue for(int i = 0; i < 100; i++) { foreach (var x in queues.Get<double>("pong", 10)) { Console.Write("pong={0} ", x); queues.Delete(x); } Console.Write("sleep 1000ms. "); System.Threading.Thread.Sleep(1000); Console.WriteLine(); } } } }
zyyin2005-lokad
Samples/Source/PingPong/PingPongClient/Program.cs
C#
bsd
1,102
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.ServiceFabric; namespace PingPong { /// <summary>Retrieving messages from 'ping' and put them in 'pong'.</summary> [QueueServiceSettings(AutoStart = true, QueueName = "ping")] public class PingPongService : QueueService<double> { protected override void Start(double x) { var y = x * x; // square operation Put(y, "pong"); // Optionaly, we could manually delete incoming messages, // but here, we let the framework deal with that. // Delete(x); } } }
zyyin2005-lokad
Samples/Source/PingPong/PingPongService/PingPong.cs
C#
bsd
666
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PingPongService")] [assembly: AssemblyDescription("Sample cloud service for Lokad.Cloud")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PingPong")] [assembly: AssemblyCopyright("Copyright © Lokad 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("87598c0a-9398-47d0-aaac-2b4376fd75de")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zyyin2005-lokad
Samples/Source/PingPong/PingPongService/Properties/AssemblyInfo.cs
C#
bsd
1,476
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SimpleBlob")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("SimpleBlob")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3c7e97b6-69bb-4626-8028-24d7d3ce7e2b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zyyin2005-lokad
Samples/Source/SimpleBlob/Properties/AssemblyInfo.cs
C#
bsd
1,450
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; using Lokad.Cloud.Storage; namespace SimpleBlob { [DataContract] class Book { [DataMember] public string Title { get; set; } [DataMember] public string Author { get; set; } } class BookName : BlobName<Book> { public override string ContainerName { get { return "books"; } // default container for 'Book' entities } [Rank(0)] public string Publisher { get; set;} // TreatDefaultAsNull = true, '0' will be ignored [Rank(1, true)] public int BookId { get; set;} } class Program { static void Main(string[] args) { // insert your own connection string here, or use one of the other options: var blobStorage = CloudStorage .ForAzureConnectionString("DefaultEndpointsProtocol=https;AccountName=YOURACCOUNT;AccountKey=YOURKEY") .BuildBlobStorage(); var potterBook = new Book { Author = "J. K. Rowling", Title = "Harry Potter" }; // Resulting blob name is: Bloomsbury Publishing/1 var potterRef = new BookName {Publisher = "Bloomsbury Publishing", BookId = 1}; var poemsBook = new Book { Author = "John Keats", Title = "Complete Poems" }; // Resulting blob name is: Harvard University Press/2 var poemsRef = new BookName {Publisher = "Harvard University Press", BookId = 2}; // writing entities to the storage blobStorage.PutBlob(potterRef, potterBook); blobStorage.PutBlob(poemsRef, poemsBook); // retrieving all entities from 'Bloomsbury Publishing' foreach (var book in blobStorage.ListBlobs(new BookName { Publisher = "Bloomsbury Publishing" })) { Console.WriteLine("{0} by {1}", book.Title, book.Author); } Console.WriteLine("Press enter to exit."); Console.ReadLine(); } } }
zyyin2005-lokad
Samples/Source/SimpleBlob/Program.cs
C#
bsd
2,263
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Drawing; using System.Windows.Forms; using System.Threading; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Samples.MapReduce { public partial class MainForm : Form { string _currentFileName; MapReduceJob<byte[], Histogram> _mapReduceJob; Histogram _currentHistogram; public MainForm() { InitializeComponent(); } private void _btnBrowse_Click(object sender, EventArgs e) { using(var dialog = new OpenFileDialog()) { dialog.Filter = "Image Files (*.bmp; *.jpg; *.png)|*.bmp;*.jpg;*.png"; dialog.Title = "Select Input Image File"; dialog.Multiselect = false; dialog.CheckFileExists = true; if(dialog.ShowDialog() == DialogResult.OK) { _currentFileName = dialog.FileName; _picPreview.ImageLocation = _currentFileName; _currentHistogram = null; _pnlHistogram.Refresh(); } } _btnStart.Enabled = _currentFileName != null; } private void _btnStart_Click(object sender, EventArgs e) { _btnStart.Enabled = false; _btnBrowse.Enabled = false; _prgProgress.Style = ProgressBarStyle.Marquee; _currentHistogram = null; _pnlHistogram.Refresh(); var storage = CloudStorage .ForAzureConnectionString(Properties.Settings.Default.DataConnectionString) .BuildStorageProviders(); _mapReduceJob = new MapReduceJob<byte[], Histogram>(storage.BlobStorage, storage.QueueStorage); // Do this asynchronously because it requires a few seconds ThreadPool.QueueUserWorkItem(s => { using(var input = (Bitmap)Bitmap.FromFile(_currentFileName)) { var slices = Helpers.SliceBitmapAsPng(input, 14); // Queue slices _mapReduceJob.PushItems(new HistogramMapReduceFunctions(), slices, 4); //_currentHistogram = Helpers.ComputeHistogram(input); //_pnlHistogram.Refresh(); } BeginInvoke(new Action(() => _timer.Start())); }); } private void _timer_Tick(object sender, EventArgs e) { _timer.Stop(); ThreadPool.QueueUserWorkItem(s => { // Check job status bool completed = _mapReduceJob.IsCompleted(); if (completed) { _currentHistogram = _mapReduceJob.GetResult(); _mapReduceJob.DeleteJobData(); } BeginInvoke(new Action(() => { if (completed) { _pnlHistogram.Refresh(); _btnStart.Enabled = true; _btnBrowse.Enabled = true; _prgProgress.Style = ProgressBarStyle.Blocks; } else _timer.Start(); })); }); } private void _pnlHistogram_Paint(object sender, PaintEventArgs e) { e.Graphics.Clear(_pnlHistogram.BackColor); if(_currentHistogram == null) return; double maxFreq = _currentHistogram.GetMaxFrequency(); for(int i = 0; i < _currentHistogram.Frequencies.Length; i++) { e.Graphics.DrawLine(Pens.Black, i, _pnlHistogram.Height, i, _pnlHistogram.Height - (float)(_pnlHistogram.Height * _currentHistogram.Frequencies[i] / maxFreq)); } } } }
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceClient/MainForm.cs
C#
bsd
3,262
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MapReduceClient")] [assembly: AssemblyDescription("Sample MAP-REDUCE client")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Lokad.Cloud")] [assembly: AssemblyCopyright("Copyright © Lokad 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0380224e-14b3-4955-9ac3-cff50f3c91ad")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceClient/Properties/AssemblyInfo.cs
C#
bsd
1,467
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Windows.Forms; namespace Lokad.Cloud.Samples.MapReduce { class Program { [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceClient/Program.cs
C#
bsd
458
 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lokad.Cloud.Samples.MapReduce { /// <summary> /// Implements map/reduce functions for the Histogram sample. /// </summary> public class HistogramMapReduceFunctions : IMapReduceFunctions { public object GetMapper() { return (Func<byte[], Histogram>)Helpers.ComputeHistogram; } public object GetReducer() { return (Func<Histogram, Histogram, Histogram>)Helpers.MergeHistograms; } } }
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceClientLib/HistogramMapReduceFunctions.cs
C#
bsd
532
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using Lokad.Cloud.Samples.MapReduce; using System.IO; using System.Drawing.Imaging; namespace Lokad.Cloud.Samples.MapReduce { /// <summary>Implements helper methods.</summary> public static class Helpers { /// <summary>Slices an input bitmap into several parts.</summary> /// <param name="input">The input bitmap.</param> /// <param name="sliceCount">The number of slices.</param> /// <returns>The slices.</returns> static Bitmap[] SliceBitmap(Bitmap input, int sliceCount) { // Simply split the bitmap in vertical slices var outputBitmaps = new Bitmap[sliceCount]; int sliceWidth = input.Width / sliceCount; int processedWidth = 0; for(int i = 0; i < sliceCount; i++) { // Last slice takes into account remaining pixels int currentWidth = i != sliceCount - 1 ? sliceWidth : input.Width - processedWidth; var currentSlice = new Bitmap(currentWidth, input.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); using(var graphics = Graphics.FromImage(currentSlice)) { graphics.DrawImage(input, -processedWidth, 0); } processedWidth += currentWidth; outputBitmaps[i] = currentSlice; } return outputBitmaps; } /// <summary>Slices an input bitmap into several parts.</summary> /// <param name="input">The input bitmap.</param> /// <param name="sliceCount">The number of slices.</param> /// <returns>The slices, saved as PNG and serialized in byte arrays.</returns> public static byte[][] SliceBitmapAsPng(Bitmap input, int sliceCount) { Bitmap[] slices = SliceBitmap(input, sliceCount); var dump = new byte[slices.Length][]; for(int i = 0; i < slices.Length; i++) { using(var stream = new MemoryStream()) { slices[i].Save(stream, ImageFormat.Png); dump[i] = stream.ToArray(); } slices[i].Dispose(); } return dump; } /// <summary>Computes the histogram of a bitpam.</summary> /// <param name="inputStream">The serialized, PNG format bitmap.</param> /// <returns>The histogram.</returns> public static Histogram ComputeHistogram(byte[] inputStream) { // This method is inefficient (GetPixel is slow) but easy to understand Bitmap input = null; using(var stream = new MemoryStream(inputStream)) { stream.Seek(0, SeekOrigin.Begin); input = (Bitmap)Bitmap.FromStream(stream); } var result = new Histogram(input.Width * input.Height); double increment = 1D / result.TotalPixels; for(int row = 0; row < input.Height; row++) { for(int col = 0; col < input.Width; col++) { Color pixel = input.GetPixel(col, row); int grayScale = (int)Math.Round(pixel.R * 0.3F + pixel.G * 0.59F + pixel.B * 0.11F); // Make sure the result is inside the freqs array (0-255) if(grayScale < 0) grayScale = 0; if(grayScale > Histogram.FrequenciesSize - 1) grayScale = Histogram.FrequenciesSize - 1; result.Frequencies[grayScale] += increment; } } return result; } /// <summary>Merges two histograms.</summary> /// <param name="hist1">The first histogram.</param> /// <param name="hist2">The second histogram.</param> /// <returns>The merged histogram.</returns> public static Histogram MergeHistograms(Histogram hist1, Histogram hist2) { var result = new Histogram(hist1.TotalPixels + hist2.TotalPixels); for(int i = 0; i < result.Frequencies.Length; i++) { result.Frequencies[i] = (hist1.Frequencies[i] * hist1.TotalPixels + hist2.Frequencies[i] * hist2.TotalPixels) / (double)result.TotalPixels; } return result; } } }
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceClientLib/Helpers.cs
C#
bsd
3,828
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MapReduceClient")] [assembly: AssemblyDescription("Sample MAP-REDUCE client library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Lokad.Cloud")] [assembly: AssemblyCopyright("Copyright © Lokad 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2807DD46-91E4-4796-AC29-AC8EFC01468D")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceClientLib/Properties/AssemblyInfo.cs
C#
bsd
1,475
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace Lokad.Cloud.Samples.MapReduce { /// <summary>Represents a picture histogram.</summary> [DataContract] public class Histogram { /// <summary>The size of the <see cref="M:Frequencies"/> array (2^8).</summary> public static readonly int FrequenciesSize = 256; /// <summary>An array of 256 items, each representing /// the frequency of each brightness level (0.0 to 1.0).</summary> [DataMember] public double[] Frequencies; /// <summary>The total number of pixels (weights the histogram).</summary> [DataMember] public int TotalPixels; protected Histogram() { } /// <summary>Initializes a new instance of the <see cref="T:Histogram"/> class.</summary> /// <param name="totalPixels">The total number of pixels.</param> public Histogram(int totalPixels) { Frequencies = new double[FrequenciesSize]; TotalPixels = totalPixels; } /// <summary>Gets the max frequency in the histogram (for scaling purposes).</summary> /// <returns>The max frequency.</returns> public double GetMaxFrequency() { return Frequencies.Max(); } } }
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceClientLib/Histogram.cs
C#
bsd
1,404
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MapReduceService")] [assembly: AssemblyDescription("Sample MAP-REDUCE service part of Lokad.Cloud")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Lokad.Cloud")] [assembly: AssemblyCopyright("Copyright © Lokad 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e1d2e5f0-ac90-4256-8403-d4645d30a068")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceService/Properties/AssemblyInfo.cs
C#
bsd
1,489
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Samples.MapReduce { /// <summary>Manages sets of blobs for map/reduce services.</summary> /// <typeparam name="TMapIn">The type of the items that are input in the map operation.</typeparam> /// <typeparam name="TMapOut">The type of the items that are output from the map operation.</typeparam> /// <typeparam name="TReduceOut">The type of the items that are output from the reduce operation.</typeparam> /// <remarks>All public mebers are thread-safe.</remarks> /// <seealso cref="MapReduceService"/> /// <seealso cref="MapReduceJob"/> public sealed class MapReduceBlobSet { /// <summary>The queue used for managing map/reduce work items (<seealso cref="T:BatchMessage"/>).</summary> internal const string JobsQueueName = "blobsets"; internal const string ContainerName = "blobsets"; internal const string ConfigPrefix = "config"; internal const string InputPrefix = "input"; internal const string ReducedPrefix = "reduced"; internal const string AggregatedPrefix = "aggregated"; internal const string CounterPrefix = "counter"; // Final blob names: // - blobsets/config/<job-name> -- map/reduce/aggregate functions plus number of queued blobsets -- read-only // - blobsets/input/<job-name>/<blob-guid> -- read-only // - blobsets/reduced/<job-name>/<blob-guid> -- write-only // - blobsets/aggregated/<job-name> -- write-only // - blobsets/counter/<job-name> -- read/write IBlobStorageProvider _blobStorage; IQueueStorageProvider _queueStorage; /// <summary>Initializes a new instance of the <see cref="T:MapReduceBlobSet"/> generic class.</summary> /// <param name="blobStorage">The blob storage provider.</param> /// <param name="queueStorage">The queue storage provider.</param> public MapReduceBlobSet(IBlobStorageProvider blobStorage, IQueueStorageProvider queueStorage) { if(null == blobStorage) throw new ArgumentNullException("blobStorage"); if(null == queueStorage) throw new ArgumentNullException("queueStorage"); _blobStorage = blobStorage; _queueStorage = queueStorage; } Maybe<MapReduceConfiguration> GetJobConfig(string jobName) { var configBlobName = MapReduceConfigurationName.Create(jobName); var config = _blobStorage.GetBlob(configBlobName); return config; } /// <summary>Generates the blob sets that are required to run cloud-based map/reduce operations.</summary> /// <param name="jobName">The name of the job (should be unique).</param> /// <param name="items">The items that must be processed (at least two).</param> /// <param name="functions">The map/reduce/aggregate functions (aggregate is optional).</param> /// <param name="workerCount">The number of workers to use.</param> /// <param name="mapIn">The type of the map input.</param> /// <param name="mapOut">The type of the map output.</param> /// <remarks>This method should be called from <see cref="T:MapReduceJob"/>.</remarks> public void GenerateBlobSets(string jobName, IList<object> items, IMapReduceFunctions functions, int workerCount, Type mapIn, Type mapOut) { // Note: items is IList and not IEnumerable because the number of items must be known up-front // 1. Store config // 2. Put blobs and queue job messages // 3. Put messages in the work queue int itemCount = items.Count; // Note: each blobset should contain at least two elements int blobSetCount = Math.Min(workerCount, itemCount); float blobsPerSet = (float)itemCount / (float)blobSetCount; string ignored; // 1. Store configuration var configBlobName = MapReduceConfigurationName.Create(jobName); var config = new MapReduceConfiguration() { TMapInType = mapIn.AssemblyQualifiedName, TMapOutType = mapOut.AssemblyQualifiedName, MapReduceFunctionsImplementor = functions.GetType().AssemblyQualifiedName, BlobSetCount = blobSetCount }; _blobStorage.PutBlob(configBlobName.ContainerName, configBlobName.ToString(), config, typeof(MapReduceConfiguration), false, out ignored); // 2.1. Allocate blobsets var allNames = new InputBlobName[blobSetCount][]; int processedBlobs = 0; for(int currSet = 0; currSet < blobSetCount; currSet++) { // Last blobset might be smaller int thisSetSize = currSet != blobSetCount - 1 ? (int)Math.Ceiling(blobsPerSet) : itemCount - processedBlobs; allNames[currSet] = new InputBlobName[thisSetSize]; processedBlobs += thisSetSize; } if(processedBlobs != itemCount) { throw new InvalidOperationException("Processed Blobs are less than the number of items"); } // 2.2. Store input data (separate cycle for clarity) processedBlobs = 0; for(int currSet = 0; currSet < blobSetCount; currSet++) { for(int i = 0; i < allNames[currSet].Length; i++) { // BlobSet and Blob IDs start from zero allNames[currSet][i] = InputBlobName.Create(jobName, currSet, i); var item = items[processedBlobs]; _blobStorage.PutBlob(allNames[currSet][i].ContainerName, allNames[currSet][i].ToString(), item, mapIn, false, out ignored); processedBlobs++; } _queueStorage.Put(JobsQueueName, new JobMessage() { Type = MessageType.BlobSetToProcess, JobName = jobName, BlobSetId = currSet }); } } private static IMapReduceFunctions GetMapReduceFunctions(string typeName) { return Activator.CreateInstance(Type.GetType(typeName)) as IMapReduceFunctions; } /// <summary>Performs map/reduce operations on a blobset.</summary> /// <param name="jobName">The name of the job.</param> /// <param name="blobSetId">The blobset ID.</param> /// <remarks>This method should be called from <see cref="T:MapReduceService"/>.</remarks> public void PerformMapReduce(string jobName, int blobSetId) { // 1. Load config // 2. For all blobs in blobset, do map (output N) // 3. For all mapped items, do reduce (output 1) // 4. Store reduce result // 5. Update counter // 6. If aggregator != null && blobsets are all processed --> enqueue aggregation message // 7. Delete blobset // 1. Load config var config = GetJobConfig(jobName).Value; var blobsetPrefix = InputBlobName.GetPrefix(jobName, blobSetId); var mapResults = new List<object>(); var mapReduceFunctions = GetMapReduceFunctions(config.MapReduceFunctionsImplementor); var mapIn = Type.GetType(config.TMapInType); var mapOut = Type.GetType(config.TMapOutType); // 2. Do map for all blobs in the blobset string ignored; foreach (var blobName in _blobStorage.ListBlobNames(blobsetPrefix)) { var inputBlob = _blobStorage.GetBlob(blobName.ContainerName, blobName.ToString(), mapIn, out ignored); if (!inputBlob.HasValue) { continue; } object mapResult = InvokeAsDelegate(mapReduceFunctions.GetMapper(), inputBlob.Value); mapResults.Add(mapResult); } // 3. Do reduce for all mapped results while (mapResults.Count > 1) { object item1 = mapResults[0]; object item2 = mapResults[1]; mapResults.RemoveAt(0); mapResults.RemoveAt(0); object reduceResult = InvokeAsDelegate(mapReduceFunctions.GetReducer(), item1, item2); mapResults.Add(reduceResult); } // 4. Store reduced result var reducedBlobName = ReducedBlobName.Create(jobName, blobSetId); _blobStorage.PutBlob(reducedBlobName.ContainerName, reducedBlobName.ToString(), mapResults[0], mapOut, false, out ignored); // 5. Update counter var counterName = BlobCounterName.Create(jobName); var counter = new BlobCounter(_blobStorage, counterName); var totalCompletedBlobSets = (int) counter.Increment(1); // 6. Queue aggregation if appropriate if (totalCompletedBlobSets == config.BlobSetCount) { _queueStorage.Put(JobsQueueName, new JobMessage {JobName = jobName, BlobSetId = null, Type = MessageType.ReducedDataToAggregate}); } // 7. Delete blobset's blobs _blobStorage.DeleteAllBlobs(blobsetPrefix); } /// <summary>Performs the aggregate operation on a blobset.</summary> /// <param name="jobName">The name of the job.</param> public void PerformAggregate(string jobName) { // 1. Load config // 2. Do aggregation // 3. Store result // 4. Delete reduced data // 1. Load config var config = GetJobConfig(jobName).Value; var reducedBlobPrefix = ReducedBlobName.GetPrefix(jobName); var aggregateResults = new List<object>(); Type mapOut = Type.GetType(config.TMapOutType); // 2. Load reduced items and do aggregation string ignored; foreach (var blobName in _blobStorage.ListBlobNames(reducedBlobPrefix)) { var blob = _blobStorage.GetBlob(blobName.ContainerName, blobName.ToString(), mapOut, out ignored); if(!blob.HasValue) { continue; } aggregateResults.Add(blob.Value); } IMapReduceFunctions mapReduceFunctions = GetMapReduceFunctions(config.MapReduceFunctionsImplementor); while(aggregateResults.Count > 1) { object item1 = aggregateResults[0]; object item2 = aggregateResults[1]; aggregateResults.RemoveAt(0); aggregateResults.RemoveAt(0); object aggregResult = InvokeAsDelegate(mapReduceFunctions.GetReducer(), item1, item2); aggregateResults.Add(aggregResult); } // 3. Store aggregated result var aggregatedBlobName = AggregatedBlobName.Create(jobName); _blobStorage.PutBlob(aggregatedBlobName.ContainerName, aggregatedBlobName.ToString(), aggregateResults[0], mapOut, false, out ignored); // 4. Delete reduced data _blobStorage.DeleteAllBlobs(reducedBlobPrefix); } /// <summary>Gets the number of completed blobsets of a job.</summary> /// <param name="jobName">The name of the job.</param> /// <returns>The number of completed blobsets (<c>Tuple.Item1</c>) and the total number of blobsets (<c>Tuple.Item2</c>).</returns> /// <exception cref="ArgumentException">If <paramref name="jobName"/> refers to an inexistent job.</exception> public System.Tuple<int, int> GetCompletedBlobSets(string jobName) { var config = GetJobConfig(jobName); if (!config.HasValue) { throw new ArgumentException("Unknown job", "jobName"); } var counter = new BlobCounter(_blobStorage, BlobCounterName.Create(jobName)); int completedBlobsets = (int)counter.GetValue(); return new System.Tuple<int, int>(completedBlobsets, config.Value.BlobSetCount); } /// <summary>Retrieves the aggregated result of a map/reduce job.</summary> /// <typeparam name="T">The type of the result.</typeparam> /// <param name="jobName">The name of the job.</param> /// <returns>The aggregated result.</returns> /// <exception cref="InvalidOperationException">If the is not yet complete.</exception> /// <exception cref="ArgumentException">If <paramref name="jobName"/> refers to an inexistent job.</exception> public T GetAggregatedResult<T>(string jobName) { var config = GetJobConfig(jobName); if (!config.HasValue) { throw new ArgumentException("Unknown job", "jobName"); } var counter = new BlobCounter(_blobStorage, BlobCounterName.Create(jobName)); int completedBlobsets = (int)counter.GetValue(); if (completedBlobsets < config.Value.BlobSetCount) throw new InvalidOperationException("Job is not complete (there still are blobsets to process)"); Type mapOut = Type.GetType(config.Value.TMapOutType); var blobName = AggregatedBlobName.Create(jobName); string ignored; var aggregatedResult = _blobStorage.GetBlob(blobName.ContainerName, blobName.ToString(), mapOut, out ignored); if(!aggregatedResult.HasValue) { throw new InvalidOperationException("Job is not complete (reduced items must still be aggregated)"); } return (T) aggregatedResult.Value; } /// <summary>Deletes all the data related to a job, regardless of the job status.</summary> /// <param name="jobName">The name of the job.</param> /// <remarks>Messages enqueued cannot be deleted but they cause no harm.</remarks> public void DeleteJobData(string jobName) { _blobStorage.DeleteBlobIfExist(MapReduceConfigurationName.Create(jobName)); _blobStorage.DeleteAllBlobs(InputBlobName.GetPrefix(jobName)); _blobStorage.DeleteAllBlobs(ReducedBlobName.GetPrefix(jobName)); _blobStorage.DeleteBlobIfExist(AggregatedBlobName.Create(jobName)); _blobStorage.DeleteBlobIfExist(BlobCounterName.Create(jobName)); } /// <summary>Gets the existing jobs.</summary> /// <returns>The names of the existing jobs.</returns> public IList<string> GetExistingJobs() { var names = new List<string>(); foreach (var blobName in _blobStorage.ListBlobNames(MapReduceConfigurationName.GetPrefix())) { names.Add(blobName.JobName); } return names; } #region Delegate Utils /// <summary>Use reflection to invoke a delegate.</summary> static object InvokeAsDelegate(object target, params object[] inputs) { return target.GetType().InvokeMember( "Invoke", System.Reflection.BindingFlags.InvokeMethod, null, target, inputs); } #endregion #region Private Classes /// <summary>Contains configuration for a map/reduce job.</summary> [Serializable] public class MapReduceConfiguration { /// <summary>The type name of the TMapIn type.</summary> public string TMapInType { get; set; } /// <summary>The type name of the TMapOut type.</summary> public string TMapOutType { get; set; } /// <summary>The type name of the class that implements <see cref="IMapReduceFunctions"/>.</summary> public string MapReduceFunctionsImplementor { get; set; } /// <summary>The number of blobsets to be processed.</summary> public int BlobSetCount { get; set; } } public class MapReduceConfigurationName : BlobName<MapReduceConfiguration> { public override string ContainerName { get { return MapReduceBlobSet.ContainerName; } } [Rank(0)] public string Prefix; [Rank(1)] public string JobName; public MapReduceConfigurationName(string prefix, string jobName) { Prefix = prefix; JobName = jobName; } public static MapReduceConfigurationName Create(string jobName) { return new MapReduceConfigurationName(ConfigPrefix, jobName); } public static MapReduceConfigurationName GetPrefix() { return new MapReduceConfigurationName(ConfigPrefix, null); } } private class InputBlobName : BlobName<object> { public override string ContainerName { get { return MapReduceBlobSet.ContainerName; } } [Rank(0)] public string Prefix; [Rank(1)] public string JobName; [Rank(2)] public int? BlobSetId; [Rank(3)] public int? BlobId; public InputBlobName(string prefix, string jobName, int? blobSetId, int? blobId) { Prefix = prefix; JobName = jobName; BlobSetId = blobSetId; BlobId = blobId; } public static InputBlobName Create(string jobName, int blobSetId, int blobId) { return new InputBlobName(InputPrefix, jobName, blobSetId, blobId); } public static InputBlobName GetPrefix(string jobName, int blobSetId) { return new InputBlobName(InputPrefix, jobName, blobSetId, null); } public static InputBlobName GetPrefix(string jobName) { return new InputBlobName(InputPrefix, jobName, null, null); } } private class ReducedBlobName : BlobName<object> { public override string ContainerName { get { return MapReduceBlobSet.ContainerName; } } [Rank(0)] public string Prefix; [Rank(1)] public string JobName; [Rank(2, true)] public int BlobSetId; public ReducedBlobName(string prefix, string jobName, int blobSetIt) { Prefix = prefix; JobName = jobName; BlobSetId = blobSetIt; } public static ReducedBlobName Create(string jobName, int blobSetId) { return new ReducedBlobName(ReducedPrefix, jobName, blobSetId); } public static ReducedBlobName GetPrefix(string jobName) { return new ReducedBlobName(ReducedPrefix, jobName, 0); } } private class AggregatedBlobName : BlobName<object> { public override string ContainerName { get { return MapReduceBlobSet.ContainerName; } } [Rank(0)] public string Prefix; [Rank(1)] public string JobName; public AggregatedBlobName(string prefix, string jobName) { Prefix = prefix; JobName = jobName; } public static AggregatedBlobName Create(string jobName) { return new AggregatedBlobName(AggregatedPrefix, jobName); } } private class BlobCounterName : BlobName<decimal> { public override string ContainerName { get { return MapReduceBlobSet.ContainerName; } } [Rank(0)] public string Prefix; [Rank(1)] public string JobName; public BlobCounterName(string prefix, string jobName) { Prefix = prefix; JobName = jobName; } public static BlobCounterName Create(string jobName) { return new BlobCounterName(CounterPrefix, jobName); } } #endregion } }
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceService/MapReduceBlobSet.cs
C#
bsd
17,772
 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lokad.Cloud.Samples.MapReduce { /// <summary> /// Defines the interface for a class that implements map/reduce functions. /// </summary> /// <remarks>Classes implementing this interface must have a parameterless constructor, /// and must be deployed both on server and client.</remarks> public interface IMapReduceFunctions { /// <summary>Gets the mapper function, expected to be Func{TMapIn, TMapOut}.</summary> /// <returns>The mapper function.</returns> object GetMapper(); /// <summary>Gets the reducer function, expected to be Func{TMapOut, TMapOut, TMapOut}.</summary> /// <returns>The reducer function.</returns> object GetReducer(); } }
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceService/IMapReduceFunctions.cs
C#
bsd
791
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using Lokad.Cloud.ServiceFabric; namespace Lokad.Cloud.Samples.MapReduce { /// <summary>Implements a map/reduce service.</summary> /// <seealso cref="MapReduceBlobSet"/> /// <seealso cref="MapReduceJob"/> [QueueServiceSettings( AutoStart = true, Description = "Processes map/reduce jobs", QueueName = MapReduceBlobSet.JobsQueueName)] public class MapReduceService : QueueService<JobMessage> { protected override void Start(JobMessage message) { switch(message.Type) { case MessageType.BlobSetToProcess: ProcessBlobSet(message.JobName, message.BlobSetId.Value); break; case MessageType.ReducedDataToAggregate: AggregateData(message.JobName); break; default: throw new InvalidOperationException("Invalid Message Type"); } } void ProcessBlobSet(string jobName, int blobSetId) { var blobSet = new MapReduceBlobSet(BlobStorage, QueueStorage); blobSet.PerformMapReduce(jobName, blobSetId); } void AggregateData(string jobName) { var blobSet = new MapReduceBlobSet(BlobStorage, QueueStorage); blobSet.PerformAggregate(jobName); } } }
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceService/MapReduceService.cs
C#
bsd
1,327
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Samples.MapReduce { /// <summary>Entry point for setting up and consuming a map/reduce service.</summary> /// <typeparam name="TMapIn">The type of the items that are input in the map operation.</typeparam> /// <typeparam name="TMapOut">The type of the items that are output from the map operation.</typeparam> /// <remarks>All public members are thread-safe.</remarks> /// <seealso cref="MapReduceBlobSet"/> /// <seealso cref="MapReduceService"/> public sealed class MapReduceJob<TMapIn, TMapOut> { // HACK: thread-safety is achieved via locks. It would be better to make this class immutable. string _jobName; IBlobStorageProvider _blobStorage; IQueueStorageProvider _queueStorage; bool _itemsPushed = false; /// <summary>Initializes a new instance of the /// <see cref="T:MapReduceJob{TMapIn,TMapOut,TReduceOut}"/> generic class.</summary> /// <param name="blobStorage">The blob storage provider.</param> /// <param name="queueStorage">The queue storage provider.</param> public MapReduceJob(IBlobStorageProvider blobStorage, IQueueStorageProvider queueStorage) { if(null == blobStorage) throw new ArgumentNullException("blobStorage"); if(null == queueStorage) throw new ArgumentNullException("queueStorage"); _jobName = Guid.NewGuid().ToString("N"); _blobStorage = blobStorage; _queueStorage = queueStorage; } /// <summary>Initializes a new instance of the /// <see cref="T:MapReduceJob{TMapIn,TMapOut,TReduceOut}"/> generic class.</summary> /// <param name="jobId">The ID of the job as previously returned by <see cref="M:PushItems"/>.</param> /// <param name="blobStorage">The blob storage provider.</param> /// <param name="queueStorage">The queue storage provider.</param> public MapReduceJob(string jobId, IBlobStorageProvider blobStorage, IQueueStorageProvider queueStorage) { if(null == jobId) throw new ArgumentNullException("jobId"); if(null == blobStorage) throw new ArgumentNullException("blobStorage"); if(null == queueStorage) throw new ArgumentNullException("queueStorage"); _jobName = jobId; _itemsPushed = true; _blobStorage = blobStorage; _queueStorage = queueStorage; } /// <summary>Pushes a batch of items for processing.</summary> /// <param name="functions">The functions for map/reduce/aggregate operations.</param> /// <param name="items">The items to process (at least two).</param> /// <param name="workerCount">The max number of workers to use.</param> /// <returns>The batch ID.</returns> /// <exception cref="InvalidOperationException">If the method was already called.</exception> /// <exception cref="ArgumentException">If <paramref name="items"/> contains less than two items.</exception> public string PushItems(IMapReduceFunctions functions, IList<TMapIn> items, int workerCount) { lock(_jobName) { if(_itemsPushed) throw new InvalidOperationException("A batch was already pushed to the work queue"); var blobSet = new MapReduceBlobSet(_blobStorage, _queueStorage); blobSet.GenerateBlobSets(_jobName, new List<object>(from i in items select (object)i), functions, workerCount, typeof(TMapIn), typeof(TMapOut)); _itemsPushed = true; return _jobName; } } /// <summary>Indicates whether the job is completed.</summary> /// <returns><c>true</c> if the batch is completed, <c>false</c> otherwise.</returns> public bool IsCompleted() { lock(_jobName) { var blobSet = new MapReduceBlobSet(_blobStorage, _queueStorage); var status = blobSet.GetCompletedBlobSets(_jobName); if(status.Item1 < status.Item2) return false; try { blobSet.GetAggregatedResult<object>(_jobName); return true; } catch(InvalidOperationException) { return false; } } } /// <summary>Gets the result of a job.</summary> /// <returns>The result item.</returns> /// <exception cref="InvalidOperationException">If the result is not ready (<seealso cref="M:IsCompleted"/>).</exception> public TMapOut GetResult() { lock(_jobName) { var blobSet = new MapReduceBlobSet(_blobStorage, _queueStorage); return blobSet.GetAggregatedResult<TMapOut>(_jobName); } } /// <summary>Deletes all the data related to the job.</summary> /// <remarks>After calling this method, the instance of <see cref="T:MapReduceJob"/> /// should not be used anymore.</remarks> public void DeleteJobData() { lock(_jobName) { var blobSet = new MapReduceBlobSet(_blobStorage, _queueStorage); blobSet.DeleteJobData(_jobName); } } } }
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceService/MapReduceJob.cs
C#
bsd
5,000
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lokad.Cloud.Samples.MapReduce { /// <summary>Contains information about a batch item to process.</summary> [Serializable] public sealed class JobMessage { /// <summary>The type of the message.</summary> public MessageType Type { get; set; } /// <summary>The name of the job.</summary> public string JobName { get; set; } /// <summary>The ID of the blobset to process, if appropriate.</summary> public int? BlobSetId { get; set; } } /// <summary>Defines message types for <see cref="T:BatchMessage"/>s.</summary> public enum MessageType { /// <summary>A blob set must be processed (map/reduce).</summary> BlobSetToProcess, /// <summary>The result of a map/reduce job is ready for aggregation.</summary> ReducedDataToAggregate } }
zyyin2005-lokad
Samples/Source/MapReduce/MapReduceService/JobMessage.cs
C#
bsd
1,044
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SimpleTable")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lokad SAS")] [assembly: AssemblyProduct("SimpleTable")] [assembly: AssemblyCopyright("Copyright © Lokad 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e4f5a45c-f284-459a-8c78-5b45d0c6bfaa")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zyyin2005-lokad
Samples/Source/SimpleTable/Properties/AssemblyInfo.cs
C#
bsd
1,448
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; using Lokad.Cloud.Storage; namespace SimpleTable { [DataContract] class Book { [DataMember] public string Title { get; set; } [DataMember] public string Author { get; set; } } class Program { static void Main(string[] args) { // insert your own connection string here, or use one of the other options: var tableStorage = CloudStorage .ForAzureConnectionString("DefaultEndpointsProtocol=https;AccountName=YOURACCOUNT;AccountKey=YOURKEY") .BuildTableStorage(); // 'books' is the name of the table var books = new CloudTable<Book>(tableStorage, "books"); var potterBook = new Book { Author = "J. K. Rowling", Title = "Harry Potter" }; var poemsBook = new Book { Author = "John Keats", Title = "Complete Poems" }; // inserting (or updating record in Table Storage) books.Upsert(new[] { new CloudEntity<Book> {PartitionKey = "UK", RowKey = "potter", Value = potterBook}, new CloudEntity<Book> {PartitionKey = "UK", RowKey = "poems", Value = poemsBook} }); // reading from table foreach(var entity in books.Get()) { Console.WriteLine("{0} by {1} in partition '{2}' and rowkey '{3}'", entity.Value.Title, entity.Value.Author, entity.PartitionKey, entity.RowKey); } Console.WriteLine("Press enter to exit."); Console.ReadLine(); } } }
zyyin2005-lokad
Samples/Source/SimpleTable/Program.cs
C#
bsd
1,875
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using Lokad.Cloud.ServiceFabric; namespace IoCforService { /// <summary>Sample service is IoC populated property.</summary> public class MyService : ScheduledService { /// <summary>IoC populated property. </summary> public MyProvider Provider { get; set; } protected override void StartOnSchedule() { if(null == Providers) { throw new InvalidOperationException("Provider should have been populated."); } } } }
zyyin2005-lokad
Samples/Source/IoCforService/MyService.cs
C#
bsd
621
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Autofac; using Autofac.Builder; namespace IoCforService { public class MyModule : Module { protected override void Load(ContainerBuilder builder) { builder.Register(c => new MyProvider(c.Resolve<Lokad.Cloud.Storage.Shared.Logging.ILog>())); } } }
zyyin2005-lokad
Samples/Source/IoCforService/MyModule.cs
C#
bsd
441
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad; namespace IoCforService { /// <summary>Sample provider, registered though Autofac module.</summary> public class MyProvider { public MyProvider(Lokad.Cloud.Storage.Shared.Logging.ILog logger) { logger.Log(Lokad.Cloud.Storage.Shared.Logging.LogLevel.Info, "Client IoC module loaded."); } } }
zyyin2005-lokad
Samples/Source/IoCforService/MyProvider.cs
C#
bsd
497
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("IoCforService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IoCforService")] [assembly: AssemblyCopyright("Copyright © 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("36a257ac-60c9-4d6d-b011-7c4feb130b45")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zyyin2005-lokad
Samples/Source/IoCforService/Properties/AssemblyInfo.cs
C#
bsd
1,438
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; /** * hessdroid test suite. * * @author hessdroid@gmail.com */ @SuiteClasses({ PrimitiveTypeTests.class, ReferenceTypeTests.class, NullDateTests.class, CollectionTypeTests.class, CookieParserTests.class }) @RunWith(Suite.class) public class TestSuite { }
zzgfly-hessdroid
tests/org/ast/tests/TestSuite.java
Java
asf20
1,016
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests.base; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import com.caucho.hessian.client.HessianProxyFactory; import com.caucho.hessian.io.HessianRemoteObject; /** * Factory for {@link HessianTestProxy} that extends {@link HessianProxyFactory} in order to * reuse most of it's functionality.<p/> * * Especially {@link #create(Class, ClassLoader, HessianSkeleton)} is supposed to be used in * test-cases in order to specify a {@link HessianSkeleton}, acting as (fictional) server-side * instance. * * @see HessianTestProxy * @see HessianProxyFactory * * @author hessdroid@gmail.com * */ public class HessianTestProxyFactory extends HessianProxyFactory { /** * Creates a new proxy for the specified service. This is the main method intented * for testing the serialization/deserialization of this library. * * @return a proxy to the object with the specified interface. */ public <T> T create(Class<T> api, ClassLoader loader, HessianSkeleton server) { if (api == null) throw new NullPointerException("api must not be null for HessianTestProxyFactory.create()"); InvocationHandler handler = new HessianTestProxy(this, server); return (T) Proxy.newProxyInstance(loader, new Class[] { api, HessianRemoteObject.class }, handler); } }
zzgfly-hessdroid
tests/org/ast/tests/base/HessianTestProxyFactory.java
Java
asf20
1,937
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests.base; import java.io.Serializable; import org.junit.Before; /** * Base class for all hessdroid tests. The formal generic parameter <tt>T</tt> is used to specify the type * of the web service's interface. The interface must not implement or extends another interface except * {@link Serializable} if reference types are used in method signatures. * * @author hessdroid@gmail.com * * @param <T> the web service's interface */ public abstract class HessianTest<T> { // Server-Side private T _serviceImpl; private Class<T> _serviceImplClass; private HessianSkeleton service; // Client-Side private T testApiClient; @SuppressWarnings("unchecked") public HessianTest(T testApiInstance) throws Exception { _serviceImpl = testApiInstance; _serviceImplClass = (Class<T>) testApiInstance.getClass().getInterfaces()[0]; } @Before public void setUp() throws Exception { HessianTestProxyFactory factory = new HessianTestProxyFactory(); service = new HessianSkeleton(_serviceImpl, _serviceImplClass); testApiClient = factory.create(_serviceImplClass, Thread.currentThread().getContextClassLoader(), service); } public T client() { return testApiClient; }; }
zzgfly-hessdroid
tests/org/ast/tests/base/HessianTest.java
Java
asf20
1,832
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package org.ast.tests.base; import com.caucho.hessian.io.AbstractHessianInput; import com.caucho.hessian.io.AbstractHessianOutput; import com.caucho.services.server.AbstractSkeleton; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; /** * Proxy class for Hessian services. */ public class HessianSkeleton extends AbstractSkeleton { private static final Logger log = Logger.getLogger(HessianSkeleton.class.getName()); private Object _service; /** * Create a new hessian skeleton. * * @param service the underlying service object. * @param apiClass the API interface */ public HessianSkeleton(Object service, Class apiClass) { super(apiClass); if (service == null) service = this; _service = service; if (! apiClass.isAssignableFrom(service.getClass())) throw new IllegalArgumentException("Service " + service + " must be an instance of " + apiClass.getName()); } /** * Create a new hessian skeleton. * * @param service the underlying service object. * @param apiClass the API interface */ public HessianSkeleton(Class apiClass) { super(apiClass); } /** * Invoke the object with the request from the input stream. * * @param in the Hessian input stream * @param out the Hessian output stream */ public void invoke(AbstractHessianInput in, AbstractHessianOutput out) throws Exception { invoke(_service, in, out); } /** * Invoke the object with the request from the input stream. * * @param in the Hessian input stream * @param out the Hessian output stream */ public void invoke(Object service, AbstractHessianInput in, AbstractHessianOutput out) throws Exception { // backward compatibility for some frameworks that don't read // the call type first in.skipOptionalCall(); String methodName = in.readMethod(); Method method = getMethod(methodName); if (method != null) { } else if ("_hessian_getAttribute".equals(methodName)) { String attrName = in.readString(); in.completeCall(); String value = null; if ("java.api.class".equals(attrName)) value = getAPIClassName(); else if ("java.home.class".equals(attrName)) value = getHomeClassName(); else if ("java.object.class".equals(attrName)) value = getObjectClassName(); out.startReply(); out.writeObject(value); out.completeReply(); out.close(); return; } else if (method == null) { out.startReply(); out.writeFault("NoSuchMethodException", "The service has no method named: " + in.getMethod(), null); out.completeReply(); out.close(); return; } Class []args = method.getParameterTypes(); Object []values = new Object[args.length]; for (int i = 0; i < args.length; i++) { values[i] = in.readObject(args[i]); } Object result = null; try { result = method.invoke(service, values); } catch (Throwable e) { if (e instanceof InvocationTargetException) e = ((InvocationTargetException) e).getTargetException(); log.log(Level.FINE, this + " " + e.toString(), e); out.startReply(); out.writeFault("ServiceException", e.getMessage(), e); out.completeReply(); out.close(); return; } // The complete call needs to be after the invoke to handle a // trailing InputStream in.completeCall(); out.startReply(); out.writeObject(result); out.completeReply(); out.close(); } }
zzgfly-hessdroid
tests/org/ast/tests/base/HessianSkeleton.java
Java
asf20
5,937
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests.base; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.WeakHashMap; import java.util.logging.Level; import java.util.logging.Logger; import com.caucho.hessian.client.HessianProxy; import com.caucho.hessian.io.AbstractHessianInput; import com.caucho.hessian.io.AbstractHessianOutput; import com.caucho.hessian.io.HessianDebugInputStream; import com.caucho.hessian.io.HessianInput; import com.caucho.hessian.io.HessianOutput; import com.caucho.hessian.io.HessianProtocolException; import com.caucho.services.server.AbstractSkeleton; /** * Proxy implementation for Hessian test clients. It implements {@link InvocationHandler} in order * to act as proxy class for arbitrary interfaces. In contrast to {@link HessianProxy} this proxy's * constructor takes a {@link HessianSkeleton} that is used as fictional server-side service instance.<p/> * * {@link #sendRequest(String, Object[])} forwards method invocations directly to the given {@link HessianSkeleton} without * using a transport protocol, indeed {@link ByteArrayInputStream} and {@link ByteArrayOutputStream} are used to push/pull hessian * byte array data. * * @see InvocationHandler * @see HessianProxy * @see HessianSkeleton * * @author hessdroid@gmail.com */ public class HessianTestProxy implements InvocationHandler { private static final Logger log = Logger.getLogger(HessianTestProxy.class.getName()); protected HessianTestProxyFactory _factory; private WeakHashMap<Method, String> _mangleMap = new WeakHashMap<Method, String>(); private HessianSkeleton _skeletonServer; /** * Package protected constructor for factory */ HessianTestProxy(HessianTestProxyFactory factory, HessianSkeleton skeletonServer) { _factory = factory; _skeletonServer = skeletonServer; } /** * Handles the object invocation. * * @param proxy * the proxy object to invoke * @param method * the method to call * @param args * the arguments to the proxy object */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String mangleName; synchronized (_mangleMap) { mangleName = _mangleMap.get(method); } if (mangleName == null) { String methodName = method.getName(); Class[] params = method.getParameterTypes(); // equals and hashCode are special cased if (methodName.equals("equals") && params.length == 1 && params[0].equals(Object.class)) { Object value = args[0]; if (value == null || !Proxy.isProxyClass(value.getClass())) return Boolean.FALSE; HessianTestProxy handler = (HessianTestProxy) Proxy.getInvocationHandler(value); return Boolean.valueOf(equals(handler)); } else if (methodName.equals("hashCode") && params.length == 0) return Integer.valueOf(hashCode()); else if (methodName.equals("getHessianType")) return proxy.getClass().getInterfaces()[0].getName(); else if (methodName.equals("getHessianURL")) return toString(); else if (methodName.equals("toString") && params.length == 0) return "HessianTestProxy[" + hashCode() + "]"; if (!_factory.isOverloadEnabled()) mangleName = method.getName(); else mangleName = mangleName(method); synchronized (_mangleMap) { _mangleMap.put(method, mangleName); } } InputStream is = null; try { if (log.isLoggable(Level.FINER)) log.finer("Hessian[" + toString() + "] calling " + mangleName); is = sendRequest(mangleName, args); if (log.isLoggable(Level.FINEST)) { PrintWriter dbg = new PrintWriter(new LogWriter(log)); is = new HessianDebugInputStream(is, dbg); } AbstractHessianInput in = _factory.getHessianInput(is); in.startReply(); Object value = in.readObject(method.getReturnType()); in.completeReply(); return value; } catch (HessianProtocolException e) { throw new RuntimeException(e); } finally { try { if (is != null) is.close(); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } } protected String mangleName(Method method) { Class[] param = method.getParameterTypes(); if (param == null || param.length == 0) return method.getName(); else return AbstractSkeleton.mangleName(method, false); } protected InputStream sendRequest(String methodName, Object[] args) throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); // if (log.isLoggable(Level.FINEST)) { // PrintWriter dbg = new PrintWriter(new LogWriter(log)); // os = new HessianDebugOutputStream(os, dbg); // } AbstractHessianOutput out = _factory.getHessianOutput(os); out.call(methodName, args); out.flush(); // Invoke the _skeletonServer - to see if serialization/deserialization works ByteArrayOutputStream result = new ByteArrayOutputStream(); _skeletonServer.invoke(new HessianInput(new ByteArrayInputStream(os.toByteArray())), new HessianOutput(result)); return new ByteArrayInputStream(result.toByteArray()); } static class LogWriter extends Writer { private Logger _log; private Level _level = Level.FINEST; private StringBuilder _sb = new StringBuilder(); LogWriter(Logger log) { _log = log; } public void write(char ch) { if (ch == '\n' && _sb.length() > 0) { _log.fine(_sb.toString()); _sb.setLength(0); } else _sb.append((char) ch); } public void write(char[] buffer, int offset, int length) { for (int i = 0; i < length; i++) { char ch = buffer[offset + i]; if (ch == '\n' && _sb.length() > 0) { _log.log(_level, _sb.toString()); _sb.setLength(0); } else _sb.append((char) ch); } } public void flush() { } public void close() { if (_sb.length() > 0) _log.log(_level, _sb.toString()); } } }
zzgfly-hessdroid
tests/org/ast/tests/base/HessianTestProxy.java
Java
asf20
6,624
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Date; import org.ast.tests.api.TestReferenceTypes; import org.ast.tests.api.TestType; import org.ast.tests.base.HessianTest; import org.junit.Test; /** * {@link HessianTest} that is intented to regression test a bug in hessdroid: * * http://code.google.com/p/hessdroid/issues/detail?id=1 * * @author hessdroid@gmail.com */ public class NullDateTests extends HessianTest<TestReferenceTypes> { private static final Date testDate = new Date(); public NullDateTests() throws Exception { super(new TestReferenceTypes() { public TestType getTestType() { return new TestType() { public String getName() { return "name"; } }; } public Date getDate() { return null; } }); } @Test public void callObject() throws Exception { assertNotNull(client().getTestType()); assertEquals("name", client().getTestType().getName()); assertEquals(null, client().getDate()); } }
zzgfly-hessdroid
tests/org/ast/tests/NullDateTests.java
Java
asf20
1,670
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests; import org.ast.tests.api.TestCollectionTypes; import org.ast.tests.base.HessianTest; import org.junit.Test; import java.util.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * {@link HessianTest} that is intended to test method calls with collection data types. * * @author <a href="mailto:wolf@wolfpaulus.com">Wolf Paulus</a> */ public class CollectionTypeTests extends HessianTest<TestCollectionTypes> { @SuppressWarnings("serial") public CollectionTypeTests() throws Exception { super(new TestCollectionTypes() { public List<Number> getList() { List<Number> list = new ArrayList<Number>(); list.add(1); list.add(2f); list.add(3d); return list; } public Map<Integer, Date> getMap() { Map<Integer, Date> map = new HashMap<Integer, Date>(); map.put(1, new Date(1l)); map.put(2, new Date(2l)); map.put(3, new Date(3l)); return map; } public Set<String> getSet() { Set<String> set = new HashSet<String>(); set.add("1"); set.add("2"); set.add("3"); return set; } public Collection<Iterable<?>> getCollection() { Collection<Iterable<?>> c = new ArrayList<Iterable<?>>(); c.add(getList()); c.add(getSet()); return c; } }); } @Test public void callSet() throws Exception { Set<String> set = client().getSet(); int k = 0; for (String s : set) { if ("1".equals(s)) k++; if ("2".equals(s)) k++; if ("3".equals(s)) k++; } assertEquals(3, k); } @Test public void callList() throws Exception { Iterator<Number> it = client().getList().iterator(); Number n = it.next(); assertTrue(Integer.class.equals(n.getClass())); assertTrue(new Integer(1).equals(1)); n = it.next(); assertTrue(Double.class.equals(n.getClass())); assertTrue(new Float(2).equals(2f)); n = it.next(); assertTrue(Double.class.equals(n.getClass())); assertTrue(new Double(3).equals(3d)); assertTrue(!it.hasNext()); } @Test public void callMap() throws Exception { Map<Integer, Date> map = client().getMap(); assertEquals(3, map.size()); assertEquals(new Date(1l), map.get(1)); assertEquals(new Date(2l), map.get(2)); assertEquals(new Date(3l), map.get(3)); } @Test public void callCollection() throws Exception { Collection<Iterable<?>> c = client().getCollection(); Iterator<?> it = c.iterator(); Object obj = it.next(); assertTrue(ArrayList.class.equals(obj.getClass())); obj = it.next(); assertTrue(HashSet.class.equals(obj.getClass())); assertTrue(!it.hasNext()); } }
zzgfly-hessdroid
tests/org/ast/tests/CollectionTypeTests.java
Java
asf20
3,758
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests; import com.ast.util.CookieParser; import com.ast.util.CookieParser.Cookie; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; public class CookieParserTests { @Test public void testWithCookieValueAndPath() throws Exception { Cookie c = CookieParser.parse("myhost", "Set-Cookie: cookie-value; path=path"); assertEquals(c.host, "myhost"); assertEquals(c.path, "path"); } @Test public void testWithCompleteCookiePath() throws Exception { // Set-Cookie: cookie-value; expires=date; path=path; domain=domain-name; secure Cookie c = CookieParser.parse("myhost", "Set-Cookie: cookie-value; expires=date; path=path; domain=domain-name; secure"); assertEquals(c.host, "myhost"); assertEquals(c.path, "path"); assertEquals(c.value, "cookie-value"); assertEquals(c.expires, "date"); assertEquals(c.domain, "domain-name"); assertEquals(c.secure, true); } @Test public void testWithRealWorldCookie() throws Exception { // simple real-world cookie: Cookie c = CookieParser.parse("myhost", "Set-Cookie: JSESSIONID=9126DE0DA91BD7D3C1A1A0608EC66645; Path=/Server"); assertEquals(c.path, "/Server"); assertEquals(c.value, "JSESSIONID=9126DE0DA91BD7D3C1A1A0608EC66645"); assertEquals(c.sessionId, "9126DE0DA91BD7D3C1A1A0608EC66645"); // simple real-world cookie: c = CookieParser.parse("myhost", "Set-Cookie: JSESSIONID=A5BCBA5F3B50EC39E3CA4CE3EE86210C; Path=/"); assertEquals(c.path, "/"); assertEquals(c.value, "JSESSIONID=A5BCBA5F3B50EC39E3CA4CE3EE86210C"); assertEquals(c.sessionId, "A5BCBA5F3B50EC39E3CA4CE3EE86210C"); } @Test public void testEdgeCases() throws Exception { Cookie c; try { c = CookieParser.parse("myhost", null); assertEquals(c.host, "myhost"); // never executed } catch (Exception e) { assertTrue("Expect Exception to be thrown in CookieParser.parse()", true); } try { c = CookieParser.parse(null, "Set-Cookie: cookie-value; path=path"); assertEquals(c.path, "path"); // never executed } catch (Exception e) { assertTrue("Expect Exception to be thrown in CookieParser.parse()", true); } try { c = CookieParser.parse("myhost", ""); assertEquals(c.host, "myhost"); assertEquals(c.value,""); c = CookieParser.parse("", "Set-Cookie: cookie-value; path=path"); assertEquals(c.host, ""); assertEquals(c.value,"cookie-value"); c = CookieParser.parse("myhost", "0123456789"); assertEquals(c.value, "0123456789"); } catch (Exception e) { assertTrue("Exception thrown in CookieParser.parse()", false); } } }
zzgfly-hessdroid
tests/org/ast/tests/CookieParserTests.java
Java
asf20
3,610
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Date; import org.ast.tests.api.TestReferenceTypes; import org.ast.tests.api.TestType; import org.ast.tests.base.HessianTest; import org.junit.Test; /** * {@link HessianTest} that is intented to test method calls with reference data types. * * @author hessdroid@gmail.com */ public class ReferenceTypeTests extends HessianTest<TestReferenceTypes> { private static final Date testDate = new Date(); @SuppressWarnings("serial") public ReferenceTypeTests() throws Exception { super(new TestReferenceTypes() { public TestType getTestType() { return new TestType() { public String getName() { return "name"; } }; } public Date getDate() { return testDate; } }); } @Test public void callObject() throws Exception { assertNotNull(client().getTestType()); assertEquals("name", client().getTestType().getName()); assertEquals(testDate, client().getDate()); } }
zzgfly-hessdroid
tests/org/ast/tests/ReferenceTypeTests.java
Java
asf20
1,664
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests.api; import java.io.Serializable; /** * Simple type to test reference types. * * @author hessdroid@gmail.com */ public interface TestType extends Serializable { public String getName(); }
zzgfly-hessdroid
tests/org/ast/tests/api/TestType.java
Java
asf20
827
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests.api; import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; /** * Simple interface for testing collection data types. * * @author <a href="mailto:wolf@wolfpaulus.com">Wolf Paulus</a> */ public interface TestCollectionTypes extends Serializable { public Set<String> getSet(); public List<Number> getList(); public Map<Integer,Date> getMap(); public Collection<Iterable<?>> getCollection(); }
zzgfly-hessdroid
tests/org/ast/tests/api/TestCollectionTypes.java
Java
asf20
1,124
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests.api; import java.io.Serializable; /** * Simple interface for testing primitive data types. * * @author hessdroid@gmail.com */ public interface TestPrimitiveTypes extends Serializable { public int getInt(); public Integer getInteger(); public String getString(); public boolean getBoolean(); }
zzgfly-hessdroid
tests/org/ast/tests/api/TestPrimitiveTypes.java
Java
asf20
934
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests.api; import java.io.Serializable; import java.util.Date; /** * Simple interface for testing reference data types. * * @author hessdroid@gmail.com */ public interface TestReferenceTypes extends Serializable { public TestType getTestType(); public Date getDate(); }
zzgfly-hessdroid
tests/org/ast/tests/api/TestReferenceTypes.java
Java
asf20
902
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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 org.ast.tests; import static org.junit.Assert.assertEquals; import org.ast.tests.api.TestPrimitiveTypes; import org.ast.tests.base.HessianTest; import org.junit.Test; /** * {@link HessianTest} that is intended to test method calls with primitive data types. * * @author hessdroid@gmail.com */ public class PrimitiveTypeTests extends HessianTest<TestPrimitiveTypes> { @SuppressWarnings("serial") public PrimitiveTypeTests() throws Exception { super(new TestPrimitiveTypes() { public boolean getBoolean() { return true; } public int getInt() { return 0; } public Integer getInteger() { return 0; } public String getString() { return "string"; } }); } @Test public void callInt() throws Exception { assertEquals(0, client().getInt()); } @Test public void callString() throws Exception { assertEquals("string", client().getString()); } @Test public void callBoolean() throws Exception { assertEquals(true, client().getBoolean()); } }
zzgfly-hessdroid
tests/org/ast/tests/PrimitiveTypeTests.java
Java
asf20
1,629
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2004 Caucho Technology, Inc. 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.client; /** * API retrieving hessian meta information. */ public interface HessianMetaInfoAPI { /** * Returns a service attribute. * * <ul> * <li>java.api.class - the Java interface for the object interface. * <li>java.ejb.home.class - the EJB home interface * <li>java.ejb.remote.class - the EJB remote interface * <li>java.primary.key.class - the EJB primary key class * </ul> */ public Object _hessian_getAttribute(String name); }
zzgfly-hessdroid
src/com/caucho/hessian/client/HessianMetaInfoAPI.java
Java
asf20
2,730
/* * Copyright (C) 2009 hessdroid@gmail.com * * 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.caucho.hessian.client; import com.ast.util.CookieParser; import com.ast.util.CookieParser.Cookie; import com.caucho.hessian.io.HessianRemoteObject; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; /** * <code>HessianHttpProxyFactory</code> extends the * <code>HessianProxyFactory</code>'s capabilities, by adding support for HTTP * Cookies. A cookie map is used to map Server/Paths to cookies * * @author <a href="mailto:wolf@wolfpaulus.com">Wolf Paulus</a> * @version 1.0 Date: Nov 17, 2009 */ public class HessianHttpProxyFactory extends HessianProxyFactory { /* * public Object create2(Class api, String urlName, ClassLoader loader) * throws MalformedURLException { InvocationHandler handler = new * HessianHttpProxy(this, new URL(urlName)); return * Proxy.newProxyInstance(api.getClassLoader(), new Class[]{api, * HessianRemoteObject.class}, handler); } */ /** * Creates a new proxy with the specified URL. The returned object is a * proxy with the interface specified by api. * <p/> * <p/> * <pre> * String url = "http://localhost:8080/ejb/hello"); * HelloHome hello = (HelloHome) factory.create(HelloHome.class, url); * </pre> * * @param api the interface the proxy class needs to implement * @param urlName the URL where the client object is located. * @param loader <code>ClassLoader</code> to be used loading the proxy * instance's class * @return a proxy to the object with the specified interface. * @throws java.net.MalformedURLException if URL object cannot be created with the provided urlName */ @SuppressWarnings({"unchecked"}) @Override public <T> T create(Class<T> api, String urlName, ClassLoader loader) throws MalformedURLException { // // todo: since the api is already loaded, maybe the api class' classloader should be tried, // in case the provided classloader fails. InvocationHandler handler = new HessianHttpProxy(this, new URL(urlName)); return (T) Proxy.newProxyInstance(loader, new Class[]{api, HessianRemoteObject.class}, handler); } /** * Clear the Cookie Cache, should be run on every logout. */ public static void clearCookieCache() { HessianHttpProxy.cookieMap.clear(); } /** * The <code>HessianHttpProxy</code> intercepts request and response, so that * cookies can be read in the incoming response and written before an * outgoing request is sent. Cookie strings are stored in a * <code>Hashtable</code>; and the URL's host+path is used for the key. * <p/> * When the cookie string is retrieved, the path is shortened, all the way * to / until a match is found. * <p/> * Available Header Fields are: * <p/> * Header Field: date (Wed, 18 Nov 2009 21:01:44 GMT) * Header Field: content-type (application/x-hessian) * Header Field: transfer-encoding (chunked) * Header Field: server (Apache-Coyote/1.1) * Header Field: set-cookie (JSESSIONID=5930D0459F0CE1B769ED5D08B031F9D2; Path=/Server) */ private static class HessianHttpProxy extends HessianProxy { private static final Logger log = Logger.getLogger(HessianHttpProxy.class.getName()); private static final HashMap<String, Cookie> cookieMap = new HashMap<String, Cookie>(); private static final String COOKIE_SET = "set-cookie"; HessianHttpProxy(HessianProxyFactory factory, URL url) { super(url, factory); } /** * Read cookies found in a server's response, so we can send them back * with the next request. The response-header field names are the key * values of the map. * * @param conn <code>URLConnection</code> */ protected void parseResponseHeaders(URLConnection conn) { List<String> cookieStrings = conn.getHeaderFields().get(HessianHttpProxy.COOKIE_SET); if (cookieStrings != null) { String host = conn.getURL().getHost(); for (String s : cookieStrings) { Cookie cookie = CookieParser.parse(host, s); HessianHttpProxy.cookieMap.put(cookie.host + cookie.path, cookie); log.finest("Cookie cached: " + cookie.host + cookie.path + ":" + s); } } } /** * Add the cookies we received in a previous response, into the current * request. The getUrl().getPath() might return something like this: * /Server/comm Here we look for a close match in the cookiemap, * starting with the most specific. * * @param conn <code>URLConnection</code> */ protected void addRequestHeaders(URLConnection conn) { String host = conn.getURL().getHost(); String path = conn.getURL().getPath(); while (path != null && 0 < path.length()) { log.info("Host:+" + host +",Path:"+path); Cookie cookie = HessianHttpProxy.cookieMap.get(host + path); if (cookie != null) { conn.setRequestProperty("Cookie", cookie.value); log.finest("Cookie set in request:" + cookie.value); break; } int i = path.lastIndexOf("/"); if (0==i && 1<path.length()) { path = "/"; } else { path = path.substring(0, i); } } } } }
zzgfly-hessdroid
src/com/caucho/hessian/client/HessianHttpProxyFactory.java
Java
asf20
6,434
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2004 Caucho Technology, Inc. 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.client; import com.caucho.hessian.io.*; import com.caucho.services.client.ServiceProxyFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Logger; /** * Factory for creating Hessian client stubs. The returned stub will * call the remote object for all methods. * <p/> * <pre> * String url = "http://localhost:8080/ejb/hello"; * HelloHome hello = (HelloHome) factory.create(HelloHome.class, url); * </pre> * <p/> * After creation, the stub can be like a regular Java class. Because * it makes remote calls, it can throw more exceptions than a Java class. * In particular, it may throw protocol exceptions. * <p/> * <h3>Authentication</h3> * <p/> * <p>The proxy can use HTTP basic authentication if the user and the * password are set. */ @SuppressWarnings({"UnusedDeclaration"}) public class HessianProxyFactory implements ServiceProxyFactory { protected static Logger log = Logger.getLogger(HessianProxyFactory.class.getName()); private SerializerFactory _serializerFactory; private HessianRemoteResolver _resolver; private String _user; private String _password; private String _basicAuth; private boolean _isOverloadEnabled = false; private boolean _isHessian2Reply = true; private boolean _isHessian2Request = false; private boolean _isChunkedPost = true; private boolean _isDebug = false; private long _readTimeout = -1; /** * Creates the new proxy factory. */ public HessianProxyFactory() { _resolver = new HessianProxyResolver(this); } /** * Sets the user. * * @param user <code>String</code> */ public void setUser(String user) { _user = user; _basicAuth = null; } /** * Sets the password. * * @param password <code>String</code> */ public void setPassword(String password) { _password = password; _basicAuth = null; } /** * Sets the debug * * @param isDebug <code>boolean</code> */ public void setDebug(boolean isDebug) { _isDebug = isDebug; } /** * Gets the debug * * @return <code>boolean</code> */ public boolean isDebug() { return _isDebug; } /** * Returns true if overloaded methods are allowed (using mangling) * * @return <code>boolean</code> */ public boolean isOverloadEnabled() { return _isOverloadEnabled; } /** * set true if overloaded methods are allowed (using mangling) * * @param isOverloadEnabled <code>boolean</code> */ public void setOverloadEnabled(boolean isOverloadEnabled) { _isOverloadEnabled = isOverloadEnabled; } /** * Set true if should use chunked encoding on the request. * * @param isChunked <code>boolean</code> */ public void setChunkedPost(boolean isChunked) { _isChunkedPost = isChunked; } /** * Set true if should use chunked encoding on the request. * * @return <code>boolean</code> */ public boolean isChunkedPost() { return _isChunkedPost; } /** * The socket timeout on requests in milliseconds. * * @return <code>long</code> */ public long getReadTimeout() { return _readTimeout; } /** * The socket timeout on requests in milliseconds. * * @param timeout <code>long</code> */ public void setReadTimeout(long timeout) { _readTimeout = timeout; } /** * True if the proxy can read Hessian 2 responses. * * @param isHessian2 <code>boolean</code> */ public void setHessian2Reply(boolean isHessian2) { _isHessian2Reply = isHessian2; } /** * True if the proxy should send Hessian 2 requests. * * @param isHessian2 <code>boolean</code> */ public void setHessian2Request(boolean isHessian2) { _isHessian2Request = isHessian2; if (isHessian2) _isHessian2Reply = true; } /** * @return <code>HessianRemoteResolver</code> the remote resolver. */ public HessianRemoteResolver getRemoteResolver() { return _resolver; } /** * Sets the serializer factory. * * @param factory <code>SerializerFactory</code> */ public void setSerializerFactory(SerializerFactory factory) { _serializerFactory = factory; } /** * Gets the serializer factory. * * @return <code>SerializerFactory</code> */ public SerializerFactory getSerializerFactory() { if (_serializerFactory == null) _serializerFactory = new SerializerFactory(); return _serializerFactory; } /** * Creates the URL connection. * * @param url <coe>URL</code> * @return <code>URLConnection</code> * @throws IOException if connection cannot be opened */ protected URLConnection openConnection(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setDoOutput(true); if (_readTimeout > 0) { try { conn.setReadTimeout((int) _readTimeout); } catch (Throwable e) { // intentionally empty } } conn.setRequestProperty("Content-Type", "x-application/hessian"); if (_basicAuth != null) conn.setRequestProperty("Authorization", _basicAuth); else if (_user != null && _password != null) { _basicAuth = "Basic " + base64(_user + ":" + _password); conn.setRequestProperty("Authorization", _basicAuth); } return conn; } /** * Creates a new proxy with the specified URL. The API class uses * the java.api.class value from _hessian_ * * @param urlName the URL where the client object is located. * @return a proxy to the object with the specified interface. * @throws java.net.MalformedURLException if URL object cannot be created with the provided urlName * @throws ClassNotFoundException if the current Thread's contextClassLoader cannot find the api class */ @SuppressWarnings({"unchecked"}) public Object create(String urlName) throws MalformedURLException, ClassNotFoundException { HessianMetaInfoAPI metaInfo = create(HessianMetaInfoAPI.class, urlName); String apiClassName = (String) metaInfo._hessian_getAttribute("java.api.class"); if (apiClassName == null) { throw new HessianRuntimeException(urlName + " has an unknown api."); } ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class<Object> apiClass = (Class<Object>) Class.forName(apiClassName, false, loader); return create(apiClass, urlName); } /** * Creates a new proxy with the specified URL. The returned object * is a proxy with the interface specified by api. * <p/> * <pre> * String url = "http://localhost:8080/ejb/hello"); * HelloHome hello = (HelloHome) factory.create(HelloHome.class, url); * </pre> * * @param api the interface the proxy class needs to implement * @param urlName the URL where the client object is located. * @return a proxy to the object with the specified interface. */ public <T>T create(Class<T> api, String urlName) throws MalformedURLException { return create(api, urlName, Thread.currentThread().getContextClassLoader()); } /** * Creates a new proxy with the specified URL. The returned object * is a proxy with the interface specified by api. * <p/> * <pre> * String url = "http://localhost:8080/ejb/hello"); * HelloHome hello = (HelloHome) factory.create(HelloHome.class, url); * </pre> * * @param api the interface the proxy class needs to implement * @param urlName the URL where the client object is located. * @param loader <code>ClassLoader</code> to be used loading the proxy instance's class * @return a proxy to the object with the specified interface. * @throws java.net.MalformedURLException if URL object cannot be created with the provided urlName */ @SuppressWarnings({"unchecked"}) public <T>T create(Class<T> api, String urlName, ClassLoader loader) throws MalformedURLException { if (api == null) { throw new NullPointerException("api must not be null for HessianProxyFactory.create()"); } InvocationHandler handler; URL url = new URL(urlName); handler = new HessianProxy(this, url); return (T) Proxy.newProxyInstance(loader, new Class[]{api, HessianRemoteObject.class}, handler); } public AbstractHessianInput getHessianInput(InputStream is) { AbstractHessianInput in; if (_isDebug) is = new HessianDebugInputStream(is, new PrintWriter(System.out)); in = new Hessian2Input(is); in.setRemoteResolver(getRemoteResolver()); in.setSerializerFactory(getSerializerFactory()); return in; } public AbstractHessianOutput getHessianOutput(OutputStream os) { AbstractHessianOutput out; if (_isHessian2Request) out = new Hessian2Output(os); else { HessianOutput out1 = new HessianOutput(os); out = out1; if (_isHessian2Reply) out1.setVersion(2); } out.setSerializerFactory(getSerializerFactory()); return out; } /** * Creates the Base64 value. * * @param value <code>String</code> * @return <code>String</code> base65 encoded String */ private String base64(String value) { StringBuffer cb = new StringBuffer(); int i; for (i = 0; i + 2 < value.length(); i += 3) { long chunk = (int) value.charAt(i); chunk = (chunk << 8) + (int) value.charAt(i + 1); chunk = (chunk << 8) + (int) value.charAt(i + 2); cb.append(encode(chunk >> 18)); cb.append(encode(chunk >> 12)); cb.append(encode(chunk >> 6)); cb.append(encode(chunk)); } if (i + 1 < value.length()) { long chunk = (int) value.charAt(i); chunk = (chunk << 8) + (int) value.charAt(i + 1); chunk <<= 8; cb.append(encode(chunk >> 18)); cb.append(encode(chunk >> 12)); cb.append(encode(chunk >> 6)); cb.append('='); } else if (i < value.length()) { long chunk = (int) value.charAt(i); chunk <<= 16; cb.append(encode(chunk >> 18)); cb.append(encode(chunk >> 12)); cb.append('='); cb.append('='); } return cb.toString(); } public static char encode(long d) { d &= 0x3f; if (d < 26) return (char) (d + 'A'); else if (d < 52) return (char) (d + 'a' - 26); else if (d < 62) return (char) (d + '0' - 52); else if (d == 62) return '+'; else return '/'; } }
zzgfly-hessdroid
src/com/caucho/hessian/client/HessianProxyFactory.java
Java
asf20
13,763
/* * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.client; import com.caucho.hessian.HessianException; /** * Exception caused by failure of the client proxy to connect to the server. */ public class HessianConnectionException extends HessianException { /** * Zero-arg constructor. */ public HessianConnectionException() { } /** * Create the exception. */ public HessianConnectionException(String message) { super(message); } /** * Create the exception. */ public HessianConnectionException(String message, Throwable rootCause) { super(message, rootCause); } /** * Create the exception. */ public HessianConnectionException(Throwable rootCause) { super(rootCause); } }
zzgfly-hessdroid
src/com/caucho/hessian/client/HessianConnectionException.java
Java
asf20
2,954
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2004 Caucho Technology, Inc. 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.client; import com.caucho.hessian.io.*; import com.caucho.services.server.AbstractSkeleton; import java.io.*; import java.util.logging.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.WeakHashMap; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; /** * Proxy implementation for Hessian clients. Applications will generally use * HessianProxyFactory to create proxy clients. */ public class HessianProxy implements InvocationHandler { private static final Logger log = Logger.getLogger(HessianProxy.class .getName()); protected HessianProxyFactory _factory; private WeakHashMap<Method, String> _mangleMap = new WeakHashMap<Method, String>(); private URL _url; /** * Package protected constructor for factory */ HessianProxy(HessianProxyFactory factory, URL url) { _factory = factory; _url = url; } /** * Protected constructor for subclassing */ protected HessianProxy(URL url, HessianProxyFactory factory) { _factory = factory; _url = url; } /** * Returns the proxy's URL. */ public URL getURL() { return _url; } /** * Handles the object invocation. * * @param proxy * the proxy object to invoke * @param method * the method to call * @param args * the arguments to the proxy object */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String mangleName; synchronized (_mangleMap) { mangleName = _mangleMap.get(method); } if (mangleName == null) { String methodName = method.getName(); Class[] params = method.getParameterTypes(); // equals and hashCode are special cased if (methodName.equals("equals") && params.length == 1 && params[0].equals(Object.class)) { Object value = args[0]; if (value == null || !Proxy.isProxyClass(value.getClass())) return Boolean.FALSE; HessianProxy handler = (HessianProxy) Proxy .getInvocationHandler(value); return Boolean.valueOf(_url.equals(handler.getURL())); } else if (methodName.equals("hashCode") && params.length == 0) return Integer.valueOf(_url.hashCode()); else if (methodName.equals("getHessianType")) return proxy.getClass().getInterfaces()[0].getName(); else if (methodName.equals("getHessianURL")) return _url.toString(); else if (methodName.equals("toString") && params.length == 0) return "HessianProxy[" + _url + "]"; if (!_factory.isOverloadEnabled()) mangleName = method.getName(); else mangleName = mangleName(method); synchronized (_mangleMap) { _mangleMap.put(method, mangleName); } } InputStream is = null; URLConnection conn = null; HttpURLConnection httpConn = null; try { if (log.isLoggable(Level.FINER)) log.finer("Hessian[" + _url + "] calling " + mangleName); conn = sendRequest(mangleName, args); if (conn instanceof HttpURLConnection) { httpConn = (HttpURLConnection) conn; int code = 500; try { code = httpConn.getResponseCode(); } catch (Exception e) { } parseResponseHeaders(conn); if (code != 200) { StringBuffer sb = new StringBuffer(); int ch; try { is = httpConn.getInputStream(); if (is != null) { while ((ch = is.read()) >= 0) sb.append((char) ch); is.close(); } is = httpConn.getErrorStream(); if (is != null) { while ((ch = is.read()) >= 0) sb.append((char) ch); } } catch (FileNotFoundException e) { throw new HessianConnectionException( "HessianProxy cannot connect to '" + _url, e); } catch (IOException e) { if (is == null) throw new HessianConnectionException(code + ": " + e, e); else throw new HessianConnectionException(code + ": " + sb, e); } if (is != null) is.close(); throw new HessianConnectionException(code + ": " + sb.toString()); } } is = conn.getInputStream(); if (log.isLoggable(Level.FINEST)) { PrintWriter dbg = new PrintWriter(new LogWriter(log)); is = new HessianDebugInputStream(is, dbg); } AbstractHessianInput in = _factory.getHessianInput(is); in.startReply(); Object value = in.readObject(method.getReturnType()); if (value instanceof InputStream) { value = new ResultInputStream(httpConn, is, in, (InputStream) value); is = null; httpConn = null; } else in.completeReply(); return value; } catch (HessianProtocolException e) { throw new HessianRuntimeException(e); } finally { try { if (is != null) is.close(); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } try { if (httpConn != null) httpConn.disconnect(); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } } protected String mangleName(Method method) { Class[] param = method.getParameterTypes(); if (param == null || param.length == 0) return method.getName(); else return AbstractSkeleton.mangleName(method, false); } /** * Method that allows subclasses to parse response headers such as cookies. * Default implementation is empty. * * @param conn */ protected void parseResponseHeaders(URLConnection conn) { } protected URLConnection sendRequest(String methodName, Object[] args) throws IOException { URLConnection conn = null; conn = _factory.openConnection(_url); boolean isValid = false; try { // Used chunked mode when available, i.e. JDK 1.5. if (_factory.isChunkedPost() && conn instanceof HttpURLConnection) { try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setChunkedStreamingMode(8 * 1024); } catch (Throwable e) { } } addRequestHeaders(conn); OutputStream os = null; try { os = conn.getOutputStream(); } catch (Exception e) { throw new HessianRuntimeException(e); } if (log.isLoggable(Level.FINEST)) { PrintWriter dbg = new PrintWriter(new LogWriter(log)); os = new HessianDebugOutputStream(os, dbg); } AbstractHessianOutput out = _factory.getHessianOutput(os); out.call(methodName, args); out.flush(); isValid = true; return conn; } finally { if (!isValid && conn instanceof HttpURLConnection) ((HttpURLConnection) conn).disconnect(); } } /** * Method that allows subclasses to add request headers such as cookies. * Default implementation is empty. */ protected void addRequestHeaders(URLConnection conn) { } static class ResultInputStream extends InputStream { private HttpURLConnection _conn; private InputStream _connIs; private AbstractHessianInput _in; private InputStream _hessianIs; ResultInputStream(HttpURLConnection conn, InputStream is, AbstractHessianInput in, InputStream hessianIs) { _conn = conn; _connIs = is; _in = in; _hessianIs = hessianIs; } public int read() throws IOException { if (_hessianIs != null) { int value = _hessianIs.read(); if (value < 0) close(); return value; } else return -1; } public int read(byte[] buffer, int offset, int length) throws IOException { if (_hessianIs != null) { int value = _hessianIs.read(buffer, offset, length); if (value < 0) close(); return value; } else return -1; } public void close() throws IOException { HttpURLConnection conn = _conn; _conn = null; InputStream connIs = _connIs; _connIs = null; AbstractHessianInput in = _in; _in = null; InputStream hessianIs = _hessianIs; _hessianIs = null; try { if (hessianIs != null) hessianIs.close(); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } try { if (in != null) { in.completeReply(); in.close(); } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } try { if (connIs != null) { connIs.close(); } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } try { if (conn != null) { conn.disconnect(); } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } } static class LogWriter extends Writer { private Logger _log; private Level _level = Level.FINEST; private StringBuilder _sb = new StringBuilder(); LogWriter(Logger log) { _log = log; } public void write(char ch) { if (ch == '\n' && _sb.length() > 0) { _log.fine(_sb.toString()); _sb.setLength(0); } else _sb.append((char) ch); } public void write(char[] buffer, int offset, int length) { for (int i = 0; i < length; i++) { char ch = buffer[offset + i]; if (ch == '\n' && _sb.length() > 0) { _log.log(_level, _sb.toString()); _sb.setLength(0); } else _sb.append((char) ch); } } public void flush() { } public void close() { if (_sb.length() > 0) _log.log(_level, _sb.toString()); } } }
zzgfly-hessdroid
src/com/caucho/hessian/client/HessianProxy.java
Java
asf20
11,349
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.client; /** * Wrapper for protocol exceptions thrown in the proxy. */ public class HessianRuntimeException extends RuntimeException { private Throwable rootCause; /** * Zero-arg constructor. */ public HessianRuntimeException() { } /** * Create the exception. */ public HessianRuntimeException(String message) { super(message); } /** * Create the exception. */ public HessianRuntimeException(String message, Throwable rootCause) { super(message); this.rootCause = rootCause; } /** * Create the exception. */ public HessianRuntimeException(Throwable rootCause) { super(String.valueOf(rootCause)); this.rootCause = rootCause; } /** * Returns the underlying cause. */ public Throwable getRootCause() { return this.rootCause; } /** * Returns the underlying cause. */ public Throwable getCause() { return getRootCause(); } }
zzgfly-hessdroid
src/com/caucho/hessian/client/HessianRuntimeException.java
Java
asf20
3,206
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.client; import com.caucho.hessian.io.HessianRemoteResolver; import java.io.IOException; /** * Looks up remote objects in the proxy. */ public class HessianProxyResolver implements HessianRemoteResolver { private HessianProxyFactory _factory; /** * Creates an uninitialized Hessian remote resolver. */ public HessianProxyResolver(HessianProxyFactory factory) { _factory = factory; } /** * Looks up a proxy object. */ public Object lookup(String type, String url) throws IOException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Class api = Class.forName(type, false, loader); return _factory.create(api, url); } catch (Exception e) { throw new IOException(String.valueOf(e)); } } }
zzgfly-hessdroid
src/com/caucho/hessian/client/HessianProxyResolver.java
Java
asf20
3,057
/* * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian; /** * Base runtime exception for Hessian exceptions. */ public class HessianException extends RuntimeException { /** * Zero-arg constructor. */ public HessianException() { } /** * Create the exception. */ public HessianException(String message) { super(message); } /** * Create the exception. */ public HessianException(String message, Throwable rootCause) { super(message, rootCause); } /** * Create the exception. */ public HessianException(Throwable rootCause) { super(rootCause); } }
zzgfly-hessdroid
src/com/caucho/hessian/HessianException.java
Java
asf20
2,790
/* * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Burlap", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.util; /** * The IntMap provides a simple hashmap from keys to integers. The API is * an abbreviation of the HashMap collection API. * * <p>The convenience of IntMap is avoiding all the silly wrapping of * integers. */ public class IdentityIntMap { /** * Encoding of a null entry. Since NULL is equal to Integer.MIN_VALUE, * it's impossible to distinguish between the two. */ public final static int NULL = 0xdeadbeef; // Integer.MIN_VALUE + 1; private static final Object DELETED = new Object(); private Object []_keys; private int []_values; private int _size; private int _mask; /** * Create a new IntMap. Default size is 16. */ public IdentityIntMap() { _keys = new Object[256]; _values = new int[256]; _mask = _keys.length - 1; _size = 0; } /** * Clear the hashmap. */ public void clear() { Object []keys = _keys; int []values = _values; for (int i = keys.length - 1; i >= 0; i--) { keys[i] = null; values[i] = 0; } _size = 0; } /** * Returns the current number of entries in the map. */ public int size() { return _size; } /** * Puts a new value in the property table with the appropriate flags */ public int get(Object key) { int mask = _mask; int hash = System.identityHashCode(key) % mask & mask; Object []keys = _keys; while (true) { Object mapKey = keys[hash]; if (mapKey == null) return NULL; else if (mapKey == key) return _values[hash]; hash = (hash + 1) % mask; } } /** * Expands the property table */ private void resize(int newSize) { Object []newKeys = new Object[newSize]; int []newValues = new int[newSize]; int mask = _mask = newKeys.length - 1; Object []keys = _keys; int values[] = _values; for (int i = keys.length - 1; i >= 0; i--) { Object key = keys[i]; if (key == null || key == DELETED) continue; int hash = System.identityHashCode(key) % mask & mask; while (true) { if (newKeys[hash] == null) { newKeys[hash] = key; newValues[hash] = values[i]; break; } hash = (hash + 1) % mask; } } _keys = newKeys; _values = newValues; } /** * Puts a new value in the property table with the appropriate flags */ public int put(Object key, int value) { int mask = _mask; int hash = System.identityHashCode(key) % mask & mask; Object []keys = _keys; while (true) { Object testKey = keys[hash]; if (testKey == null || testKey == DELETED) { keys[hash] = key; _values[hash] = value; _size++; if (keys.length <= 4 * _size) resize(4 * keys.length); return NULL; } else if (key != testKey) { hash = (hash + 1) % mask; continue; } else { int old = _values[hash]; _values[hash] = value; return old; } } } /** * Deletes the entry. Returns true if successful. */ public int remove(Object key) { int mask = _mask; int hash = System.identityHashCode(key) % mask & mask; while (true) { Object mapKey = _keys[hash]; if (mapKey == null) return NULL; else if (mapKey == key) { _keys[hash] = DELETED; _size--; return _values[hash]; } hash = (hash + 1) % mask; } } public String toString() { StringBuffer sbuf = new StringBuffer(); sbuf.append("IntMap["); boolean isFirst = true; for (int i = 0; i <= _mask; i++) { if (_keys[i] != null && _keys[i] != DELETED) { if (! isFirst) sbuf.append(", "); isFirst = false; sbuf.append(_keys[i]); sbuf.append(":"); sbuf.append(_values[i]); } } sbuf.append("]"); return sbuf.toString(); } }
zzgfly-hessdroid
src/com/caucho/hessian/util/IdentityIntMap.java
Java
asf20
6,228
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; import java.util.Date; /** * Serializing a sql date object. */ public class SqlDateSerializer extends AbstractSerializer { public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { if (obj == null) out.writeNull(); else { Class cl = obj.getClass(); if (out.addRef(obj)) return; int ref = out.writeObjectBegin(cl.getName()); if (ref < -1) { out.writeString("value"); out.writeUTCDate(((Date) obj).getTime()); out.writeMapEnd(); } else { if (ref == -1) { out.writeInt(1); out.writeString("value"); out.writeObjectBegin(cl.getName()); } out.writeUTCDate(((Date) obj).getTime()); } } } }
zzgfly-hessdroid
src/com/caucho/hessian/io/SqlDateSerializer.java
Java
asf20
3,004
/* * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Burlap", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; /** * Serializing an object for known object types. */ public class JavaDeserializer extends AbstractMapDeserializer { private static final Logger log = Logger.getLogger(JavaDeserializer.class.getName()); private final static Map<Class<?>, FieldDeserializer> deserializerCache = new HashMap<Class<?>, FieldDeserializer>(); private final Class<?> _type; private Map<String, FieldDeserializer> _fieldMap; private Map<String, Field> _keyFieldMap; private Method _readResolve; private Constructor _constructor; private Object []_constructorArgs; public JavaDeserializer(Class<?> type) { _type = type; _keyFieldMap = new HashMap<String, Field>(); initFieldMap(type); _readResolve = getReadResolve(type); if (_readResolve != null) { _readResolve.setAccessible(true); } Constructor []constructors = type.getDeclaredConstructors(); long bestCost = Long.MAX_VALUE; for (int i = 0; i < constructors.length; i++) { Class []param = constructors[i].getParameterTypes(); long cost = 0; for (int j = 0; j < param.length; j++) { cost = 4 * cost; if (Object.class.equals(param[j])) cost += 1; else if (String.class.equals(param[j])) cost += 2; else if (int.class.equals(param[j])) cost += 3; else if (long.class.equals(param[j])) cost += 4; else if (param[j].isPrimitive()) cost += 5; else cost += 6; } if (cost < 0 || cost > (1 << 48)) cost = 1 << 48; cost += (long) param.length << 48; if (cost < bestCost) { _constructor = constructors[i]; bestCost = cost; } } if (_constructor != null) { _constructor.setAccessible(true); Class []params = _constructor.getParameterTypes(); _constructorArgs = new Object[params.length]; for (int i = 0; i < params.length; i++) { _constructorArgs[i] = getParamArg(params[i]); } } } public Class<?> getType() { return _type; } public Object readMap(AbstractHessianInput in) throws IOException { try { Object obj = instantiate(); return readMap(in, obj); } catch (IOException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IOExceptionWrapper(_type.getName() + ":" + e.getMessage(), e); } } public Object readObject(AbstractHessianInput in, String []fieldNames) throws IOException { try { Object obj = instantiate(); return readObject(in, obj, fieldNames); } catch (IOException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IOExceptionWrapper(_type.getName() + ":" + e.getMessage(), e); } } private static Method getReadResolve(Class<?> cl) { try { return cl.getMethod("readResolve", new Class[0]); } catch (Exception e) {} return null; } public Object readMap(AbstractHessianInput in, Object obj) throws IOException { try { int ref = in.addRef(obj); while (! in.isEnd()) { Object key = in.readObject(); final Field field = _keyFieldMap.get(key); final FieldDeserializer deser = (FieldDeserializer) _fieldMap.get(key); if (deser != null) deser.deserialize(in, field, obj); else in.readObject(); } in.readMapEnd(); Object resolve = resolve(obj); if (obj != resolve) in.setRef(ref, resolve); return resolve; } catch (IOException e) { throw e; } catch (Exception e) { throw new IOExceptionWrapper(e); } } public Object readObject(AbstractHessianInput in, Object obj, String []fieldNames) throws IOException { try { int ref = in.addRef(obj); for (int i = 0; i < fieldNames.length; i++) { String name = fieldNames[i]; final Field field = _keyFieldMap.get(name); final FieldDeserializer deser = (FieldDeserializer) _fieldMap.get(name); if (deser != null) deser.deserialize(in, _keyFieldMap.get(name), obj); else in.readObject(); } Object resolve = resolve(obj); if (obj != resolve) in.setRef(ref, resolve); return resolve; } catch (IOException e) { throw e; } catch (Exception e) { throw new IOExceptionWrapper(obj.getClass().getName() + ":" + e, e); } } private Object resolve(Object obj) throws Exception { // if there's a readResolve method, call it try { if (_readResolve != null) return _readResolve.invoke(obj, new Object[0]); } catch (InvocationTargetException e) { if (e.getTargetException() != null) throw e; } return obj; } protected <T> T instantiate() throws Exception { try { if (_constructor != null) return (T) _constructor.newInstance(_constructorArgs); else return (T) _type.newInstance(); } catch (Exception e) { throw new HessianProtocolException("'" + _type.getName() + "' could not be instantiated", e); } } /** * Creates a map of the classes fields. */ private void initFieldMap(Class<?> cl) { _fieldMap = new HashMap<String, FieldDeserializer>(); while (cl != null) { Field []fields = cl.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { final Field field = fields[i]; if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue; else if (_fieldMap.get(field.getName()) != null) continue; try { field.setAccessible(true); } catch (Throwable e) {} final Class<?> type = field.getType(); FieldDeserializer deser = null; if (!deserializerCache.containsKey(type)) { if (String.class.equals(type)) deser = new StringFieldDeserializer(); else if (byte.class.equals(type)) { deser = new ByteFieldDeserializer(); } else if (short.class.equals(type)) { deser = new ShortFieldDeserializer(); } else if (int.class.equals(type)) { deser = new IntFieldDeserializer(); } else if (long.class.equals(type)) { deser = new LongFieldDeserializer(); } else if (float.class.equals(type)) { deser = new FloatFieldDeserializer(); } else if (double.class.equals(type)) { deser = new DoubleFieldDeserializer(); } else if (boolean.class.equals(type)) { deser = new BooleanFieldDeserializer(); } else if (java.sql.Date.class.equals(type)) { deser = new SqlDateFieldDeserializer(); } else if (java.sql.Timestamp.class.equals(type)) { deser = new SqlTimestampFieldDeserializer(); } else if (java.sql.Time.class.equals(type)) { deser = new SqlTimeFieldDeserializer(); } else { deser = new ObjectFieldDeserializer(); } deserializerCache.put(type, deser); } _fieldMap.put(field.getName(), deserializerCache.get(type)); _keyFieldMap.put(field.getName(), field); } cl = cl.getSuperclass(); } } /** * Creates a map of the classes fields. */ protected static Object getParamArg(Class cl) { if (! cl.isPrimitive()) return null; else if (boolean.class.equals(cl)) return Boolean.FALSE; else if (byte.class.equals(cl)) return new Byte((byte) 0); else if (short.class.equals(cl)) return new Short((short) 0); else if (char.class.equals(cl)) return new Character((char) 0); else if (int.class.equals(cl)) return Integer.valueOf(0); else if (long.class.equals(cl)) return Long.valueOf(0); else if (float.class.equals(cl)) return Float.valueOf(0); else if (double.class.equals(cl)) return Double.valueOf(0); else throw new UnsupportedOperationException(); } abstract static class FieldDeserializer { abstract void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException; } static class ObjectFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { Object value = null; try { value = in.readObject(field.getType()); field.set(obj, value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class BooleanFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { boolean value = false; try { value = in.readBoolean(); field.setBoolean(obj, value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class ByteFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { int value = 0; try { value = in.readInt(); field.setByte(obj, (byte) value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class ShortFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { int value = 0; try { value = in.readInt(); field.setShort(obj, (short) value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class IntFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { int value = 0; try { value = in.readInt(); field.setInt(obj, value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class LongFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { long value = 0; try { value = in.readLong(); field.setLong(obj, value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class FloatFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { double value = 0; try { value = in.readDouble(); field.setFloat(obj, (float) value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class DoubleFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { double value = 0; try { value = in.readDouble(); field.setDouble(obj, value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class StringFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { String value = null; try { value = in.readString(); field.set(obj, value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class SqlDateFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { java.sql.Date value = null; try { java.util.Date date = (java.util.Date) in.readObject(); value = new java.sql.Date(date.getTime()); field.set(obj, value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class SqlTimestampFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { java.sql.Timestamp value = null; try { java.util.Date date = (java.util.Date) in.readObject(); value = new java.sql.Timestamp(date.getTime()); field.set(obj, value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static class SqlTimeFieldDeserializer extends FieldDeserializer { void deserialize(AbstractHessianInput in, Field field, Object obj) throws IOException { java.sql.Time value = null; try { java.util.Date date = (java.util.Date) in.readObject(); value = new java.sql.Time(date.getTime()); field.set(obj, value); } catch (Exception e) { logDeserializeError(field, obj, value, e); } } } static void logDeserializeError(Field field, Object obj, Object value, Throwable e) throws IOException { String fieldName = (field.getDeclaringClass().getName() + "." + field.getName()); if (e instanceof HessianFieldException) throw (HessianFieldException) e; else if (e instanceof IOException) throw new HessianFieldException(fieldName + ": " + e.getMessage(), e); if (value != null) throw new HessianFieldException(fieldName + ": " + value.getClass().getName() + " (" + value + ")" + " cannot be assigned to '" + field.getType().getName() + "'"); else throw new HessianFieldException(fieldName + ": " + field.getType().getName() + " cannot be assigned from null", e); } }
zzgfly-hessdroid
src/com/caucho/hessian/io/JavaDeserializer.java
Java
asf20
16,135
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; /** * Exception wrapper for IO. */ public class IOExceptionWrapper extends IOException { private Throwable _cause; public IOExceptionWrapper(Throwable cause) { super(cause.toString()); _cause = cause; } public IOExceptionWrapper(String msg, Throwable cause) { super(msg); _cause = cause; } public Throwable getCause() { return _cause; } }
zzgfly-hessdroid
src/com/caucho/hessian/io/IOExceptionWrapper.java
Java
asf20
2,686
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; /** * Deserializing a JDK 1.2 Collection. */ public class AbstractListDeserializer extends AbstractDeserializer { public Object readObject(AbstractHessianInput in) throws IOException { Object obj = in.readObject(); if (obj != null) throw error("expected list at " + obj.getClass().getName() + " (" + obj + ")"); else throw error("expected list at null"); } }
zzgfly-hessdroid
src/com/caucho/hessian/io/AbstractListDeserializer.java
Java
asf20
2,692
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; /** * Serializing a remote object. */ public class StringValueSerializer extends AbstractSerializer { public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { if (obj == null) out.writeNull(); else { if (out.addRef(obj)) return; Class cl = obj.getClass(); int ref = out.writeObjectBegin(cl.getName()); if (ref < -1) { out.writeString("value"); out.writeString(obj.toString()); out.writeMapEnd(); } else { if (ref == -1) { out.writeInt(1); out.writeString("value"); out.writeObjectBegin(cl.getName()); } out.writeString(obj.toString()); } } } }
zzgfly-hessdroid
src/com/caucho/hessian/io/StringValueSerializer.java
Java
asf20
2,965
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; import java.lang.reflect.Method; /** * Deserializing an enum valued object */ public class EnumDeserializer extends AbstractDeserializer { private Class _enumType; private Method _valueOf; public EnumDeserializer(Class cl) { // hessian/33b[34], hessian/3bb[78] if (cl.isEnum()) _enumType = cl; else if (cl.getSuperclass().isEnum()) _enumType = cl.getSuperclass(); else throw new RuntimeException("Class " + cl.getName() + " is not an enum"); try { _valueOf = _enumType.getMethod("valueOf", new Class[] { Class.class, String.class }); } catch (Exception e) { throw new RuntimeException(e); } } public Class getType() { return _enumType; } public Object readMap(AbstractHessianInput in) throws IOException { String name = null; while (! in.isEnd()) { String key = in.readString(); if (key.equals("name")) name = in.readString(); else in.readObject(); } in.readMapEnd(); Object obj = create(name); in.addRef(obj); return obj; } public Object readObject(AbstractHessianInput in, String []fieldNames) throws IOException { String name = null; for (int i = 0; i < fieldNames.length; i++) { if ("name".equals(fieldNames[i])) name = in.readString(); else in.readObject(); } Object obj = create(name); in.addRef(obj); return obj; } private Object create(String name) throws IOException { if (name == null) throw new IOException(_enumType.getName() + " expects name."); try { return _valueOf.invoke(null, _enumType, name); } catch (Exception e) { throw new IOExceptionWrapper(e); } } }
zzgfly-hessdroid
src/com/caucho/hessian/io/EnumDeserializer.java
Java
asf20
4,056
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; /** * Looks up remote objects. The default just returns a HessianRemote object. */ public class AbstractHessianResolver implements HessianRemoteResolver { /** * Looks up a proxy object. */ public Object lookup(String type, String url) throws IOException { return new HessianRemote(type, url); } }
zzgfly-hessdroid
src/com/caucho/hessian/io/AbstractHessianResolver.java
Java
asf20
2,618
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.util.logging.*; public class EnvelopeFactory { private static final Logger log = Logger.getLogger(EnvelopeFactory.class.getName()); }
zzgfly-hessdroid
src/com/caucho/hessian/io/EnvelopeFactory.java
Java
asf20
2,420
/* * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.io.PrintWriter; import java.util.ArrayList; import java.util.logging.Logger; import java.util.logging.Level; /** * Debugging input stream for Hessian requests. */ public class HessianDebugInputStream extends InputStream { private InputStream _is; private HessianDebugState _state; /** * Creates an uninitialized Hessian input stream. */ public HessianDebugInputStream(InputStream is, PrintWriter dbg) { _is = is; if (dbg == null) dbg = new PrintWriter(System.out); _state = new HessianDebugState(dbg); } /** * Creates an uninitialized Hessian input stream. */ public HessianDebugInputStream(InputStream is, Logger log, Level level) { this(is, new PrintWriter(new LogWriter(log, level))); } /** * Reads a character. */ public int read() throws IOException { int ch; InputStream is = _is; if (is == null) return -1; else { ch = is.read(); } _state.next(ch); return ch; } /** * closes the stream. */ public void close() throws IOException { InputStream is = _is; _is = null; if (is != null) is.close(); _state.println(); } static class LogWriter extends Writer { private Logger _log; private Level _level; private StringBuilder _sb = new StringBuilder(); LogWriter(Logger log, Level level) { _log = log; _level = level; } public void write(char ch) { if (ch == '\n' && _sb.length() > 0) { _log.log(_level, _sb.toString()); _sb.setLength(0); } else _sb.append((char) ch); } public void write(char []buffer, int offset, int length) { for (int i = 0; i < length; i++) { char ch = buffer[offset + i]; if (ch == '\n' && _sb.length() > 0) { _log.log(_level, _sb.toString()); _sb.setLength(0); } else _sb.append((char) ch); } } public void flush() { } public void close() { } } }
zzgfly-hessdroid
src/com/caucho/hessian/io/HessianDebugInputStream.java
Java
asf20
4,349
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; import java.util.*; /** * Deserializing a JDK 1.2 Collection. */ public class CollectionDeserializer extends AbstractListDeserializer { private Class _type; public CollectionDeserializer(Class type) { _type = type; } public Class getType() { return _type; } public Object readList(AbstractHessianInput in, int length) throws IOException { Collection list = createList(); in.addRef(list); while (! in.isEnd()) list.add(in.readObject()); in.readEnd(); return list; } public Object readLengthList(AbstractHessianInput in, int length) throws IOException { Collection list = createList(); in.addRef(list); for (; length > 0; length--) list.add(in.readObject()); return list; } private Collection createList() throws IOException { Collection list = null; if (_type == null) list = new ArrayList(); else if (! _type.isInterface()) { try { list = (Collection) _type.newInstance(); } catch (Exception e) { } } if (list != null) { } else if (SortedSet.class.isAssignableFrom(_type)) list = new TreeSet(); else if (Set.class.isAssignableFrom(_type)) list = new HashSet(); else if (List.class.isAssignableFrom(_type)) list = new ArrayList(); else if (Collection.class.isAssignableFrom(_type)) list = new ArrayList(); else { try { list = (Collection) _type.newInstance(); } catch (Exception e) { throw new IOExceptionWrapper(e); } } return list; } }
zzgfly-hessdroid
src/com/caucho/hessian/io/CollectionDeserializer.java
Java
asf20
3,906
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Burlap", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; /** * Serializing an object. */ public interface Serializer { public void writeObject(Object obj, AbstractHessianOutput out) throws IOException; }
zzgfly-hessdroid
src/com/caucho/hessian/io/Serializer.java
Java
asf20
2,451
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * Serializing a JDK 1.2 Collection. */ public class CollectionSerializer extends AbstractSerializer { private boolean _sendJavaType = true; /** * Set true if the java type of the collection should be sent. */ public void setSendJavaType(boolean sendJavaType) { _sendJavaType = sendJavaType; } /** * Return true if the java type of the collection should be sent. */ public boolean getSendJavaType() { return _sendJavaType; } public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { if (out.addRef(obj)) return; Collection list = (Collection) obj; Class cl = obj.getClass(); boolean hasEnd; if (cl.equals(ArrayList.class) || ! _sendJavaType || ! Serializable.class.isAssignableFrom(cl)) hasEnd = out.writeListBegin(list.size(), null); else hasEnd = out.writeListBegin(list.size(), obj.getClass().getName()); Iterator iter = list.iterator(); while (iter.hasNext()) { Object value = iter.next(); out.writeObject(value); } if (hasEnd) out.writeListEnd(); } }
zzgfly-hessdroid
src/com/caucho/hessian/io/CollectionSerializer.java
Java
asf20
3,539
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; /** * Deserializing a Java array */ public class ArrayDeserializer extends AbstractListDeserializer { private Class _componentType; private Class _type; public ArrayDeserializer(Class componentType) { _componentType = componentType; if (_componentType != null) { try { _type = Array.newInstance(_componentType, 0).getClass(); } catch (Exception e) { } } if (_type == null) _type = Object[].class; } public Class getType() { return _type; } /** * Reads the array. */ public Object readList(AbstractHessianInput in, int length) throws IOException { if (length >= 0) { Object []data = createArray(length); in.addRef(data); if (_componentType != null) { for (int i = 0; i < data.length; i++) data[i] = in.readObject(_componentType); } else { for (int i = 0; i < data.length; i++) data[i] = in.readObject(); } in.readListEnd(); return data; } else { ArrayList list = new ArrayList(); in.addRef(list); if (_componentType != null) { while (! in.isEnd()) list.add(in.readObject(_componentType)); } else { while (! in.isEnd()) list.add(in.readObject()); } in.readListEnd(); Object []data = createArray(list.size()); for (int i = 0; i < data.length; i++) data[i] = list.get(i); return data; } } /** * Reads the array. */ public Object readLengthList(AbstractHessianInput in, int length) throws IOException { Object []data = createArray(length); in.addRef(data); if (_componentType != null) { for (int i = 0; i < data.length; i++) data[i] = in.readObject(_componentType); } else { for (int i = 0; i < data.length; i++) data[i] = in.readObject(); } return data; } protected Object []createArray(int length) { if (_componentType != null) return (Object []) Array.newInstance(_componentType, length); else return new Object[length]; } public String toString() { return "ArrayDeserializer[" + _componentType + "]"; } }
zzgfly-hessdroid
src/com/caucho/hessian/io/ArrayDeserializer.java
Java
asf20
4,586
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * Output stream for Hessian requests. * * <p>HessianOutput is unbuffered, so any client needs to provide * its own buffering. * * <h3>Serialization</h3> * * <pre> * OutputStream os = new FileOutputStream("test.xml"); * HessianOutput out = new HessianSerializerOutput(os); * * out.writeObject(obj); * os.close(); * </pre> * * <h3>Writing an RPC Call</h3> * * <pre> * OutputStream os = ...; // from http connection * HessianOutput out = new HessianSerializerOutput(os); * String value; * * out.startCall("hello"); // start hello call * out.writeString("arg1"); // write a string argument * out.completeCall(); // complete the call * </pre> */ public class HessianSerializerOutput extends HessianOutput { /** * Creates a new Hessian output stream, initialized with an * underlying output stream. * * @param os the underlying output stream. */ public HessianSerializerOutput(OutputStream os) { super(os); } /** * Creates an uninitialized Hessian output stream. */ public HessianSerializerOutput() { } /** * Applications which override this can do custom serialization. * * @param object the object to write. */ public void writeObjectImpl(Object obj) throws IOException { Class cl = obj.getClass(); try { Method method = cl.getMethod("writeReplace", new Class[0]); Object repl = method.invoke(obj, new Object[0]); writeObject(repl); return; } catch (Exception e) { } try { writeMapBegin(cl.getName()); for (; cl != null; cl = cl.getSuperclass()) { Field []fields = cl.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue; // XXX: could parameterize the handler to only deal with public field.setAccessible(true); writeString(field.getName()); writeObject(field.get(obj)); } } writeMapEnd(); } catch (IllegalAccessException e) { throw new IOExceptionWrapper(e); } } }
zzgfly-hessdroid
src/com/caucho/hessian/io/HessianSerializerOutput.java
Java
asf20
4,635
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Burlap", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.logging.*; /** * Serializing an object for known object types. */ public class BeanSerializer extends AbstractSerializer { private static final Logger log = Logger.getLogger(BeanSerializer.class.getName()); private static final Object []NULL_ARGS = new Object[0]; private Method []_methods; private String []_names; private Object _writeReplaceFactory; private Method _writeReplace; public BeanSerializer(Class cl) { introspectWriteReplace(cl); ArrayList primitiveMethods = new ArrayList(); ArrayList compoundMethods = new ArrayList(); for (; cl != null; cl = cl.getSuperclass()) { Method []methods = cl.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (Modifier.isStatic(method.getModifiers())) continue; if (method.getParameterTypes().length != 0) continue; String name = method.getName(); if (! name.startsWith("get")) continue; Class type = method.getReturnType(); if (type.equals(void.class)) continue; if (findSetter(methods, name, type) == null) continue; // XXX: could parameterize the handler to only deal with public method.setAccessible(true); if (type.isPrimitive() || type.getName().startsWith("java.lang.") && ! type.equals(Object.class)) primitiveMethods.add(method); else compoundMethods.add(method); } } ArrayList methodList = new ArrayList(); methodList.addAll(primitiveMethods); methodList.addAll(compoundMethods); _methods = new Method[methodList.size()]; methodList.toArray(_methods); _names = new String[_methods.length]; for (int i = 0; i < _methods.length; i++) { String name = _methods[i].getName(); name = name.substring(3); int j = 0; for (; j < name.length() && Character.isUpperCase(name.charAt(j)); j++) { } if (j == 1) name = name.substring(0, j).toLowerCase() + name.substring(j); else if (j > 1) name = name.substring(0, j - 1).toLowerCase() + name.substring(j - 1); _names[i] = name; } } private void introspectWriteReplace(Class cl) { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); String className = cl.getName() + "HessianSerializer"; Class serializerClass = Class.forName(className, false, loader); Object serializerObject = serializerClass.newInstance(); Method writeReplace = getWriteReplace(serializerClass, cl); if (writeReplace != null) { _writeReplaceFactory = serializerObject; _writeReplace = writeReplace; return; } } catch (ClassNotFoundException e) { } catch (Exception e) { log.log(Level.FINER, e.toString(), e); } _writeReplace = getWriteReplace(cl); } /** * Returns the writeReplace method */ protected Method getWriteReplace(Class cl) { for (; cl != null; cl = cl.getSuperclass()) { Method []methods = cl.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().equals("writeReplace") && method.getParameterTypes().length == 0) return method; } } return null; } /** * Returns the writeReplace method */ protected Method getWriteReplace(Class cl, Class param) { for (; cl != null; cl = cl.getSuperclass()) { for (Method method : cl.getDeclaredMethods()) { if (method.getName().equals("writeReplace") && method.getParameterTypes().length == 1 && param.equals(method.getParameterTypes()[0])) return method; } } return null; } public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { if (out.addRef(obj)) return; Class cl = obj.getClass(); try { if (_writeReplace != null) { Object repl; if (_writeReplaceFactory != null) repl = _writeReplace.invoke(_writeReplaceFactory, obj); else repl = _writeReplace.invoke(obj); out.removeRef(obj); out.writeObject(repl); out.replaceRef(repl, obj); return; } } catch (Exception e) { log.log(Level.FINER, e.toString(), e); } int ref = out.writeObjectBegin(cl.getName()); if (ref < -1) { // Hessian 1.1 uses a map for (int i = 0; i < _methods.length; i++) { Method method = _methods[i]; Object value = null; try { value = _methods[i].invoke(obj, (Object []) null); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } out.writeString(_names[i]); out.writeObject(value); } out.writeMapEnd(); } else { if (ref == -1) { out.writeInt(_names.length); for (int i = 0; i < _names.length; i++) out.writeString(_names[i]); out.writeObjectBegin(cl.getName()); } for (int i = 0; i < _methods.length; i++) { Method method = _methods[i]; Object value = null; try { value = _methods[i].invoke(obj, (Object []) null); } catch (Exception e) { log.log(Level.FINER, e.toString(), e); } out.writeObject(value); } } } /** * Finds any matching setter. */ private Method findSetter(Method []methods, String getterName, Class arg) { String setterName = "set" + getterName.substring(3); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (! method.getName().equals(setterName)) continue; if (! method.getReturnType().equals(void.class)) continue; Class []params = method.getParameterTypes(); if (params.length == 1 && params[0].equals(arg)) return method; } return null; } }
zzgfly-hessdroid
src/com/caucho/hessian/io/BeanSerializer.java
Java
asf20
8,066
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Burlap", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; import java.io.InputStream; /** * Serializing a stream object. */ public class InputStreamDeserializer extends AbstractDeserializer { public InputStreamDeserializer() { } public Object readObject(AbstractHessianInput in) throws IOException { return in.readInputStream(); } }
zzgfly-hessdroid
src/com/caucho/hessian/io/InputStreamDeserializer.java
Java
asf20
2,595
/* * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Burlap", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.*; import java.math.BigDecimal; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Factory for returning serialization methods. */ public class SerializerFactory extends AbstractSerializerFactory { private static final Logger log = Logger.getLogger(SerializerFactory.class.getName()); private static Deserializer OBJECT_DESERIALIZER = new BasicDeserializer(BasicDeserializer.OBJECT); private static HashMap _staticSerializerMap; private static HashMap _staticDeserializerMap; private static HashMap _staticTypeMap; protected Serializer _defaultSerializer; // Additional factories protected ArrayList _factories = new ArrayList(); protected CollectionSerializer _collectionSerializer; protected MapSerializer _mapSerializer; private Deserializer _hashMapDeserializer; private Deserializer _arrayListDeserializer; private HashMap _cachedSerializerMap; private HashMap _cachedDeserializerMap; private HashMap _cachedTypeDeserializerMap; private boolean _isAllowNonSerializable; /** * Set true if the collection serializer should send the java type. */ public void setSendCollectionType(boolean isSendType) { if (_collectionSerializer == null) _collectionSerializer = new CollectionSerializer(); _collectionSerializer.setSendJavaType(isSendType); if (_mapSerializer == null) _mapSerializer = new MapSerializer(); _mapSerializer.setSendJavaType(isSendType); } /** * Adds a factory. */ public void addFactory(AbstractSerializerFactory factory) { _factories.add(factory); } /** * If true, non-serializable objects are allowed. */ public void setAllowNonSerializable(boolean allow) { _isAllowNonSerializable = allow; } /** * If true, non-serializable objects are allowed. */ public boolean isAllowNonSerializable() { return _isAllowNonSerializable; } /** * Returns the serializer for a class. * * @param cl the class of the object that needs to be serialized. * * @return a serializer object for the serialization. */ public Serializer getSerializer(Class cl) throws HessianProtocolException { Serializer serializer; serializer = (Serializer) _staticSerializerMap.get(cl); if (serializer != null) return serializer; if (_cachedSerializerMap != null) { synchronized (_cachedSerializerMap) { serializer = (Serializer) _cachedSerializerMap.get(cl); } if (serializer != null) return serializer; } for (int i = 0; serializer == null && _factories != null && i < _factories.size(); i++) { AbstractSerializerFactory factory; factory = (AbstractSerializerFactory) _factories.get(i); serializer = factory.getSerializer(cl); } if (serializer != null) { } else if (JavaSerializer.getWriteReplace(cl) != null) serializer = new JavaSerializer(cl); else if (HessianRemoteObject.class.isAssignableFrom(cl)) serializer = new RemoteSerializer(); // // else if (BurlapRemoteObject.class.isAssignableFrom(cl)) // serializer = new RemoteSerializer(); else if (Map.class.isAssignableFrom(cl)) { if (_mapSerializer == null) _mapSerializer = new MapSerializer(); serializer = _mapSerializer; } else if (Collection.class.isAssignableFrom(cl)) { if (_collectionSerializer == null) { _collectionSerializer = new CollectionSerializer(); } serializer = _collectionSerializer; } else if (cl.isArray()) serializer = new ArraySerializer(); else if (Throwable.class.isAssignableFrom(cl)) serializer = new ThrowableSerializer(cl); else if (InputStream.class.isAssignableFrom(cl)) serializer = new InputStreamSerializer(); else if (Iterator.class.isAssignableFrom(cl)) serializer = IteratorSerializer.create(); else if (Enumeration.class.isAssignableFrom(cl)) serializer = EnumerationSerializer.create(); else if (Calendar.class.isAssignableFrom(cl)) serializer = CalendarSerializer.create(); else if (Locale.class.isAssignableFrom(cl)) serializer = LocaleSerializer.create(); else if (Enum.class.isAssignableFrom(cl)) serializer = new EnumSerializer(cl); if (serializer == null) serializer = getDefaultSerializer(cl); if (_cachedSerializerMap == null) _cachedSerializerMap = new HashMap(8); synchronized (_cachedSerializerMap) { _cachedSerializerMap.put(cl, serializer); } return serializer; } /** * Returns the default serializer for a class that isn't matched * directly. Application can override this method to produce * bean-style serialization instead of field serialization. * * @param cl the class of the object that needs to be serialized. * * @return a serializer object for the serialization. */ protected Serializer getDefaultSerializer(Class cl) { if (_defaultSerializer != null) return _defaultSerializer; if (! Serializable.class.isAssignableFrom(cl) && ! _isAllowNonSerializable) { throw new IllegalStateException("Serialized class " + cl.getName() + " must implement java.io.Serializable"); } return new JavaSerializer(cl); } /** * Returns the deserializer for a class. * * @param cl the class of the object that needs to be deserialized. * * @return a deserializer object for the serialization. */ public Deserializer getDeserializer(Class cl) throws HessianProtocolException { Deserializer deserializer; deserializer = (Deserializer) _staticDeserializerMap.get(cl); if (deserializer != null) return deserializer; if (_cachedDeserializerMap != null) { synchronized (_cachedDeserializerMap) { deserializer = (Deserializer) _cachedDeserializerMap.get(cl); } if (deserializer != null) return deserializer; } for (int i = 0; deserializer == null && _factories != null && i < _factories.size(); i++) { AbstractSerializerFactory factory; factory = (AbstractSerializerFactory) _factories.get(i); deserializer = factory.getDeserializer(cl); } if (deserializer != null) { } else if (Collection.class.isAssignableFrom(cl)) deserializer = new CollectionDeserializer(cl); else if (Map.class.isAssignableFrom(cl)) deserializer = new MapDeserializer(cl); else if (cl.isInterface()) deserializer = new ObjectDeserializer(cl); else if (cl.isArray()) deserializer = new ArrayDeserializer(cl.getComponentType()); else if (Enumeration.class.isAssignableFrom(cl)) deserializer = EnumerationDeserializer.create(); else if (Enum.class.isAssignableFrom(cl)) deserializer = new EnumDeserializer(cl); else deserializer = getDefaultDeserializer(cl); if (_cachedDeserializerMap == null) _cachedDeserializerMap = new HashMap(8); synchronized (_cachedDeserializerMap) { _cachedDeserializerMap.put(cl, deserializer); } return deserializer; } /** * Returns the default serializer for a class that isn't matched * directly. Application can override this method to produce * bean-style serialization instead of field serialization. * * @param cl the class of the object that needs to be serialized. * * @return a serializer object for the serialization. */ protected Deserializer getDefaultDeserializer(Class cl) { return new JavaDeserializer(cl); } /** * Reads the object as a list. */ public Object readList(AbstractHessianInput in, int length, String type) throws HessianProtocolException, IOException { Deserializer deserializer = getDeserializer(type); if (deserializer != null) return deserializer.readList(in, length); else return new CollectionDeserializer(ArrayList.class).readList(in, length); } /** * Reads the object as a map. */ public Object readMap(AbstractHessianInput in, String type) throws HessianProtocolException, IOException { Deserializer deserializer = getDeserializer(type); if (deserializer != null) return deserializer.readMap(in); else if (_hashMapDeserializer != null) return _hashMapDeserializer.readMap(in); else { _hashMapDeserializer = new MapDeserializer(HashMap.class); return _hashMapDeserializer.readMap(in); } } /** * Reads the object as a map. */ public Object readObject(AbstractHessianInput in, String type, String []fieldNames) throws HessianProtocolException, IOException { Deserializer deserializer = getDeserializer(type); if (deserializer != null) return deserializer.readObject(in, fieldNames); else if (_hashMapDeserializer != null) return _hashMapDeserializer.readObject(in, fieldNames); else { _hashMapDeserializer = new MapDeserializer(HashMap.class); return _hashMapDeserializer.readObject(in, fieldNames); } } /** * Reads the object as a map. */ public Deserializer getObjectDeserializer(String type, Class cl) throws HessianProtocolException { Deserializer reader = getObjectDeserializer(type); if (cl == null || cl.equals(reader.getType()) || cl.isAssignableFrom(reader.getType()) || HessianHandle.class.isAssignableFrom(reader.getType())) { return reader; } if (log.isLoggable(Level.FINE)) { log.fine("hessian: expected '" + cl.getName() + "' at '" + type + "' (" + reader.getType().getName() + ")"); } return getDeserializer(cl); } /** * Reads the object as a map. */ public Deserializer getObjectDeserializer(String type) throws HessianProtocolException { Deserializer deserializer = getDeserializer(type); if (deserializer != null) return deserializer; else if (_hashMapDeserializer != null) return _hashMapDeserializer; else { _hashMapDeserializer = new MapDeserializer(HashMap.class); return _hashMapDeserializer; } } /** * Reads the object as a map. */ public Deserializer getListDeserializer(String type, Class cl) throws HessianProtocolException { Deserializer reader = getListDeserializer(type); if (cl == null || cl.equals(reader.getType()) || cl.isAssignableFrom(reader.getType())) { return reader; } if (log.isLoggable(Level.FINE)) { log.fine("hessian: expected '" + cl.getName() + "' at '" + type + "' (" + reader.getType().getName() + ")"); } return getDeserializer(cl); } /** * Reads the object as a map. */ public Deserializer getListDeserializer(String type) throws HessianProtocolException { Deserializer deserializer = getDeserializer(type); if (deserializer != null) return deserializer; else if (_arrayListDeserializer != null) return _arrayListDeserializer; else { _arrayListDeserializer = new CollectionDeserializer(ArrayList.class); return _arrayListDeserializer; } } /** * Returns a deserializer based on a string type. */ public Deserializer getDeserializer(String type) throws HessianProtocolException { if (type == null || type.equals("")) return null; Deserializer deserializer; if (_cachedTypeDeserializerMap != null) { synchronized (_cachedTypeDeserializerMap) { deserializer = (Deserializer) _cachedTypeDeserializerMap.get(type); } if (deserializer != null) return deserializer; } deserializer = (Deserializer) _staticTypeMap.get(type); if (deserializer != null) return deserializer; if (type.startsWith("[")) { Deserializer subDeserializer = getDeserializer(type.substring(1)); if (subDeserializer != null) deserializer = new ArrayDeserializer(subDeserializer.getType()); else deserializer = new ArrayDeserializer(Object.class); } else { try { Class cl = Class.forName(type, false, getClass().getClassLoader()); deserializer = getDeserializer(cl); } catch (Exception e) { log.warning("Hessian/Burlap: '" + type + "' is an unknown class in " + getClass().getClassLoader() + ":\n" + e); log.log(Level.FINER, e.toString(), e); } } if (deserializer != null) { if (_cachedTypeDeserializerMap == null) _cachedTypeDeserializerMap = new HashMap(8); synchronized (_cachedTypeDeserializerMap) { _cachedTypeDeserializerMap.put(type, deserializer); } } return deserializer; } private static void addBasic(Class cl, String typeName, int type) { _staticSerializerMap.put(cl, new BasicSerializer(type)); Deserializer deserializer = new BasicDeserializer(type); _staticDeserializerMap.put(cl, deserializer); _staticTypeMap.put(typeName, deserializer); } static { _staticSerializerMap = new HashMap(); _staticDeserializerMap = new HashMap(); _staticTypeMap = new HashMap(); addBasic(void.class, "void", BasicSerializer.NULL); addBasic(Boolean.class, "boolean", BasicSerializer.BOOLEAN); addBasic(Byte.class, "byte", BasicSerializer.BYTE); addBasic(Short.class, "short", BasicSerializer.SHORT); addBasic(Integer.class, "int", BasicSerializer.INTEGER); addBasic(Long.class, "long", BasicSerializer.LONG); addBasic(Float.class, "float", BasicSerializer.FLOAT); addBasic(Double.class, "double", BasicSerializer.DOUBLE); addBasic(Character.class, "char", BasicSerializer.CHARACTER_OBJECT); addBasic(String.class, "string", BasicSerializer.STRING); addBasic(Object.class, "object", BasicSerializer.OBJECT); addBasic(java.util.Date.class, "date", BasicSerializer.DATE); addBasic(boolean.class, "boolean", BasicSerializer.BOOLEAN); addBasic(byte.class, "byte", BasicSerializer.BYTE); addBasic(short.class, "short", BasicSerializer.SHORT); addBasic(int.class, "int", BasicSerializer.INTEGER); addBasic(long.class, "long", BasicSerializer.LONG); addBasic(float.class, "float", BasicSerializer.FLOAT); addBasic(double.class, "double", BasicSerializer.DOUBLE); addBasic(char.class, "char", BasicSerializer.CHARACTER); addBasic(boolean[].class, "[boolean", BasicSerializer.BOOLEAN_ARRAY); addBasic(byte[].class, "[byte", BasicSerializer.BYTE_ARRAY); addBasic(short[].class, "[short", BasicSerializer.SHORT_ARRAY); addBasic(int[].class, "[int", BasicSerializer.INTEGER_ARRAY); addBasic(long[].class, "[long", BasicSerializer.LONG_ARRAY); addBasic(float[].class, "[float", BasicSerializer.FLOAT_ARRAY); addBasic(double[].class, "[double", BasicSerializer.DOUBLE_ARRAY); addBasic(char[].class, "[char", BasicSerializer.CHARACTER_ARRAY); addBasic(String[].class, "[string", BasicSerializer.STRING_ARRAY); addBasic(Object[].class, "[object", BasicSerializer.OBJECT_ARRAY); _staticSerializerMap.put(Class.class, new ClassSerializer()); _staticDeserializerMap.put(Class.class, new ClassDeserializer()); _staticDeserializerMap.put(Number.class, new BasicDeserializer(BasicSerializer.NUMBER)); _staticSerializerMap.put(BigDecimal.class, new StringValueSerializer()); try { _staticDeserializerMap.put(BigDecimal.class, new StringValueDeserializer(BigDecimal.class)); } catch (Throwable e) { } _staticSerializerMap.put(File.class, new StringValueSerializer()); try { _staticDeserializerMap.put(File.class, new StringValueDeserializer(File.class)); } catch (Throwable e) { } // _staticSerializerMap.put(ObjectName.class, new StringValueSerializer()); // try { // _staticDeserializerMap.put(ObjectName.class, // new StringValueDeserializer(ObjectName.class)); // } catch (Throwable e) { // } _staticSerializerMap.put(java.sql.Date.class, new SqlDateSerializer()); _staticSerializerMap.put(java.sql.Time.class, new SqlDateSerializer()); _staticSerializerMap.put(java.sql.Timestamp.class, new SqlDateSerializer()); _staticSerializerMap.put(java.io.InputStream.class, new InputStreamSerializer()); _staticDeserializerMap.put(java.io.InputStream.class, new InputStreamDeserializer()); try { _staticDeserializerMap.put(java.sql.Date.class, new SqlDateDeserializer(java.sql.Date.class)); _staticDeserializerMap.put(java.sql.Time.class, new SqlDateDeserializer(java.sql.Time.class)); _staticDeserializerMap.put(java.sql.Timestamp.class, new SqlDateDeserializer(java.sql.Timestamp.class)); } catch (Throwable e) { e.printStackTrace(); } // hessian/3bb5 try { Class stackTrace = Class.forName("java.lang.StackTraceElement"); _staticDeserializerMap.put(stackTrace, new StackTraceElementDeserializer()); } catch (Throwable e) { } } }
zzgfly-hessdroid
src/com/caucho/hessian/io/SerializerFactory.java
Java
asf20
19,314
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Burlap", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; /** * Deserializing an object. */ abstract public class AbstractDeserializer implements Deserializer { public Class getType() { return Object.class; } public Object readObject(AbstractHessianInput in) throws IOException { Object obj = in.readObject(); String className = getClass().getName(); if (obj != null) throw error(className + ": unexpected object " + obj.getClass().getName() + " (" + obj + ")"); else throw error(className + ": unexpected null value"); } public Object readList(AbstractHessianInput in, int length) throws IOException { throw new UnsupportedOperationException(String.valueOf(this)); } public Object readLengthList(AbstractHessianInput in, int length) throws IOException { throw new UnsupportedOperationException(String.valueOf(this)); } public Object readMap(AbstractHessianInput in) throws IOException { Object obj = in.readObject(); String className = getClass().getName(); if (obj != null) throw error(className + ": unexpected object " + obj.getClass().getName() + " (" + obj + ")"); else throw error(className + ": unexpected null value"); } public Object readObject(AbstractHessianInput in, String []fieldNames) throws IOException { throw new UnsupportedOperationException(String.valueOf(this)); } protected HessianProtocolException error(String msg) { return new HessianProtocolException(msg); } protected String codeName(int ch) { if (ch < 0) return "end of file"; else return "0x" + Integer.toHexString(ch & 0xff); } }
zzgfly-hessdroid
src/com/caucho/hessian/io/AbstractDeserializer.java
Java
asf20
3,934
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Burlap", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; /** * Deserializing an object. */ public interface Deserializer { public Class getType(); public Object readObject(AbstractHessianInput in) throws IOException; public Object readList(AbstractHessianInput in, int length) throws IOException; public Object readLengthList(AbstractHessianInput in, int length) throws IOException; public Object readMap(AbstractHessianInput in) throws IOException; public Object readObject(AbstractHessianInput in, String []fieldNames) throws IOException; }
zzgfly-hessdroid
src/com/caucho/hessian/io/Deserializer.java
Java
asf20
2,829
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * 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. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.util.*; import java.util.zip.*; import java.io.*; import com.caucho.hessian.io.*; public class Deflation extends HessianEnvelope { public Deflation() { } public Hessian2Output wrap(Hessian2Output out) throws IOException { OutputStream os = new DeflateOutputStream(out); Hessian2Output filterOut = new Hessian2Output(os); filterOut.setCloseStreamOnClose(true); return filterOut; } public Hessian2Input unwrap(Hessian2Input in) throws IOException { int version = in.readEnvelope(); String method = in.readMethod(); if (! method.equals(getClass().getName())) throw new IOException("expected hessian Envelope method '" + getClass().getName() + "' at '" + method + "'"); return unwrapHeaders(in); } public Hessian2Input unwrapHeaders(Hessian2Input in) throws IOException { InputStream is = new DeflateInputStream(in); Hessian2Input filter = new Hessian2Input(is); filter.setCloseStreamOnClose(true); return filter; } static class DeflateOutputStream extends OutputStream { private Hessian2Output _out; private OutputStream _bodyOut; private DeflaterOutputStream _deflateOut; DeflateOutputStream(Hessian2Output out) throws IOException { _out = out; _out.startEnvelope(Deflation.class.getName()); _out.writeInt(0); _bodyOut = _out.getBytesOutputStream(); _deflateOut = new DeflaterOutputStream(_bodyOut); } public void write(int ch) throws IOException { _deflateOut.write(ch); } public void write(byte []buffer, int offset, int length) throws IOException { _deflateOut.write(buffer, offset, length); } public void close() throws IOException { Hessian2Output out = _out; _out = null; if (out != null) { _deflateOut.close(); _bodyOut.close(); out.writeInt(0); out.completeEnvelope(); out.close(); } } } static class DeflateInputStream extends InputStream { private Hessian2Input _in; private InputStream _bodyIn; private InflaterInputStream _inflateIn; DeflateInputStream(Hessian2Input in) throws IOException { _in = in; int len = in.readInt(); if (len != 0) throw new IOException("expected no headers"); _bodyIn = _in.readInputStream(); _inflateIn = new InflaterInputStream(_bodyIn); } public int read() throws IOException { return _inflateIn.read(); } public int read(byte []buffer, int offset, int length) throws IOException { return _inflateIn.read(buffer, offset, length); } public void close() throws IOException { Hessian2Input in = _in; _in = null; if (in != null) { _inflateIn.close(); _bodyIn.close(); int len = in.readInt(); if (len != 0) throw new IOException("Unexpected footer"); in.completeEnvelope(); in.close(); } } } }
zzgfly-hessdroid
src/com/caucho/hessian/io/Deflation.java
Java
asf20
5,363