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 (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.ComponentModel; namespace Lokad.Cloud.Storage.Shared.Policies { /// <summary> /// Helper class for creating fluent APIs, that hides unused signatures. /// </summary> public abstract class Syntax { /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> [EditorBrowsable(EditorBrowsableState.Never)] public override string ToString() { return base.ToString(); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { return base.Equals(obj); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Creates the syntax for the specified target /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="inner">The inner.</param> /// <returns>new syntax instance</returns> public static Syntax<TTarget> For<TTarget>(TTarget inner) { return new Syntax<TTarget>(inner); } } /// <summary> /// Helper class for creating fluent APIs, that hides unused signatures. /// </summary> public sealed class Syntax<TTarget> : Syntax { readonly TTarget _inner; /// <summary> /// Initializes a new instance of the <see cref="Syntax{T}"/> class. /// </summary> /// <param name="inner">The underlying instance.</param> public Syntax(TTarget inner) { _inner = inner; } /// <summary> /// Gets the underlying object. /// </summary> /// <value>The underlying object.</value> [EditorBrowsable(EditorBrowsableState.Advanced)] public TTarget Target { get { return _inner; } } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Policies/Syntax.cs
C#
bsd
3,288
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared.Policies { /// <summary> This delegate represents <em>catch</em> block.</summary> /// <param name="ex">Exception to handle.</param> /// <returns><em>true</em> if we can handle exception.</returns> public delegate bool ExceptionHandler(Exception ex); }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Policies/ExceptionHandler.cs
C#
bsd
491
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared.Policies { sealed class RetryStateWithCount : IRetryState { int _errorCount; readonly Action<Exception, int> _onRetry; readonly Predicate<int> _canRetry; public RetryStateWithCount(int retryCount, Action<Exception, int> onRetry) { _onRetry = onRetry; _canRetry = i => _errorCount <= retryCount; } public bool CanRetry(Exception ex) { _errorCount += 1; bool result = _canRetry(_errorCount); if (result) { _onRetry(ex, _errorCount - 1); } return result; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Policies/RetryStateWithCount.cs
C#
bsd
900
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared.Policies { sealed class RetryState : IRetryState { readonly Action<Exception> _onRetry; public RetryState(Action<Exception> onRetry) { _onRetry = onRetry; } bool IRetryState.CanRetry(Exception ex) { _onRetry(ex); return true; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Policies/RetryState.cs
C#
bsd
572
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.IO; namespace Lokad.Cloud.Storage.Shared { /// <summary> /// Generic data serializer interface. /// </summary> public interface IDataSerializer { /// <summary>Serializes the object to the specified stream.</summary> /// <param name="instance">The instance.</param> /// <param name="destinationStream">The destination stream.</param> void Serialize(object instance, Stream destinationStream); /// <summary>Deserializes the object from specified source stream.</summary> /// <param name="sourceStream">The source stream.</param> /// <param name="type">The type of the object to deserialize.</param> /// <returns>deserialized object</returns> object Deserialize(Stream sourceStream, Type type); } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/IDataSerializer.cs
C#
bsd
1,011
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Diagnostics; using System.Linq; using System.Threading; namespace Lokad.Cloud.Storage.Shared.Diagnostics { /// <summary> <para> /// Class to provide simple measurement of some method calls. /// This class has been designed to provide light performance monitoring /// that could be used for instrumenting methods in production. It does /// not use any locks and uses design to avoid 90% of concurrency issues. /// </para><para> /// Counters are designed to be "cheap" and throwaway, so we basically we /// don't care about the remaining 10% /// </para><para> /// The usage idea is simple - data is captured from the counters at /// regular intervals of time (i.e. 5-10 minutes). Counters are reset /// after that. Data itself is aggregated on the monitoring side. /// If there are some bad values (i.e. due to some rare race condition /// between multiple threads and monitoring scan) then the counter data /// is simply discarded. /// </para></summary> public sealed class ExecutionCounter { long _openCount; long _closeCount; long _runningTime; readonly long[] _openCounters; readonly long[] _closeCounters; readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="ExecutionCounter"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="openCounterCount">The open counter count.</param> /// <param name="closeCounterCount">The close counter count.</param> public ExecutionCounter(string name, int openCounterCount, int closeCounterCount) { _name = name; _openCounters = new long[openCounterCount]; _closeCounters = new long[closeCounterCount]; } /// <summary> /// Open the specified counter and adds the provided values to the openCounters collection /// </summary> /// <param name="openCounters">The open counters.</param> /// <returns>timestamp for the operation</returns> public long Open(params long[] openCounters) { // abdullin: this is not really atomic and precise, // but we do not care that much unchecked { Interlocked.Increment(ref _openCount); for (int i = 0; i < openCounters.Length; i++) { Interlocked.Add(ref _openCounters[i], openCounters[i]); } } return Stopwatch.GetTimestamp(); } /// <summary> /// Closes the specified timestamp. /// </summary> /// <param name="timestamp">The timestamp.</param> /// <param name="closeCounters">The close counters.</param> public void Close(long timestamp, params long[] closeCounters) { var runningTime = Stopwatch.GetTimestamp() - timestamp; // this counter has been reset after opening - discard if ((_openCount == 0) || (runningTime < 0)) return; // abdullin: this is not really atomic and precise, // but we do not care that much unchecked { Interlocked.Add(ref _runningTime, runningTime); Interlocked.Increment(ref _closeCount); for (int i = 0; i < closeCounters.Length; i++) { Interlocked.Add(ref _closeCounters[i], closeCounters[i]); } } } /// <summary> /// Resets this instance. /// </summary> public void Reset() { _runningTime = 0; _openCount = 0; _closeCount = 0; for (int i = 0; i < _closeCounters.Length; i++) { _closeCounters[i] = 0; } for (int i = 0; i < _openCounters.Length; i++) { _openCounters[i] = 0; } } /// <summary> /// Converts this instance to <see cref="ExecutionStatistics"/> /// </summary> /// <returns></returns> public ExecutionStatistics ToStatistics() { long dateTimeTicks = _runningTime; if (Stopwatch.IsHighResolution) { double num2 = dateTimeTicks; num2 *= 10000000.0 / Stopwatch.Frequency; dateTimeTicks = (long)num2; } return new ExecutionStatistics( _name, _openCount, _closeCount, _openCounters.Concat(_closeCounters).ToArray(), dateTimeTicks); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Diagnostics/ExecutionCounter.cs
C#
bsd
5,095
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.Serialization; using System.Xml.Serialization; // CAUTION: do not touch namespace as it would be likely to break the persistence of this entity. namespace Lokad.Diagnostics.Persist { /// <summary> /// Diagnostics: Persistence class for aggregated method calls and timing. /// </summary> [Serializable] [DataContract] [DebuggerDisplay("{Name}: {OpenCount}, {RunningTime}")] public sealed class ExecutionData { /// <summary> /// Name of the executing method /// </summary> [XmlAttribute] [DataMember(Order = 1)] public string Name { get; set; } /// <summary> /// Number of times the counter has been opened /// </summary> [XmlAttribute, DefaultValue(0)] [DataMember(Order = 2)] public long OpenCount { get; set; } /// <summary> /// Gets or sets the counter has been closed /// </summary> /// <value>The close count.</value> [XmlAttribute, DefaultValue(0)] [DataMember(Order = 3)] public long CloseCount { get; set; } /// <summary> /// Total execution count of the method in ticks /// </summary> [XmlAttribute, DefaultValue(0)] [DataMember(Order = 4)] public long RunningTime { get; set; } /// <summary> /// Method-specific counters /// </summary> [DataMember(Order = 5)] public long[] Counters { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ExecutionData"/> class. /// </summary> public ExecutionData() { Counters = new long[0]; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Diagnostics/Persistence/ExecutionData.cs
C#
bsd
2,016
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.Linq; using Lokad.Cloud.Storage.Shared.Diagnostics; namespace Lokad.Diagnostics.Persist { /// <summary> /// Helper extensions for converting to/from data classes in the Diagnostics namespace /// </summary> public static class ConversionExtensions { /// <summary> /// Converts immutable statistics objects to the persistence objects /// </summary> /// <param name="statisticsArray">The immutable statistics objects.</param> /// <returns>array of persistence objects</returns> public static ExecutionData[] ToPersistence(this ExecutionStatistics[] statisticsArray) { return statisticsArray.Select(es => new ExecutionData { CloseCount = es.CloseCount, Counters = es.Counters, Name = es.Name, OpenCount = es.OpenCount, RunningTime = es.RunningTime }).ToArray(); } /// <summary> /// Converts persistence objects to immutable statistics objects /// </summary> /// <param name="dataArray">The persistence data objects.</param> /// <returns>array of statistics objects</returns> public static ExecutionStatistics[] FromPersistence(this ExecutionData[] dataArray) { return dataArray.Select( d => new ExecutionStatistics( d.Name, d.OpenCount, d.CloseCount, d.Counters, d.RunningTime)).ToArray(); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Diagnostics/Persistence/ConvertionExtensions.cs
C#
bsd
1,807
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lokad.Cloud.Storage.Shared.Diagnostics { /// <summary> /// In-memory thread-safe collection of <see cref="ExecutionCounter"/> /// </summary> public sealed class ExecutionCounters { /// <summary> /// Default instance of this counter /// </summary> public static readonly ExecutionCounters Default = new ExecutionCounters(); readonly object _lock = new object(); readonly IList<ExecutionCounter> _counters = new List<ExecutionCounter>(); /// <summary> /// Registers the execution counters within this collection. /// </summary> /// <param name="counters">The counters.</param> public void RegisterRange(IEnumerable<ExecutionCounter> counters) { lock (_lock) { foreach(var c in counters) { _counters.Add(c); } } } /// <summary> /// Retrieves statistics for all exception counters in this collection /// </summary> /// <returns></returns> public IList<ExecutionStatistics> ToList() { lock (_lock) { return _counters.Select(c => c.ToStatistics()).ToList(); } } /// <summary> /// Resets all counters. /// </summary> public void ResetAll() { lock (_lock) { foreach (var counter in _counters) { counter.Reset(); } } } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Diagnostics/ExceptionCounters.cs
C#
bsd
1,929
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared.Diagnostics { /// <summary> /// Statistics about some execution counter /// </summary> [Serializable] public sealed class ExecutionStatistics { readonly long _openCount; readonly long _closeCount; readonly long[] _counters; readonly long _runningTime; readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="ExecutionStatistics"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="openCount">The open count.</param> /// <param name="closeCount">The close count.</param> /// <param name="counters">The counters.</param> /// <param name="runningTime">The running time.</param> public ExecutionStatistics(string name, long openCount, long closeCount, long[] counters, long runningTime) { _openCount = openCount; _closeCount = closeCount; _counters = counters; _runningTime = runningTime; _name = name; } /// <summary> /// Gets the number of times the counter has been opened /// </summary> /// <value>The open count.</value> public long OpenCount { get { return _openCount; } } /// <summary> /// Gets the number of times the counter has been properly closed. /// </summary> /// <value>The close count.</value> public long CloseCount { get { return _closeCount; } } /// <summary> /// Gets the native counters collected by this counter. /// </summary> /// <value>The counters.</value> public long[] Counters { get { return _counters; } } /// <summary> /// Gets the total running time between open and close statements in ticks. /// </summary> /// <value>The running time expressed in 100-nanosecond units.</value> public long RunningTime { get { return _runningTime; } } /// <summary> /// Gets the name for this counter. /// </summary> /// <value>The name.</value> public string Name { get { return _name; } } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Diagnostics/ExecutionStatistics.cs
C#
bsd
2,622
#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; namespace Lokad.Cloud.Storage { /// <summary>Abstraction for the Table Storage.</summary> /// <remarks>This provider represents a logical abstraction of the Table Storage, /// not the Table Storage itself. In particular, implementations handle paging /// and query splitting internally. Also, this provider implicitly relies on /// serialization to handle generic entities (not constrained by the few datatypes /// available to the Table Storage).</remarks> public interface ITableStorageProvider { /// <summary>Creates a new table if it does not exist already.</summary> /// <returns><c>true</c> if a new table has been created. /// <c>false</c> if the table already exists. /// </returns> bool CreateTable(string tableName); /// <summary>Deletes a table if it exists.</summary> /// <returns><c>true</c> if the table has been deleted. /// <c>false</c> if the table does not exist. /// </returns> bool DeleteTable(string tableName); /// <summary>Returns the list of all the tables that exist in the storage.</summary> IEnumerable<string> GetTables(); /// <summary>Iterates through all entities of a given table.</summary> /// <remarks>The enumeration is typically expected to be lazy, iterating through /// all the entities with paged request. If the table does not exist, an /// empty enumeration is returned. /// </remarks> IEnumerable<CloudEntity<T>> Get<T>(string tableName); /// <summary>Iterates through all entities of a given table and partition.</summary> /// <remarks><para>The enumeration is typically expected to be lazy, iterating through /// all the entities with paged request. If the table does not exists, or if the partition /// does not exists, an empty enumeration is returned.</para> /// </remarks> IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey); /// <summary>Iterates through a range of entities of a given table and partition.</summary> /// <param name="tableName">Name of the Table.</param> /// <param name="partitionKey">Name of the partition which can not be null.</param> /// <param name="startRowKey">Inclusive start row key. If <c>null</c>, no start range /// constraint is enforced.</param> /// <param name="endRowKey">Exclusive end row key. If <c>null</c>, no ending range /// constraint is enforced.</param> /// <remarks> /// The enumeration is typically expected to be lazy, iterating through /// all the entities with paged request.The enumeration is ordered by row key. /// If the table or the partition key does not exist, the returned enumeration is empty. /// </remarks> IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, string startRowKey, string endRowKey); /// <summary>Iterates through all entities specified by their row keys.</summary> /// <param name="tableName">The name of the table. This table should exists otherwise the method will fail.</param> /// <param name="partitionKey">Partition key (can not be null).</param> /// <param name="rowKeys">lazy enumeration of non null string representing rowKeys.</param> /// <remarks>The enumeration is typically expected to be lazy, iterating through /// all the entities with paged request. If the table or the partition key does not exist, /// the returned enumeration is empty.</remarks> IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys); /// <summary>Inserts a collection of new entities into the table storage.</summary> /// <remarks> /// <para>The call is expected to fail on the first encountered already-existing /// entity. Results are not garanteed if one or several entities already exist. /// </para> /// <para>There is no upper limit on the number of entities provided through /// the enumeration. The implementations are expected to lazily iterates /// and to create batch requests as the move forward. /// </para> /// <para>If the table does not exist then it should be created.</para> /// <warning>Idempotence is not enforced.</warning> /// </remarks> ///<exception cref="InvalidOperationException"> if an already existing entity has been encountered.</exception> void Insert<T>(string tableName, IEnumerable<CloudEntity<T>> entities); /// <summary>Updates a collection of existing entities into the table storage.</summary> /// <remarks> /// <para>The call is expected to fail on the first non-existing entity. /// Results are not garanteed if one or several entities do not exist already. /// </para> /// <para>If <paramref name="force"/> is <c>false</c>, the call is expected to /// fail if one or several entities have changed in the meantime. If <c>true</c>, /// the entities are overwritten even if they've been changed remotely in the meantime. /// </para> /// <para>There is no upper limit on the number of entities provided through /// the enumeration. The implementations are expected to lazily iterates /// and to create batch requests as the move forward. /// </para> /// <para>Idempotence of the implementation is required.</para> /// </remarks> /// <exception cref="InvalidOperationException"> thrown if the table does not exist /// or an non-existing entity has been encountered.</exception> void Update<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force); /// <summary>Updates or insert a collection of existing entities into the table storage.</summary> /// <remarks> /// <para>New entities will be inserted. Existing entities will be updated, /// even if they have changed remotely in the meantime. /// </para> /// <para>There is no upper limit on the number of entities provided through /// the enumeration. The implementations are expected to lazily iterates /// and to create batch requests as the move forward. /// </para> /// <para>If the table does not exist then it should be created.</para> /// <para>Idempotence of the implementation is required.</para> /// </remarks> void Upsert<T>(string tableName, IEnumerable<CloudEntity<T>> entities); /// <summary>Deletes all specified entities.</summary> /// <param name="tableName">Name of the table.</param> /// <param name="partitionKey">The partition key (assumed to be non null).</param> /// <param name="rowKeys">Lazy enumeration of non null string representing the row keys.</param> /// <remarks> /// <para> /// The implementation is expected to lazily iterate through all row keys /// and send batch deletion request to the underlying storage.</para> /// <para>Idempotence of the method is required.</para> /// <para>The method should not fail if the table does not exist.</para> /// </remarks> void Delete<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys); /// <summary>Deletes a collection of entities.</summary> /// <remarks> /// <para> /// The implementation is expected to lazily iterate through all row keys /// and send batch deletion request to the underlying storage.</para> /// <para>Idempotence of the method is required.</para> /// <para>The method should not fail if the table does not exist.</para> /// <para>If <paramref name="force"/> is <c>false</c>, the call is expected to /// fail if one or several entities have changed remotely in the meantime. If <c>true</c>, /// the entities are deleted even if they've been changed remotely in the meantime. /// </para> /// </remarks> void Delete<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force); } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Tables/ITableStorageProvider.cs
C#
bsd
8,612
#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.Collections.Generic; using System.Linq; // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMethodReturnValue.Global namespace Lokad.Cloud.Storage { /// <summary>Helper extensions methods for storage providers.</summary> public static class TableStorageExtensions { /// <summary>Gets the specified cloud entity if it exists.</summary> /// <typeparam name="T"></typeparam> public static Maybe<CloudEntity<T>> Get<T>(this ITableStorageProvider provider, string tableName, string partitionName, string rowKey) { var entity = provider.Get<T>(tableName, partitionName, new[] {rowKey}).FirstOrDefault(); return null != entity ? new Maybe<CloudEntity<T>>(entity) : Maybe<CloudEntity<T>>.Empty; } /// <summary>Gets a strong typed wrapper around the table storage provider.</summary> public static CloudTable<T> GetTable<T>(this ITableStorageProvider provider, string tableName) { return new CloudTable<T>(provider, tableName); } /// <summary>Updates a collection of existing entities into the table storage.</summary> /// <remarks> /// <para>The call is expected to fail on the first non-existing entity. /// Results are not garanteed if one or several entities do not exist already. /// </para> /// <para>The call is also expected to fail if one or several entities have /// changed remotely in the meantime. Use the overloaded method with the additional /// force parameter to change this behavior if needed. /// </para> /// <para>There is no upper limit on the number of entities provided through /// the enumeration. The implementations are expected to lazily iterates /// and to create batch requests as the move forward. /// </para> /// <para>Idempotence of the implementation is required.</para> /// </remarks> /// <exception cref="InvalidOperationException"> thrown if the table does not exist /// or an non-existing entity has been encountered.</exception> public static void Update<T>(this ITableStorageProvider provider, string tableName, IEnumerable<CloudEntity<T>> entities) { provider.Update(tableName, entities, false); } /// <summary>Deletes a collection of entities.</summary> /// <remarks> /// <para> /// The implementation is expected to lazily iterate through all row keys /// and send batch deletion request to the underlying storage.</para> /// <para>Idempotence of the method is required.</para> /// <para>The method should not fail if the table does not exist.</para> /// <para>The call is expected to fail if one or several entities have /// changed remotely in the meantime. Use the overloaded method with the additional /// force parameter to change this behavior if needed. /// </para> /// </remarks> public static void Delete<T>(this ITableStorageProvider provider, string tableName, IEnumerable<CloudEntity<T>> entities) { provider.Delete(tableName, entities, false); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Tables/TableStorageExtensions.cs
C#
bsd
3,493
#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; namespace Lokad.Cloud.Storage { /// <summary>Entity to be stored by the <see cref="ITableStorageProvider"/>.</summary> /// <typeparam name="T">Type of the value carried by the entity.</typeparam> /// <remarks>Once serialized the <c>CloudEntity.Value</c> should weight less /// than 720KB to be compatible with Table Storage limitations on entities.</remarks> public class CloudEntity<T> { /// <summary>Indexed system property.</summary> public string RowKey { get; set; } /// <summary>Indexed system property.</summary> public string PartitionKey { get; set; } /// <summary>Flag indicating last update. Populated by the Table Storage.</summary> public DateTime Timestamp { get; set; } /// <summary>ETag. Indicates changes. Populated by the Table Storage.</summary> public string ETag { get; set; } /// <summary>Value carried by the entity.</summary> public T Value { get; set; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Tables/CloudEntity.cs
C#
bsd
1,182
#region Copyright (c) Lokad 2010-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 System.Text.RegularExpressions; namespace Lokad.Cloud.Storage { /// <summary>Strong-typed utility wrapper for the <see cref="ITableStorageProvider"/>.</summary> /// <remarks> /// The purpose of the <c>CloudTable{T}</c> is to provide a strong-typed access to the /// table storage in the client code. Indeed, the row table storage provider typically /// let you (potentially) mix different types into a single table. /// </remarks> public class CloudTable<T> { readonly ITableStorageProvider _provider; readonly string _tableName; /// <summary>Name of the underlying table.</summary> public string Name { get { return _tableName; } } /// <remarks></remarks> public CloudTable(ITableStorageProvider provider, string tableName) { // validating against the Windows Azure rule for table names. if (!Regex.Match(tableName, "^[A-Za-z][A-Za-z0-9]{2,62}").Success) { throw new ArgumentException("Table name is incorrect", "tableName"); } _provider = provider; _tableName = tableName; } /// <seealso cref="ITableStorageProvider.Get{T}(string, string)"/> public Maybe<CloudEntity<T>> Get(string partitionName, string rowKey) { var entity = _provider.Get<T>(_tableName, partitionName, new[] {rowKey}).FirstOrDefault(); return null != entity ? new Maybe<CloudEntity<T>>(entity) : Maybe<CloudEntity<T>>.Empty; } /// <seealso cref="ITableStorageProvider.Get{T}(string)"/> public IEnumerable<CloudEntity<T>> Get() { return _provider.Get<T>(_tableName); } /// <seealso cref="ITableStorageProvider.Get{T}(string, string)"/> public IEnumerable<CloudEntity<T>> Get(string partitionKey) { return _provider.Get<T>(_tableName, partitionKey); } /// <seealso cref="ITableStorageProvider.Get{T}(string, string, string, string)"/> public IEnumerable<CloudEntity<T>> Get(string partitionKey, string startRowKey, string endRowKey) { return _provider.Get<T>(_tableName, partitionKey, startRowKey, endRowKey); } /// <seealso cref="ITableStorageProvider.Get{T}(string, string, IEnumerable{string})"/> public IEnumerable<CloudEntity<T>> Get(string partitionKey, IEnumerable<string> rowKeys) { return _provider.Get<T>(_tableName, partitionKey, rowKeys); } /// <seealso cref="ITableStorageProvider.Insert{T}(string, IEnumerable{CloudEntity{T}})"/> public void Insert(IEnumerable<CloudEntity<T>> entities) { _provider.Insert(_tableName, entities); } /// <seealso cref="ITableStorageProvider.Insert{T}(string, IEnumerable{CloudEntity{T}})"/> public void Insert(CloudEntity<T> entity) { _provider.Insert(_tableName, new []{entity}); } /// <seealso cref="ITableStorageProvider.Update{T}(string, IEnumerable{CloudEntity{T}})"/> public void Update(IEnumerable<CloudEntity<T>> entities) { _provider.Update(_tableName, entities); } /// <seealso cref="ITableStorageProvider.Update{T}(string, IEnumerable{CloudEntity{T}})"/> public void Update(CloudEntity<T> entity) { _provider.Update(_tableName, new [] {entity}); } /// <seealso cref="ITableStorageProvider.Upsert{T}(string, IEnumerable{CloudEntity{T}})"/> public void Upsert(IEnumerable<CloudEntity<T>> entities) { _provider.Upsert(_tableName, entities); } /// <seealso cref="ITableStorageProvider.Upsert{T}(string, IEnumerable{CloudEntity{T}})"/> public void Upsert(CloudEntity<T> entity) { _provider.Upsert(_tableName, new [] {entity}); } /// <seealso cref="ITableStorageProvider.Delete{T}(string, string, IEnumerable{string})"/> public void Delete(string partitionKey, IEnumerable<string> rowKeys) { _provider.Delete<T>(_tableName, partitionKey, rowKeys); } /// <seealso cref="ITableStorageProvider.Delete{T}(string, string, IEnumerable{string})"/> public void Delete(string partitionKey, string rowKey) { _provider.Delete<T>(_tableName, partitionKey, new []{rowKey}); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Tables/CloudTable.cs
C#
bsd
4,844
#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.IO.Compression; using System.Reflection; using System.Runtime.Serialization; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; namespace Lokad.Cloud.Storage { /// <summary> /// Formatter based on <c>DataContractSerializer</c> and <c>NetDataContractSerializer</c>. /// The formatter targets storage of persistent or transient data in the cloud storage. /// </summary> /// <remarks> /// If a <c>DataContract</c> attribute is present, then the <c>DataContractSerializer</c> /// is favored. If not, then the <c>NetDataContractSerializer</c> is used instead. /// This class is not <b>thread-safe</b>. /// </remarks> public class CloudFormatter : IIntermediateDataSerializer { XmlObjectSerializer GetXmlSerializer(Type type) { // 'false' == do not inherit the attribute if (GetAttributes<DataContractAttribute>(type, false).Length > 0) { return new DataContractSerializer(type); } return new NetDataContractSerializer(); } public void Serialize(object instance, Stream destination) { var serializer = GetXmlSerializer(instance.GetType()); using(var compressed = Compress(destination, true)) using(var writer = XmlDictionaryWriter.CreateBinaryWriter(compressed, null, null, false)) { serializer.WriteObject(writer, instance); } } public object Deserialize(Stream source, Type type) { var serializer = GetXmlSerializer(type); using(var decompressed = Decompress(source, true)) using(var reader = XmlDictionaryReader.CreateBinaryReader(decompressed, XmlDictionaryReaderQuotas.Max)) { return serializer.ReadObject(reader); } } public XElement UnpackXml(Stream source) { using(var decompressed = Decompress(source, true)) using (var reader = XmlDictionaryReader.CreateBinaryReader(decompressed, XmlDictionaryReaderQuotas.Max)) { return XElement.Load(reader); } } public void RepackXml(XElement data, Stream destination) { using(var compressed = Compress(destination, true)) using(var writer = XmlDictionaryWriter.CreateBinaryWriter(compressed, null, null, false)) { data.Save(writer); writer.Flush(); compressed.Flush(); } } static GZipStream Compress(Stream stream, bool leaveOpen) { return new GZipStream(stream, CompressionMode.Compress, leaveOpen); } static GZipStream Decompress(Stream stream, bool leaveOpen) { return new GZipStream(stream, CompressionMode.Decompress, leaveOpen); } ///<summary>Retrieve attributes from the type.</summary> ///<param name="target">Type to perform operation upon</param> ///<param name="inherit"><see cref="MemberInfo.GetCustomAttributes(Type,bool)"/></param> ///<typeparam name="T">Attribute to use</typeparam> ///<returns>Empty array of <typeparamref name="T"/> if there are no attributes</returns> static T[] GetAttributes<T>(ICustomAttributeProvider target, bool inherit) where T : Attribute { if (target.IsDefined(typeof(T), inherit)) { return target .GetCustomAttributes(typeof(T), inherit) .Select(a => (T)a).ToArray(); } return new T[0]; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/CloudFormatter.cs
C#
bsd
3,994
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion namespace Lokad.Cloud.Storage { public class CloudStorageProviders { /// <summary>Abstracts the Blob Storage.</summary> public IBlobStorageProvider BlobStorage { get; private set; } /// <summary>Abstracts the Queue Storage.</summary> public IQueueStorageProvider QueueStorage { get; private set; } /// <summary>Abstracts the Table Storage.</summary> public ITableStorageProvider TableStorage { get; private set; } /// <summary>Abstracts the finalizer (used for fast resource release /// in case of runtime shutdown).</summary> public IRuntimeFinalizer RuntimeFinalizer { get; private set; } public Shared.Logging.ILog Log { get; private set; } /// <summary>IoC constructor.</summary> public CloudStorageProviders( IBlobStorageProvider blobStorage, IQueueStorageProvider queueStorage, ITableStorageProvider tableStorage, IRuntimeFinalizer runtimeFinalizer, Shared.Logging.ILog log) { BlobStorage = blobStorage; QueueStorage = queueStorage; TableStorage = tableStorage; RuntimeFinalizer = runtimeFinalizer; Log = log; } /// <summary>Copy constructor.</summary> protected CloudStorageProviders( CloudStorageProviders copyFrom) { BlobStorage = copyFrom.BlobStorage; QueueStorage = copyFrom.QueueStorage; TableStorage = copyFrom.TableStorage; RuntimeFinalizer = copyFrom.RuntimeFinalizer; Log = copyFrom.Log; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/CloudStorageProviders.cs
C#
bsd
1,863
#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.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("Lokad.Cloud.Storage")] [assembly: AssemblyDescription("")] [assembly: AssemblyCopyright("Copyright © Lokad 2010")] [assembly: AssemblyTrademark("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f1c9ee22-a41c-47ce-8d7e-bcacd3954986")] [assembly: InternalsVisibleTo("Lokad.Cloud.Framework.Test")]
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Properties/AssemblyInfo.cs
C#
bsd
839
#region Copyright (c) Lokad 2010-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.ComponentModel; using System.Net; using Lokad.Cloud.Storage.Shared; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.StorageClient; namespace Lokad.Cloud.Storage { public static class CloudStorage { public static CloudStorageBuilder ForAzureAccount(CloudStorageAccount storageAccount) { return new AzureCloudStorageBuilder(storageAccount); } public static CloudStorageBuilder ForAzureConnectionString(string connectionString) { CloudStorageAccount storageAccount; if (!CloudStorageAccount.TryParse(connectionString, out storageAccount)) { throw new InvalidOperationException("Failed to get valid connection string"); } return new AzureCloudStorageBuilder(storageAccount); } public static CloudStorageBuilder ForAzureAccountAndKey(string accountName, string key, bool useHttps = true) { return new AzureCloudStorageBuilder(new CloudStorageAccount(new StorageCredentialsAccountAndKey(accountName, key), useHttps)); } public static CloudStorageBuilder ForDevelopmentStorage() { return new AzureCloudStorageBuilder(CloudStorageAccount.DevelopmentStorageAccount); } public static CloudStorageBuilder ForInMemoryStorage() { return new InMemoryStorageBuilder(); } [EditorBrowsable(EditorBrowsableState.Never)] public abstract class CloudStorageBuilder { /// <remarks>Can not be null</remarks> protected IDataSerializer DataSerializer { get; private set; } /// <remarks>Can be null if not needed</remarks> protected Shared.Logging.ILog Log { get; private set; } /// <remarks>Can be null if not needed</remarks> protected IRuntimeFinalizer RuntimeFinalizer { get; private set; } protected CloudStorageBuilder() { // defaults DataSerializer = new CloudFormatter(); } /// <summary> /// Replace the default data serializer with a custom implementation /// </summary> public CloudStorageBuilder WithDataSerializer(IDataSerializer dataSerializer) { DataSerializer = dataSerializer; return this; } /// <summary> /// Optionally provide a log provider. /// </summary> public CloudStorageBuilder WithLog(Shared.Logging.ILog log) { Log = log; return this; } /// <summary> /// Optionally provide a runtime finalizer. /// </summary> public CloudStorageBuilder WithRuntimeFinalizer(IRuntimeFinalizer runtimeFinalizer) { RuntimeFinalizer = runtimeFinalizer; return this; } public abstract IBlobStorageProvider BuildBlobStorage(); public abstract ITableStorageProvider BuildTableStorage(); public abstract IQueueStorageProvider BuildQueueStorage(); public CloudStorageProviders BuildStorageProviders() { return new CloudStorageProviders( BuildBlobStorage(), BuildQueueStorage(), BuildTableStorage(), RuntimeFinalizer, Log); } } } internal sealed class InMemoryStorageBuilder : CloudStorage.CloudStorageBuilder { public override IBlobStorageProvider BuildBlobStorage() { return new InMemory.MemoryBlobStorageProvider { DataSerializer = DataSerializer }; } public override ITableStorageProvider BuildTableStorage() { return new InMemory.MemoryTableStorageProvider { DataSerializer = DataSerializer }; } public override IQueueStorageProvider BuildQueueStorage() { return new InMemory.MemoryQueueStorageProvider { DataSerializer = DataSerializer }; } } internal sealed class AzureCloudStorageBuilder : CloudStorage.CloudStorageBuilder { private readonly CloudStorageAccount _storageAccount; internal AzureCloudStorageBuilder(CloudStorageAccount storageAccount) { _storageAccount = storageAccount; // http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx ServicePointManager.FindServicePoint(storageAccount.TableEndpoint).UseNagleAlgorithm = false; ServicePointManager.FindServicePoint(storageAccount.QueueEndpoint).UseNagleAlgorithm = false; } public override IBlobStorageProvider BuildBlobStorage() { return new Azure.BlobStorageProvider( BlobClient(), DataSerializer, Log); } public override ITableStorageProvider BuildTableStorage() { return new Azure.TableStorageProvider( TableClient(), DataSerializer); } public override IQueueStorageProvider BuildQueueStorage() { return new Azure.QueueStorageProvider( QueueClient(), BuildBlobStorage(), DataSerializer, RuntimeFinalizer, Log); } CloudBlobClient BlobClient() { var blobClient = _storageAccount.CreateCloudBlobClient(); blobClient.RetryPolicy = BuildDefaultRetry(); return blobClient; } CloudTableClient TableClient() { var tableClient = _storageAccount.CreateCloudTableClient(); tableClient.RetryPolicy = BuildDefaultRetry(); return tableClient; } CloudQueueClient QueueClient() { var queueClient = _storageAccount.CreateCloudQueueClient(); queueClient.RetryPolicy = BuildDefaultRetry(); return queueClient; } static RetryPolicy BuildDefaultRetry() { // [abdullin]: in short this gives us MinBackOff + 2^(10)*Rand.(~0.5.Seconds()) // at the last retry. Reflect the method for more details var deltaBackoff = TimeSpan.FromSeconds(0.5); return RetryPolicies.RetryExponential(10, deltaBackoff); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/CloudStorage.cs
C#
bsd
7,094
#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.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.Cryptography; using System.Threading; using System.Xml.Linq; using Lokad.Cloud.Storage.Shared; using Lokad.Cloud.Storage.Shared.Diagnostics; using Lokad.Cloud.Storage.Shared.Policies; using Lokad.Cloud.Storage.Shared.Threading; using Microsoft.WindowsAzure.StorageClient; using Microsoft.WindowsAzure.StorageClient.Protocol; using Lokad.Cloud.Storage.Shared.Logging; namespace Lokad.Cloud.Storage.Azure { /// <summary>Provides access to the Blob Storage.</summary> /// <remarks> /// All the methods of <see cref="BlobStorageProvider"/> are thread-safe. /// </remarks> public class BlobStorageProvider : IBlobStorageProvider { /// <summary>Custom meta-data used as a work-around of an issue of the StorageClient.</summary> /// <remarks>[vermorel 2010-11] The StorageClient for odds reasons do not enable the /// retrieval of the Content-MD5 property when performing a GET on blobs. In order to validate /// the integrity during the entire roundtrip, we need to apply a suplementary header /// used to perform the MD5 check.</remarks> private const string MetadataMD5Key = "LokadContentMD5"; readonly CloudBlobClient _blobStorage; readonly IDataSerializer _serializer; readonly ActionPolicy _azureServerPolicy; readonly ActionPolicy _networkPolicy; readonly ILog _log; // Instrumentation readonly ExecutionCounter _countPutBlob; readonly ExecutionCounter _countGetBlob; readonly ExecutionCounter _countGetBlobIfModified; readonly ExecutionCounter _countUpsertBlobOrSkip; readonly ExecutionCounter _countDeleteBlob; /// <summary>IoC constructor.</summary> public BlobStorageProvider(CloudBlobClient blobStorage, IDataSerializer serializer, ILog log = null) { _blobStorage = blobStorage; _serializer = serializer; _log = log; _azureServerPolicy = AzurePolicies.TransientServerErrorBackOff; _networkPolicy = AzurePolicies.NetworkCorruption; // Instrumentation ExecutionCounters.Default.RegisterRange(new[] { _countPutBlob = new ExecutionCounter("BlobStorageProvider.PutBlob", 0, 0), _countGetBlob = new ExecutionCounter("BlobStorageProvider.GetBlob", 0, 0), _countGetBlobIfModified = new ExecutionCounter("BlobStorageProvider.GetBlobIfModified", 0, 0), _countUpsertBlobOrSkip = new ExecutionCounter("BlobStorageProvider.UpdateBlob", 0, 0), _countDeleteBlob = new ExecutionCounter("BlobStorageProvider.DeleteBlob", 0, 0), }); } public IEnumerable<string> ListContainers(string containerNamePrefix = null) { var enumerator = String.IsNullOrEmpty(containerNamePrefix) ? _blobStorage.ListContainers().GetEnumerator() : _blobStorage.ListContainers(containerNamePrefix).GetEnumerator(); // TODO: Parallelize while (true) { if (!_azureServerPolicy.Get(enumerator.MoveNext)) { yield break; } // removing /container/ from the blob name (dev storage: /account/container/) yield return enumerator.Current.Name; } } public bool CreateContainerIfNotExist(string containerName) { //workaround since Azure is presently returning OutOfRange exception when using a wrong name. if (!BlobStorageExtensions.IsContainerNameValid(containerName)) throw new NotSupportedException("containerName is not compliant with azure constraints on container naming"); var container = _blobStorage.GetContainerReference(containerName); try { _azureServerPolicy.Do(container.Create); return true; } catch(StorageClientException ex) { if(ex.ErrorCode == StorageErrorCode.ContainerAlreadyExists || ex.ErrorCode == StorageErrorCode.ResourceAlreadyExists) { return false; } throw; } } public bool DeleteContainerIfExist(string containerName) { var container = _blobStorage.GetContainerReference(containerName); try { _azureServerPolicy.Do(container.Delete); return true; } catch(StorageClientException ex) { if(ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return false; } throw; } } public IEnumerable<string> ListBlobNames(string containerName, string blobNamePrefix = null) { // Enumerated blobs do not have a "name" property, // thus the name must be extracted from their URI // http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/c5e36676-8d07-46cc-b803-72621a0898b0/?prof=required if (blobNamePrefix == null) { blobNamePrefix = string.Empty; } var container = _blobStorage.GetContainerReference(containerName); var options = new BlobRequestOptions { UseFlatBlobListing = true }; // if no prefix is provided, then enumerate the whole container IEnumerator<IListBlobItem> enumerator; if (string.IsNullOrEmpty(blobNamePrefix)) { enumerator = container.ListBlobs(options).GetEnumerator(); } else { // 'CloudBlobDirectory' must be used for prefixed enumeration var directory = container.GetDirectoryReference(blobNamePrefix); // HACK: [vermorel] very ugly override, but otherwise an "/" separator gets forcibly added typeof(CloudBlobDirectory).GetField("prefix", BindingFlags.Instance | BindingFlags.NonPublic) .SetValue(directory, blobNamePrefix); enumerator = directory.ListBlobs(options).GetEnumerator(); } // TODO: Parallelize while (true) { try { if (!_azureServerPolicy.Get(enumerator.MoveNext)) { yield break; } } catch (StorageClientException ex) { // if the container does not exist, empty enumeration if (ex.ErrorCode == StorageErrorCode.ContainerNotFound) { yield break; } throw; } // removing /container/ from the blob name (dev storage: /account/container/) yield return Uri.UnescapeDataString(enumerator.Current.Uri.AbsolutePath.Substring(container.Uri.LocalPath.Length + 1)); } } public IEnumerable<T> ListBlobs<T>(string containerName, string blobNamePrefix = null, int skip = 0) { var names = ListBlobNames(containerName, blobNamePrefix); if (skip > 0) { names = names.Skip(skip); } return names.Select(name => GetBlob<T>(containerName, name)) .Where(blob => blob.HasValue) .Select(blob => blob.Value); } public bool DeleteBlobIfExist(string containerName, string blobName) { var timestamp = _countDeleteBlob.Open(); var container = _blobStorage.GetContainerReference(containerName); try { var blob = container.GetBlockBlobReference(blobName); _azureServerPolicy.Do(blob.Delete); _countDeleteBlob.Close(timestamp); return true; } catch (StorageClientException ex) // no such container, return false { if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return false; } throw; } } public void DeleteAllBlobs(string containerName, string blobNamePrefix = null) { // TODO: Parallelize foreach (var blobName in ListBlobNames(containerName, blobNamePrefix)) { DeleteBlobIfExist(containerName, blobName); } } public Maybe<T> GetBlob<T>(string containerName, string blobName) { string ignoredEtag; return GetBlob<T>(containerName, blobName, out ignoredEtag); } public Maybe<T> GetBlob<T>(string containerName, string blobName, out string etag) { return GetBlob(containerName, blobName, typeof(T), out etag) .Convert(o => (T)o, Maybe<T>.Empty); } public Maybe<object> GetBlob(string containerName, string blobName, Type type, out string etag) { var timestamp = _countGetBlob.Open(); var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); using (var stream = new MemoryStream()) { etag = null; // if no such container, return empty try { _azureServerPolicy.Do(() => _networkPolicy.Do(() => { stream.Seek(0, SeekOrigin.Begin); blob.DownloadToStream(stream); VerifyContentHash(blob, stream, containerName, blobName); })); etag = blob.Properties.ETag; } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return Maybe<object>.Empty; } throw; } stream.Seek(0, SeekOrigin.Begin); var deserialized = _serializer.TryDeserialize(stream, type); _countGetBlob.Close(timestamp); if (!deserialized.IsSuccess && _log != null) { _log.WarnFormat(deserialized.Error, "Cloud Storage: A blob was retrieved for GeBlob but failed to deserialize. Blob {0} in container {1}.", blobName, containerName); } return deserialized.IsSuccess ? new Maybe<object>(deserialized.Value) : Maybe<object>.Empty; } } public Maybe<XElement> GetBlobXml(string containerName, string blobName, out string etag) { etag = null; var formatter = _serializer as IIntermediateDataSerializer; if (formatter == null) { return Maybe<XElement>.Empty; } var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); using (var stream = new MemoryStream()) { // if no such container, return empty try { _azureServerPolicy.Do(() => _networkPolicy.Do(() => { stream.Seek(0, SeekOrigin.Begin); blob.DownloadToStream(stream); VerifyContentHash(blob, stream, containerName, blobName); })); etag = blob.Properties.ETag; } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return Maybe<XElement>.Empty; } throw; } stream.Seek(0, SeekOrigin.Begin); var unpacked = formatter.TryUnpackXml(stream); return unpacked.IsSuccess ? unpacked.Value : Maybe<XElement>.Empty; } } /// <summary>As many parallel requests than there are blob names.</summary> public Maybe<T>[] GetBlobRange<T>(string containerName, string[] blobNames, out string[] etags) { var tempResult = blobNames.SelectInParallel(blobName => { string etag; var blob = GetBlob<T>(containerName, blobName, out etag); return new Tuple<Maybe<T>, string>(blob, etag); }, blobNames.Length); etags = new string[blobNames.Length]; var result = new Maybe<T>[blobNames.Length]; for (int i = 0; i < tempResult.Length; i++) { result[i] = tempResult[i].Item1; etags[i] = tempResult[i].Item2; } return result; } public Maybe<T> GetBlobIfModified<T>(string containerName, string blobName, string oldEtag, out string newEtag) { // 'oldEtag' is null, then behavior always match simple 'GetBlob'. if (null == oldEtag) { return GetBlob<T>(containerName, blobName, out newEtag); } var timestamp = _countGetBlobIfModified.Open(); newEtag = null; var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); try { var options = new BlobRequestOptions { AccessCondition = AccessCondition.IfNoneMatch(oldEtag) }; using (var stream = new MemoryStream()) { _azureServerPolicy.Do(() => _networkPolicy.Do(() => { stream.Seek(0, SeekOrigin.Begin); blob.DownloadToStream(stream, options); VerifyContentHash(blob, stream, containerName, blobName); })); newEtag = blob.Properties.ETag; stream.Seek(0, SeekOrigin.Begin); var deserialized = _serializer.TryDeserializeAs<T>(stream); _countGetBlobIfModified.Close(timestamp); if (!deserialized.IsSuccess && _log != null) { _log.WarnFormat(deserialized.Error, "Cloud Storage: A blob was retrieved for GetBlobIfModified but failed to deserialize. Blob {0} in container {1}.", blobName, containerName); } return deserialized.IsSuccess ? deserialized.Value : Maybe<T>.Empty; } } catch (StorageClientException ex) { // call fails because blob has not been modified (usual case) if (ex.ErrorCode == StorageErrorCode.ConditionFailed || // HACK: BUG in StorageClient 1.0 // see http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/4817cafa-12d8-4979-b6a7-7bda053e6b21 ex.Message == @"The condition specified using HTTP conditional header(s) is not met.") { return Maybe<T>.Empty; } // call fails due to misc problems if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return Maybe<T>.Empty; } throw; } } public string GetBlobEtag(string containerName, string blobName) { var container = _blobStorage.GetContainerReference(containerName); try { var blob = container.GetBlockBlobReference(blobName); _azureServerPolicy.Do(blob.FetchAttributes); return blob.Properties.ETag; } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return null; } throw; } } public void PutBlob<T>(string containerName, string blobName, T item) { PutBlob(containerName, blobName, item, true); } public bool PutBlob<T>(string containerName, string blobName, T item, bool overwrite) { string ignored; return PutBlob(containerName, blobName, item, overwrite, out ignored); } public bool PutBlob<T>(string containerName, string blobName, T item, bool overwrite, out string etag) { return PutBlob(containerName, blobName, item, typeof(T), overwrite, out etag); } public bool PutBlob<T>(string containerName, string blobName, T item, string expectedEtag) { string outEtag; return PutBlob(containerName, blobName, item, typeof (T), true, expectedEtag, out outEtag); } public bool PutBlob(string containerName, string blobName, object item, Type type, bool overwrite, string expectedEtag, out string outEtag) { var timestamp = _countPutBlob.Open(); using (var stream = new MemoryStream()) { _serializer.Serialize(item, stream); var container = _blobStorage.GetContainerReference(containerName); Func<Maybe<string>> doUpload = () => { var blob = container.GetBlockBlobReference(blobName); // single remote call var result = UploadBlobContent(blob, stream, overwrite, expectedEtag); return result; }; try { var result = doUpload(); if (!result.HasValue) { outEtag = null; return false; } outEtag = result.Value; _countPutBlob.Close(timestamp); return true; } catch (StorageClientException ex) { // if the container does not exist, it gets created if (ex.ErrorCode == StorageErrorCode.ContainerNotFound) { // caution: the container might have been freshly deleted // (multiple retries are needed in such a situation) var tentativeEtag = Maybe<string>.Empty; AzurePolicies.SlowInstantiation.Do(() => { _azureServerPolicy.Get(container.CreateIfNotExist); tentativeEtag = doUpload(); }); if (!tentativeEtag.HasValue) { outEtag = null; return false; } outEtag = tentativeEtag.Value; _countPutBlob.Close(timestamp); return true; } if (ex.ErrorCode == StorageErrorCode.BlobAlreadyExists && !overwrite) { // See http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/fff78a35-3242-4186-8aee-90d27fbfbfd4 // and http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/86b9f184-c329-4c30-928f-2991f31e904b/ outEtag = null; return false; } var result = doUpload(); if (!result.HasValue) { outEtag = null; return false; } outEtag = result.Value; _countPutBlob.Close(timestamp); return true; } } } public bool PutBlob(string containerName, string blobName, object item, Type type, bool overwrite, out string outEtag) { return PutBlob(containerName, blobName, item, type, overwrite, null, out outEtag); } /// <param name="overwrite">If <c>false</c>, then no write happens if the blob already exists.</param> /// <param name="expectedEtag">When specified, no writing occurs unless the blob etag /// matches the one specified as argument.</param> /// <returns>The ETag of the written blob, if it was written.</returns> Maybe<string> UploadBlobContent(CloudBlob blob, Stream stream, bool overwrite, string expectedEtag) { BlobRequestOptions options; if (!overwrite) // no overwrite authorized, blob must NOT exists { options = new BlobRequestOptions { AccessCondition = AccessCondition.IfNotModifiedSince(DateTime.MinValue) }; } else // overwrite is OK { options = string.IsNullOrEmpty(expectedEtag) ? // case with no etag constraint new BlobRequestOptions { AccessCondition = AccessCondition.None } : // case with etag constraint new BlobRequestOptions { AccessCondition = AccessCondition.IfMatch(expectedEtag) }; } ApplyContentHash(blob, stream); try { _azureServerPolicy.Do(() => _networkPolicy.Do(() => { stream.Seek(0, SeekOrigin.Begin); blob.UploadFromStream(stream, options); })); } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ConditionFailed) { return Maybe<string>.Empty; } throw; } return blob.Properties.ETag; } public Maybe<T> UpdateBlobIfExist<T>( string containerName, string blobName, Func<T, T> update) { return UpsertBlobOrSkip(containerName, blobName, () => Maybe<T>.Empty, t => update(t)); } public Maybe<T> UpdateBlobIfExistOrSkip<T>( string containerName, string blobName, Func<T, Maybe<T>> update) { return UpsertBlobOrSkip(containerName, blobName, () => Maybe<T>.Empty, update); } public Maybe<T> UpdateBlobIfExistOrDelete<T>( string containerName, string blobName, Func<T, Maybe<T>> update) { var result = UpsertBlobOrSkip(containerName, blobName, () => Maybe<T>.Empty, update); if (!result.HasValue) { DeleteBlobIfExist(containerName, blobName); } return result; } public T UpsertBlob<T>(string containerName, string blobName, Func<T> insert, Func<T, T> update) { return UpsertBlobOrSkip<T>(containerName, blobName, () => insert(), t => update(t)).Value; } public Maybe<T> UpsertBlobOrSkip<T>( string containerName, string blobName, Func<Maybe<T>> insert, Func<T, Maybe<T>> update) { var timestamp = _countUpsertBlobOrSkip.Open(); var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); Maybe<T> output; TimeSpan retryInterval; var retryPolicy = AzurePolicies.OptimisticConcurrency(); for (int retryCount = 0; retryPolicy(retryCount, null, out retryInterval); retryCount++) { // 1. DOWNLOAD EXISTING INPUT BLOB, IF IT EXISTS Maybe<T> input; bool inputBlobExists = false; string inputETag = null; try { using (var readStream = new MemoryStream()) { _azureServerPolicy.Do(() => _networkPolicy.Do(() => { readStream.Seek(0, SeekOrigin.Begin); blob.DownloadToStream(readStream); VerifyContentHash(blob, readStream, containerName, blobName); })); inputETag = blob.Properties.ETag; inputBlobExists = !String.IsNullOrEmpty(inputETag); readStream.Seek(0, SeekOrigin.Begin); var deserialized = _serializer.TryDeserializeAs<T>(readStream); if (!deserialized.IsSuccess && _log != null) { _log.WarnFormat(deserialized.Error, "Cloud Storage: A blob was retrieved for Upsert but failed to deserialize. An Insert will be performed instead, overwriting the corrupt blob {0} in container {1}.", blobName, containerName); } input = deserialized.IsSuccess ? deserialized.Value : Maybe<T>.Empty; } } catch (StorageClientException ex) { // creating the container when missing if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { input = Maybe<T>.Empty; // caution: the container might have been freshly deleted // (multiple retries are needed in such a situation) AzurePolicies.SlowInstantiation.Do(() => _azureServerPolicy.Get(container.CreateIfNotExist)); } else { throw; } } // 2. APPLY UPADTE OR INSERT (DEPENDING ON INPUT) output = input.HasValue ? update(input.Value) : insert(); // 3. IF EMPTY OUTPUT THEN WE CAN SKIP THE WHOLE OPERATION if (!output.HasValue) { _countUpsertBlobOrSkip.Close(timestamp); return output; } // 4. TRY TO INSERT OR UPDATE BLOB using (var writeStream = new MemoryStream()) { _serializer.Serialize(output.Value, writeStream); writeStream.Seek(0, SeekOrigin.Begin); // Semantics: // Insert: Blob must not exist -> do not overwrite // Update: Blob must exists -> overwrite and verify matching ETag bool succeeded = inputBlobExists ? UploadBlobContent(blob, writeStream, true, inputETag).HasValue : UploadBlobContent(blob, writeStream, false, null).HasValue; if (succeeded) { _countUpsertBlobOrSkip.Close(timestamp); return output; } } // 5. WAIT UNTIL NEXT TRIAL (retry policy) if (retryInterval > TimeSpan.Zero) { Thread.Sleep(retryInterval); } } throw new TimeoutException("Failed to resolve optimistic concurrency errors within a limited number of retrials"); } public Maybe<T> UpsertBlobOrDelete<T>( string containerName, string blobName, Func<Maybe<T>> insert, Func<T, Maybe<T>> update) { var result = UpsertBlobOrSkip(containerName, blobName, insert, update); if (!result.HasValue) { DeleteBlobIfExist(containerName, blobName); } return result; } private static string ComputeContentHash(Stream source) { byte[] hash; source.Seek(0, SeekOrigin.Begin); using (var md5 = MD5.Create()) { hash = md5.ComputeHash(source); } source.Seek(0, SeekOrigin.Begin); return Convert.ToBase64String(hash); } /// <summary> /// Apply a content hash to the blob to verify upload and roundtrip consistency. /// </summary> private static void ApplyContentHash(CloudBlob blob, Stream stream) { var hash = ComputeContentHash(stream); // HACK: [Vermorel 2010-11] StorageClient does not apply MD5 on smaller blobs. // Reflector indicates that the behavior threshold is at 32MB // so manually disable hasing for larger blobs if (stream.Length < 0x2000000L) { blob.Properties.ContentMD5 = hash; } // HACK: [vermorel 2010-11] StorageClient does not provide a way to retrieve // MD5 so we add our own MD5 check which let perform our own validation when // downloading the blob (full roundtrip validation). blob.Metadata[MetadataMD5Key] = hash; } /// <summary> /// Throws a DataCorruptionException if the content hash is available but doesn't match. /// </summary> private static void VerifyContentHash(CloudBlob blob, Stream stream, string containerName, string blobName) { var expectedHash = blob.Metadata[MetadataMD5Key]; if (string.IsNullOrEmpty(expectedHash)) { return; } if (expectedHash != ComputeContentHash(stream)) { throw new DataCorruptionException( string.Format("MD5 mismatch on blob retrieval {0}/{1}.", containerName, blobName)); } } public Result<string> TryAcquireLease(string containerName, string blobName) { var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); var credentials = _blobStorage.Credentials; var uri = new Uri(credentials.TransformUri(blob.Uri.ToString())); var request = BlobRequest.Lease(uri, 90, LeaseAction.Acquire, null); credentials.SignRequest(request); HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException we) { var statusCode = ((HttpWebResponse) we.Response).StatusCode; switch (statusCode) { case HttpStatusCode.Conflict: case HttpStatusCode.RequestTimeout: case HttpStatusCode.InternalServerError: return Result<string>.CreateError(statusCode.ToString()); default: throw; } } try { return response.StatusCode == HttpStatusCode.Created ? Result<string>.CreateSuccess(response.Headers["x-ms-lease-id"]) : Result<string>.CreateError(response.StatusCode.ToString()); } finally { response.Close(); } } public bool TryReleaseLease(string containerName, string blobName, string leaseId) { return TryLeaseAction(containerName, blobName, LeaseAction.Release, leaseId); } public bool TryRenewLease(string containerName, string blobName, string leaseId) { return TryLeaseAction(containerName, blobName, LeaseAction.Renew, leaseId); } private bool TryLeaseAction(string containerName, string blobName, LeaseAction action, string leaseId = null) { var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); var credentials = _blobStorage.Credentials; var uri = new Uri(credentials.TransformUri(blob.Uri.ToString())); var request = BlobRequest.Lease(uri, 90, action, leaseId); credentials.SignRequest(request); HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException we) { var statusCode = ((HttpWebResponse) we.Response).StatusCode; switch(statusCode) { case HttpStatusCode.Conflict: case HttpStatusCode.RequestTimeout: case HttpStatusCode.InternalServerError: return false; default: throw; } } try { var expectedCode = action == LeaseAction.Break ? HttpStatusCode.Accepted : HttpStatusCode.OK; return response.StatusCode == expectedCode; } finally { response.Close(); } } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Azure/BlobStorageProvider.cs
C#
bsd
36,425
#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.Runtime.Serialization; namespace Lokad.Cloud.Storage.Azure { /// <summary> /// Exception indicating that received data has been detected to be corrupt or altered. /// </summary> [Serializable] public class DataCorruptionException : Exception { public DataCorruptionException() { } public DataCorruptionException(string message) : base(message) { } public DataCorruptionException(string message, Exception inner) : base(message, inner) { } protected DataCorruptionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Azure/DataCorruptionException.cs
C#
bsd
812
#region Copyright (c) Lokad 2010-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.Data.Services.Client; using System.Diagnostics; using System.Linq; using System.Text; using System.Web; using Lokad.Cloud.Storage.Shared; using Lokad.Cloud.Storage.Shared.Diagnostics; using Lokad.Cloud.Storage.Shared.Policies; using Microsoft.WindowsAzure.StorageClient; namespace Lokad.Cloud.Storage.Azure { /// <summary>Implementation based on the Table Storage of Windows Azure.</summary> public class TableStorageProvider : ITableStorageProvider { // HACK: those tokens will probably be provided as constants in the StorageClient library const int MaxEntityTransactionCount = 100; // HACK: Lowering the maximal payload, to avoid corner cases #117 (ContentLengthExceeded) // [vermorel] 128kB is purely arbitrary, only taken as a reasonable safety margin const int MaxEntityTransactionPayload = 4 * 1024 * 1024 - 128 * 1024; // 4 MB - 128kB const string ContinuationNextRowKeyToken = "x-ms-continuation-NextRowKey"; const string ContinuationNextPartitionKeyToken = "x-ms-continuation-NextPartitionKey"; const string NextRowKeyToken = "NextRowKey"; const string NextPartitionKeyToken = "NextPartitionKey"; readonly CloudTableClient _tableStorage; readonly IDataSerializer _serializer; readonly ActionPolicy _storagePolicy; // Instrumentation readonly ExecutionCounter _countQuery; readonly ExecutionCounter _countInsert; readonly ExecutionCounter _countUpdate; readonly ExecutionCounter _countDelete; /// <summary>IoC constructor.</summary> public TableStorageProvider(CloudTableClient tableStorage, IDataSerializer serializer) { _tableStorage = tableStorage; _serializer = serializer; _storagePolicy = AzurePolicies.TransientTableErrorBackOff; // Instrumentation ExecutionCounters.Default.RegisterRange(new[] { _countQuery = new ExecutionCounter("TableStorageProvider.QuerySegment", 0, 0), _countInsert = new ExecutionCounter("TableStorageProvider.InsertSlice", 0, 0), _countUpdate = new ExecutionCounter("TableStorageProvider.UpdateSlice", 0, 0), _countDelete = new ExecutionCounter("TableStorageProvider.DeleteSlice", 0, 0), }); } public bool CreateTable(string tableName) { var flag = false; AzurePolicies.SlowInstantiation.Do(() => flag = _tableStorage.CreateTableIfNotExist(tableName)); return flag; } public bool DeleteTable(string tableName) { var flag = false; AzurePolicies.SlowInstantiation.Do(() => flag = _tableStorage.DeleteTableIfExist(tableName)); return flag; } public IEnumerable<string> GetTables() { return _tableStorage.ListTables(); } public IEnumerable<CloudEntity<T>> Get<T>(string tableName) { if(null == tableName) throw new ArgumentNullException("tableName"); var context = _tableStorage.GetDataServiceContext(); return GetInternal<T>(context, tableName, Maybe<string>.Empty); } public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey) { if(null == tableName) throw new ArgumentNullException("tableName"); if(null == partitionKey) throw new ArgumentNullException("partitionKey"); if (partitionKey.Contains("'")) throw new ArgumentOutOfRangeException("partitionKey", "Incorrect char in partitionKey."); var filter = string.Format("(PartitionKey eq '{0}')", HttpUtility.UrlEncode(partitionKey)); var context = _tableStorage.GetDataServiceContext(); return GetInternal<T>(context, tableName, filter); } public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, string startRowKey, string endRowKey) { if(null == tableName) throw new ArgumentNullException("tableName"); if(null == partitionKey) throw new ArgumentNullException("partitionKey"); if (partitionKey.Contains("'")) throw new ArgumentOutOfRangeException("partitionKey", "Incorrect char."); if(startRowKey != null && startRowKey.Contains("'")) throw new ArgumentOutOfRangeException("startRowKey", "Incorrect char."); if(endRowKey != null && endRowKey.Contains("'")) throw new ArgumentOutOfRangeException("endRowKey", "Incorrect char."); var filter = string.Format("(PartitionKey eq '{0}')", HttpUtility.UrlEncode(partitionKey)); // optional starting range constraint if (!string.IsNullOrEmpty(startRowKey)) { // ge = GreaterThanOrEqual (inclusive) filter += string.Format(" and (RowKey ge '{0}')", HttpUtility.UrlEncode(startRowKey)); } if (!string.IsNullOrEmpty(endRowKey)) { // lt = LessThan (exclusive) filter += string.Format(" and (RowKey lt '{0}')", HttpUtility.UrlEncode(endRowKey)); } var context = _tableStorage.GetDataServiceContext(); return GetInternal<T>(context, tableName, filter); } public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys) { if(null == tableName) throw new ArgumentNullException("tableName"); if(null == partitionKey) throw new ArgumentNullException("partitionKey"); if(partitionKey.Contains("'")) throw new ArgumentOutOfRangeException("partitionKey", "Incorrect char."); var context = _tableStorage.GetDataServiceContext(); foreach (var slice in Slice(rowKeys, MaxEntityTransactionCount)) { // work-around the limitation of ADO.NET that does not provide a native way // of query a set of specified entities directly. var builder = new StringBuilder(); builder.Append(string.Format("(PartitionKey eq '{0}') and (", HttpUtility.UrlEncode(partitionKey))); for (int i = 0; i < slice.Length; i++) { // in order to avoid SQL-injection-like problems if (slice[i].Contains("'")) throw new ArgumentOutOfRangeException("rowKeys", "Incorrect char."); builder.Append(string.Format("(RowKey eq '{0}')", HttpUtility.UrlEncode(slice[i]))); if (i < slice.Length - 1) { builder.Append(" or "); } } builder.Append(")"); foreach(var entity in GetInternal<T>(context, tableName, builder.ToString())) { yield return entity; } } } private IEnumerable<CloudEntity<T>> GetInternal<T>(TableServiceContext context, string tableName, Maybe<string> filter) { string continuationRowKey = null; string continuationPartitionKey = null; var timestamp = _countQuery.Open(); context.MergeOption = MergeOption.AppendOnly; context.ResolveType = ResolveFatEntityType; do { var query = context.CreateQuery<FatEntity>(tableName); if (filter.HasValue) { query = query.AddQueryOption("$filter", filter.Value); } if (null != continuationRowKey) { query = query.AddQueryOption(NextRowKeyToken, continuationRowKey) .AddQueryOption(NextPartitionKeyToken, continuationPartitionKey); } QueryOperationResponse response = null; FatEntity[] fatEntities = null; _storagePolicy.Do(() => { try { response = query.Execute() as QueryOperationResponse; fatEntities = ((IEnumerable<FatEntity>)response).ToArray(); } catch (DataServiceQueryException ex) { // if the table does not exist, there is nothing to return var errorCode = AzurePolicies.GetErrorCode(ex); if (TableErrorCodeStrings.TableNotFound == errorCode || StorageErrorCodeStrings.ResourceNotFound == errorCode) { fatEntities = new FatEntity[0]; return; } throw; } }); _countQuery.Close(timestamp); foreach (var fatEntity in fatEntities) { var etag = context.Entities.First(e => e.Entity == fatEntity).ETag; context.Detach(fatEntity); yield return FatEntity.Convert<T>(fatEntity, _serializer, etag); } Debug.Assert(context.Entities.Count == 0); if (null != response && response.Headers.ContainsKey(ContinuationNextRowKeyToken)) { continuationRowKey = response.Headers[ContinuationNextRowKeyToken]; continuationPartitionKey = response.Headers[ContinuationNextPartitionKeyToken]; timestamp = _countQuery.Open(); } else { continuationRowKey = null; continuationPartitionKey = null; } } while (null != continuationRowKey); } public void Insert<T>(string tableName, IEnumerable<CloudEntity<T>> entities) { foreach (var g in entities.GroupBy(e => e.PartitionKey)) { InsertInternal(tableName, g); } } void InsertInternal<T>(string tableName, IEnumerable<CloudEntity<T>> entities) { var context = _tableStorage.GetDataServiceContext(); context.MergeOption = MergeOption.AppendOnly; context.ResolveType = ResolveFatEntityType; var fatEntities = entities.Select(e => Tuple.Create(FatEntity.Convert(e, _serializer), e)); var noBatchMode = false; foreach (var slice in SliceEntities(fatEntities, e => e.Item1.GetPayload())) { var timestamp = _countInsert.Open(); var cloudEntityOfFatEntity = new Dictionary<object, CloudEntity<T>>(); foreach (var fatEntity in slice) { context.AddObject(tableName, fatEntity.Item1); cloudEntityOfFatEntity.Add(fatEntity.Item1, fatEntity.Item2); } _storagePolicy.Do(() => { try { // HACK: nested try/catch try { context.SaveChanges(noBatchMode ? SaveChangesOptions.None : SaveChangesOptions.Batch); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); } // special casing the need for table instantiation catch (DataServiceRequestException ex) { var errorCode = AzurePolicies.GetErrorCode(ex); if (errorCode == TableErrorCodeStrings.TableNotFound || errorCode == StorageErrorCodeStrings.ResourceNotFound) { AzurePolicies.SlowInstantiation.Do(() => { try { _tableStorage.CreateTableIfNotExist(tableName); } // HACK: incorrect behavior of the StorageClient (2010-09) // Fails to behave properly in multi-threaded situations catch (StorageClientException cex) { if (cex.ExtendedErrorInformation == null || cex.ExtendedErrorInformation.ErrorCode != TableErrorCodeStrings.TableAlreadyExists) { throw; } } context.SaveChanges(noBatchMode ? SaveChangesOptions.None : SaveChangesOptions.Batch); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); }); } else { throw; } } } catch (DataServiceRequestException ex) { var errorCode = AzurePolicies.GetErrorCode(ex); if (errorCode == StorageErrorCodeStrings.OperationTimedOut) { // if batch does not work, then split into elementary requests // PERF: it would be better to split the request in two and retry context.SaveChanges(); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); noBatchMode = true; } // HACK: undocumented code returned by the Table Storage else if (errorCode == "ContentLengthExceeded") { context.SaveChanges(); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); noBatchMode = true; } else { throw; } } catch (DataServiceQueryException ex) { // HACK: code dupplicated var errorCode = AzurePolicies.GetErrorCode(ex); if (errorCode == StorageErrorCodeStrings.OperationTimedOut) { // if batch does not work, then split into elementary requests // PERF: it would be better to split the request in two and retry context.SaveChanges(); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); noBatchMode = true; } else { throw; } } }); _countInsert.Close(timestamp); } } public void Update<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force) { foreach (var g in entities.GroupBy(e => e.PartitionKey)) { UpdateInternal(tableName, g, force); } } void UpdateInternal<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force) { var context = _tableStorage.GetDataServiceContext(); context.MergeOption = MergeOption.AppendOnly; context.ResolveType = ResolveFatEntityType; var fatEntities = entities.Select(e => Tuple.Create(FatEntity.Convert(e, _serializer), e)); var noBatchMode = false; foreach (var slice in SliceEntities(fatEntities, e => e.Item1.GetPayload())) { var timestamp = _countUpdate.Open(); var cloudEntityOfFatEntity = new Dictionary<object, CloudEntity<T>>(); foreach (var fatEntity in slice) { // entities should be updated in a single round-trip context.AttachTo(tableName, fatEntity.Item1, MapETag(fatEntity.Item2.ETag, force)); context.UpdateObject(fatEntity.Item1); cloudEntityOfFatEntity.Add(fatEntity.Item1, fatEntity.Item2); } _storagePolicy.Do(() => { try { context.SaveChanges(noBatchMode ? SaveChangesOptions.None : SaveChangesOptions.Batch); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); } catch (DataServiceRequestException ex) { var errorCode = AzurePolicies.GetErrorCode(ex); if (errorCode == StorageErrorCodeStrings.OperationTimedOut) { // if batch does not work, then split into elementary requests // PERF: it would be better to split the request in two and retry context.SaveChanges(); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); noBatchMode = true; } else if (errorCode == TableErrorCodeStrings.TableNotFound) { AzurePolicies.SlowInstantiation.Do(() => { try { _tableStorage.CreateTableIfNotExist(tableName); } // HACK: incorrect behavior of the StorageClient (2010-09) // Fails to behave properly in multi-threaded situations catch (StorageClientException cex) { if (cex.ExtendedErrorInformation.ErrorCode != TableErrorCodeStrings.TableAlreadyExists) { throw; } } context.SaveChanges(noBatchMode ? SaveChangesOptions.None : SaveChangesOptions.Batch); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); }); } else { throw; } } catch (DataServiceQueryException ex) { // HACK: code dupplicated var errorCode = AzurePolicies.GetErrorCode(ex); if (errorCode == StorageErrorCodeStrings.OperationTimedOut) { // if batch does not work, then split into elementary requests // PERF: it would be better to split the request in two and retry context.SaveChanges(); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); noBatchMode = true; } else { throw; } } }); _countUpdate.Close(timestamp); } } public void Upsert<T>(string tableName, IEnumerable<CloudEntity<T>> entities) { foreach (var g in entities.GroupBy(e => e.PartitionKey)) { UpsertInternal(tableName, g); } } // HACK: no 'upsert' (update or insert) available at the time // http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/4b902237-7cfb-4d48-941b-4802864fc274 /// <remarks>Upsert is making several storage calls to emulate the /// missing semantic from the Table Storage.</remarks> void UpsertInternal<T>(string tableName, IEnumerable<CloudEntity<T>> entities) { // checking for entities that already exist var partitionKey = entities.First().PartitionKey; var existingKeys = new HashSet<string>( Get<T>(tableName, partitionKey, entities.Select(e => e.RowKey)).Select(e => e.RowKey)); // inserting or updating depending on the presence of the keys Insert(tableName, entities.Where(e => !existingKeys.Contains(e.RowKey))); Update(tableName, entities.Where(e => existingKeys.Contains(e.RowKey)), true); } /// <summary>Slice entities according the payload limitation of /// the transaction group, plus the maximal number of entities to /// be embedded into a single transaction.</summary> static IEnumerable<T[]> SliceEntities<T>(IEnumerable<T> entities, Func<T, int> getPayload) { var accumulator = new List<T>(100); var payload = 0; foreach (var entity in entities) { var entityPayLoad = getPayload(entity); if (accumulator.Count >= MaxEntityTransactionCount || payload + entityPayLoad >= MaxEntityTransactionPayload) { yield return accumulator.ToArray(); accumulator.Clear(); payload = 0; } accumulator.Add(entity); payload += entityPayLoad; } if (accumulator.Count > 0) { yield return accumulator.ToArray(); } } public void Delete<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys) { DeleteInternal<T>(tableName, partitionKey, rowKeys.Select(k => Tuple.Create(k, "*")), true); } public void Delete<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force) { foreach (var g in entities.GroupBy(e => e.PartitionKey)) { DeleteInternal<T>(tableName, g.Key, g.Select(e => Tuple.Create(e.RowKey, MapETag(e.ETag, force))), force); } } void DeleteInternal<T>(string tableName, string partitionKey, IEnumerable<Tuple<string,string>> rowKeysAndETags, bool force) { var context = _tableStorage.GetDataServiceContext(); // CAUTION: make sure to get rid of potential duplicate in rowkeys. // (otherwise insertion in 'context' is likely to fail) foreach (var s in Slice(rowKeysAndETags // Similar effect than 'Distinct' based on 'RowKey' .ToLookup(p => p.Item1, p => p).Select(g => g.First()), MaxEntityTransactionCount)) { var timestamp = _countDelete.Open(); var slice = s; DeletionStart: // 'slice' might have been refreshed if some entities were already deleted foreach (var rowKeyAndETag in slice) { // Deleting entities in 1 roundtrip // http://blog.smarx.com/posts/deleting-entities-from-windows-azure-without-querying-first var mock = new FatEntity { PartitionKey = partitionKey, RowKey = rowKeyAndETag.Item1 }; context.AttachTo(tableName, mock, rowKeyAndETag.Item2); context.DeleteObject(mock); } try // HACK: [vermorel] if a single entity is missing, then the whole batch operation is aborded { try // HACK: nested try/catch to handle the special case where the table is missing { _storagePolicy.Do(() => context.SaveChanges(SaveChangesOptions.Batch)); } catch (DataServiceRequestException ex) { // if the table is missing, no need to go on with the deletion var errorCode = AzurePolicies.GetErrorCode(ex); if (TableErrorCodeStrings.TableNotFound == errorCode) { _countDelete.Close(timestamp); return; } throw; } } // if some entities exist catch (DataServiceRequestException ex) { var errorCode = AzurePolicies.GetErrorCode(ex); // HACK: Table Storage both implement a bizarre non-idempotent semantic // but in addition, it throws a non-documented exception as well. if (errorCode != "ResourceNotFound") { throw; } slice = Get<T>(tableName, partitionKey, slice.Select(p => p.Item1)) .Select(e => Tuple.Create(e.RowKey, MapETag(e.ETag, force))).ToArray(); // entities with same name will be added again context = _tableStorage.GetDataServiceContext(); // HACK: [vermorel] yes, gotos are horrid, but other solutions are worst here. goto DeletionStart; } _countDelete.Close(timestamp); } } static Type ResolveFatEntityType(string name) { return typeof (FatEntity); } static string MapETag(string etag, bool force) { return force || string.IsNullOrEmpty(etag) ? "*" : etag; } static void ReadETagsAndDetach(DataServiceContext context, Action<object, string> write) { foreach (var entity in context.Entities) { write(entity.Entity, entity.ETag); context.Detach(entity.Entity); } } /// <summary> /// Performs lazy splitting of the provided collection into collections of <paramref name="sliceLength"/> /// </summary> /// <typeparam name="TItem">The type of the item.</typeparam> /// <param name="source">The source.</param> /// <param name="sliceLength">Maximum length of the slice.</param> /// <returns>lazy enumerator of the collection of arrays</returns> public static IEnumerable<TItem[]> Slice<TItem>(IEnumerable<TItem> source, int sliceLength) { if (source == null) throw new ArgumentNullException("source"); if (sliceLength <= 0) throw new ArgumentOutOfRangeException("sliceLength", "value must be greater than 0"); var list = new List<TItem>(sliceLength); foreach (var item in source) { list.Add(item); if (sliceLength == list.Count) { yield return list.ToArray(); list.Clear(); } } if (list.Count > 0) yield return list.ToArray(); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Azure/TableStorageProvider.cs
C#
bsd
30,326
#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.IO; using System.Linq; using System.Runtime.Serialization; using System.Xml.Linq; using Lokad.Cloud.Storage.Shared.Diagnostics; using Lokad.Cloud.Storage.Shared.Logging; using Lokad.Cloud.Storage.Shared.Policies; using Lokad.Diagnostics; using Lokad.Cloud.Storage.Shared; using Microsoft.WindowsAzure.StorageClient; namespace Lokad.Cloud.Storage.Azure { /// <summary>Provides access to the Queue Storage (plus the Blob Storage when /// messages are overflowing).</summary> /// <remarks> /// <para> /// Overflowing messages are stored in blob storage and normally deleted as with /// their originating correspondence in queue storage. /// </para> /// <para>All the methods of <see cref="QueueStorageProvider"/> are thread-safe.</para> /// </remarks> public class QueueStorageProvider : IQueueStorageProvider, IDisposable { internal const string OverflowingMessagesContainerName = "lokad-cloud-overflowing-messages"; internal const string PoisonedMessagePersistenceStoreName = "failing-messages"; /// <summary>Root used to synchronize accesses to <c>_inprocess</c>. /// Caution: do not hold the lock while performing operations on the cloud /// storage.</summary> readonly object _sync = new object(); readonly CloudQueueClient _queueStorage; readonly IBlobStorageProvider _blobStorage; readonly IDataSerializer _serializer; readonly IRuntimeFinalizer _runtimeFinalizer; readonly ActionPolicy _azureServerPolicy; readonly ILog _log; // Instrumentation readonly ExecutionCounter _countGetMessage; readonly ExecutionCounter _countPutMessage; readonly ExecutionCounter _countDeleteMessage; readonly ExecutionCounter _countAbandonMessage; readonly ExecutionCounter _countPersistMessage; readonly ExecutionCounter _countWrapMessage; readonly ExecutionCounter _countUnwrapMessage; // messages currently being processed (boolean property indicates if the message is overflowing) /// <summary>Mapping object --> Queue Message Id. Use to delete messages afterward.</summary> readonly Dictionary<object, InProcessMessage> _inProcessMessages; /// <summary>IoC constructor.</summary> /// <param name="blobStorage">Not null.</param> /// <param name="queueStorage">Not null.</param> /// <param name="serializer">Not null.</param> /// <param name="runtimeFinalizer">May be null (handy for strict O/C mapper /// scenario).</param> /// <param name="log">Optional log</param> public QueueStorageProvider( CloudQueueClient queueStorage, IBlobStorageProvider blobStorage, IDataSerializer serializer, IRuntimeFinalizer runtimeFinalizer, ILog log = null) { _queueStorage = queueStorage; _blobStorage = blobStorage; _serializer = serializer; _runtimeFinalizer = runtimeFinalizer; _log = log; // finalizer can be null in a strict O/C mapper scenario if(null != _runtimeFinalizer) { // self-registration for finalization _runtimeFinalizer.Register(this); } _azureServerPolicy = AzurePolicies.TransientServerErrorBackOff; _inProcessMessages = new Dictionary<object, InProcessMessage>(20); // Instrumentation ExecutionCounters.Default.RegisterRange(new[] { _countGetMessage = new ExecutionCounter("QueueStorageProvider.Get", 0, 0), _countPutMessage = new ExecutionCounter("QueueStorageProvider.PutSingle", 0, 0), _countDeleteMessage = new ExecutionCounter("QueueStorageProvider.DeleteSingle", 0, 0), _countAbandonMessage = new ExecutionCounter("QueueStorageProvider.AbandonSingle", 0, 0), _countPersistMessage = new ExecutionCounter("QueueStorageProvider.PersistSingle", 0, 0), _countWrapMessage = new ExecutionCounter("QueueStorageProvider.WrapSingle", 0, 0), _countUnwrapMessage = new ExecutionCounter("QueueStorageProvider.UnwrapSingle", 0, 0), }); } /// <summary> /// Disposing the provider will cause an abandon on all currently messages currently /// in-process. At the end of the life-cycle of the provider, normally there is no /// message in-process. /// </summary> public void Dispose() { AbandonRange(_inProcessMessages.Keys.ToArray()); } public IEnumerable<string> List(string prefix) { return _queueStorage.ListQueues(prefix).Select(queue => queue.Name); } public IEnumerable<T> Get<T>(string queueName, int count, TimeSpan visibilityTimeout, int maxProcessingTrials) { var timestamp = _countGetMessage.Open(); var queue = _queueStorage.GetQueueReference(queueName); // 1. GET RAW MESSAGES IEnumerable<CloudQueueMessage> rawMessages; try { rawMessages = _azureServerPolicy.Get(() => queue.GetMessages(count, visibilityTimeout)); } catch (StorageClientException ex) { // if the queue does not exist return an empty collection. if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return new T[0]; } throw; } // 2. SKIP EMPTY QUEUE if (null == rawMessages) { _countGetMessage.Close(timestamp); return new T[0]; } // 3. DESERIALIZE MESSAGE OR MESSAGE WRAPPER, CHECK-OUT var messages = new List<T>(count); var wrappedMessages = new List<MessageWrapper>(); lock (_sync) { foreach (var rawMessage in rawMessages) { // 3.1. DESERIALIZE MESSAGE, CHECK-OUT, COLLECT WRAPPED MESSAGES TO BE UNWRAPPED LATER var data = rawMessage.AsBytes; var stream = new MemoryStream(data); try { var dequeueCount = rawMessage.DequeueCount; // 3.1.1 UNPACK ENVELOPE IF PACKED, UPDATE POISONING INDICATOR var messageAsEnvelope = _serializer.TryDeserializeAs<MessageEnvelope>(stream); if (messageAsEnvelope.IsSuccess) { stream.Dispose(); dequeueCount += messageAsEnvelope.Value.DequeueCount; data = messageAsEnvelope.Value.RawMessage; stream = new MemoryStream(data); } // 3.1.2 PERSIST POISONED MESSAGE, SKIP if (dequeueCount > maxProcessingTrials) { // we want to persist the unpacked message (no envelope) but still need to drop // the original message, that's why we pass the original rawMessage but the unpacked data PersistRawMessage(rawMessage, data, queueName, PoisonedMessagePersistenceStoreName, String.Format("Message was dequeued {0} times but failed processing each time.", dequeueCount - 1)); if (_log != null) { _log.WarnFormat("Cloud Storage: A message of type {0} in queue {1} failed to process repeatedly and has been quarantined.", typeof(T).Name, queueName); } continue; } // 3.1.3 DESERIALIZE MESSAGE IF POSSIBLE var messageAsT = _serializer.TryDeserializeAs<T>(stream); if (messageAsT.IsSuccess) { messages.Add(messageAsT.Value); CheckOutMessage(messageAsT.Value, rawMessage, data, queueName, false, dequeueCount); continue; } // 3.1.4 DESERIALIZE WRAPPER IF POSSIBLE var messageAsWrapper = _serializer.TryDeserializeAs<MessageWrapper>(stream); if (messageAsWrapper.IsSuccess) { // we don't retrieve messages while holding the lock wrappedMessages.Add(messageAsWrapper.Value); CheckOutMessage(messageAsWrapper.Value, rawMessage, data, queueName, true, dequeueCount); continue; } // 3.1.5 PERSIST FAILED MESSAGE, SKIP // we want to persist the unpacked message (no envelope) but still need to drop // the original message, that's why we pass the original rawMessage but the unpacked data PersistRawMessage(rawMessage, data, queueName, PoisonedMessagePersistenceStoreName, String.Format("Message failed to deserialize:\r\nAs {0}:\r\n{1}\r\n\r\nAs MessageEnvelope:\r\n{2}\r\n\r\nAs MessageWrapper:\r\n{3}", typeof (T).FullName, messageAsT.Error, messageAsEnvelope.IsSuccess ? "unwrapped" : messageAsEnvelope.Error.ToString(), messageAsWrapper.Error)); if (_log != null) { _log.WarnFormat(messageAsT.Error, "Cloud Storage: A message in queue {0} failed to deserialize to type {1} and has been quarantined.", queueName, typeof(T).Name); } } finally { stream.Dispose(); } } } // 4. UNWRAP WRAPPED MESSAGES foreach (var mw in wrappedMessages) { var unwrapTimestamp = _countUnwrapMessage.Open(); string ignored; var blobContent = _blobStorage.GetBlob(mw.ContainerName, mw.BlobName, typeof(T), out ignored); // blob may not exists in (rare) case of failure just before queue deletion // but after container deletion (or also timeout deletion). if (!blobContent.HasValue) { CloudQueueMessage rawMessage; lock (_sync) { rawMessage = _inProcessMessages[mw].RawMessages[0]; CheckInMessage(mw); } DeleteRawMessage(rawMessage, queue); // skipping the message if it can't be unwrapped continue; } T innerMessage = (T)blobContent.Value; // substitution: message wrapper replaced by actual item in '_inprocess' list CheckOutRelink(mw, innerMessage); messages.Add(innerMessage); _countUnwrapMessage.Close(unwrapTimestamp); } _countGetMessage.Close(timestamp); // 5. RETURN LIST OF MESSAGES return messages; } public void Put<T>(string queueName, T message) { PutRange(queueName, new[] { message }); } public void PutRange<T>(string queueName, IEnumerable<T> messages) { var queue = _queueStorage.GetQueueReference(queueName); foreach (var message in messages) { var timestamp = _countPutMessage.Open(); using (var stream = new MemoryStream()) { _serializer.Serialize(message, stream); // Caution: MaxMessageSize is not related to the number of bytes // but the number of characters when Base64-encoded: CloudQueueMessage queueMessage; if (stream.Length >= (CloudQueueMessage.MaxMessageSize - 1) / 4 * 3) { queueMessage = new CloudQueueMessage(PutOverflowingMessageAndWrap(queueName, message)); } else { try { queueMessage = new CloudQueueMessage(stream.ToArray()); } catch (ArgumentException) { queueMessage = new CloudQueueMessage(PutOverflowingMessageAndWrap(queueName, message)); } } PutRawMessage(queueMessage, queue); } _countPutMessage.Close(timestamp); } } byte[] PutOverflowingMessageAndWrap<T>(string queueName, T message) { var timestamp = _countWrapMessage.Open(); var blobRef = OverflowingMessageBlobName<T>.GetNew(queueName); // HACK: In this case serialization is performed another time (internally) _blobStorage.PutBlob(blobRef, message); var mw = new MessageWrapper { ContainerName = blobRef.ContainerName, BlobName = blobRef.ToString() }; using (var stream = new MemoryStream()) { _serializer.Serialize(mw, stream); var serializerWrapper = stream.ToArray(); _countWrapMessage.Close(timestamp); return serializerWrapper; } } void DeleteOverflowingMessages(string queueName) { _blobStorage.DeleteAllBlobs(OverflowingMessagesContainerName, queueName); } public void Clear(string queueName) { try { // caution: call 'DeleteOverflowingMessages' first (BASE). DeleteOverflowingMessages(queueName); var queue = _queueStorage.GetQueueReference(queueName); _azureServerPolicy.Do(queue.Clear); } catch (StorageClientException ex) { // if the queue does not exist do nothing if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return; } throw; } } public bool Delete<T>(T message) { return DeleteRange(new[] { message }) > 0; } public int DeleteRange<T>(IEnumerable<T> messages) { int deletionCount = 0; foreach (var message in messages) { var timestamp = _countDeleteMessage.Open(); // 1. GET RAW MESSAGE & QUEUE, OR SKIP IF NOT AVAILABLE/ALREADY DELETED CloudQueueMessage rawMessage; string queueName; bool isOverflowing; byte[] data; lock (_sync) { // ignoring message if already deleted InProcessMessage inProcMsg; if (!_inProcessMessages.TryGetValue(message, out inProcMsg)) { continue; } rawMessage = inProcMsg.RawMessages[0]; isOverflowing = inProcMsg.IsOverflowing; queueName = inProcMsg.QueueName; data = inProcMsg.Data; } var queue = _queueStorage.GetQueueReference(queueName); // 2. DELETING THE OVERFLOW BLOB, IF WRAPPED if (isOverflowing) { var messageWrapper = _serializer.TryDeserializeAs<MessageWrapper>(data); if (messageWrapper.IsSuccess) { _blobStorage.DeleteBlobIfExist(messageWrapper.Value.ContainerName, messageWrapper.Value.BlobName); } else if (_log != null) { _log.WarnFormat(messageWrapper.Error, "Cloud Storage: The overflowing part of a corrupt message in queue {0} could not be identified and may have not been deleted while deleting the message itself.", queueName); } } // 3. DELETE THE MESSAGE FROM THE QUEUE if(DeleteRawMessage(rawMessage, queue)) { deletionCount++; } // 4. REMOVE THE RAW MESSAGE CheckInMessage(message); _countDeleteMessage.Close(timestamp); } return deletionCount; } public bool Abandon<T>(T message) { return AbandonRange(new[] { message }) > 0; } public int AbandonRange<T>(IEnumerable<T> messages) { int abandonCount = 0; foreach (var message in messages) { var timestamp = _countAbandonMessage.Open(); // 1. GET RAW MESSAGE & QUEUE, OR SKIP IF NOT AVAILABLE/ALREADY DELETED CloudQueueMessage oldRawMessage; string queueName; int dequeueCount; byte[] data; lock (_sync) { // ignoring message if already deleted InProcessMessage inProcMsg; if (!_inProcessMessages.TryGetValue(message, out inProcMsg)) { continue; } queueName = inProcMsg.QueueName; dequeueCount = inProcMsg.DequeueCount; oldRawMessage = inProcMsg.RawMessages[0]; data = inProcMsg.Data; } var queue = _queueStorage.GetQueueReference(queueName); // 2. CLONE THE MESSAGE AND PUT IT TO THE QUEUE // we always use an envelope here since the dequeue count // is always >0, which we should continue to track in order // to make poison detection possible at all. var envelope = new MessageEnvelope { DequeueCount = dequeueCount, RawMessage = data }; CloudQueueMessage newRawMessage = null; using (var stream = new MemoryStream()) { _serializer.Serialize(envelope, stream); if (stream.Length < (CloudQueueMessage.MaxMessageSize - 1)/4*3) { try { newRawMessage = new CloudQueueMessage(stream.ToArray()); } catch (ArgumentException) { } } if (newRawMessage == null) { envelope.RawMessage = PutOverflowingMessageAndWrap(queueName, message); using (var wrappedStream = new MemoryStream()) { _serializer.Serialize(envelope, wrappedStream); newRawMessage = new CloudQueueMessage(wrappedStream.ToArray()); } } } PutRawMessage(newRawMessage, queue); // 3. DELETE THE OLD MESSAGE FROM THE QUEUE if(DeleteRawMessage(oldRawMessage, queue)) { abandonCount++; } // 4. REMOVE THE RAW MESSAGE CheckInMessage(message); _countAbandonMessage.Close(timestamp); } return abandonCount; } public bool ResumeLater<T>(T message) { string queueName; lock (_sync) { // ignoring message if already deleted InProcessMessage inProcMsg; if (!_inProcessMessages.TryGetValue(message, out inProcMsg)) { return false; } queueName = inProcMsg.QueueName; } Put(queueName, message); return Delete(message); } public int ResumeLaterRange<T>(IEnumerable<T> messages) { return messages.Count(ResumeLater); } public void Persist<T>(T message, string storeName, string reason) { PersistRange(new[] { message }, storeName, reason); } public void PersistRange<T>(IEnumerable<T> messages, string storeName, string reason) { foreach (var message in messages) { // 1. GET MESSAGE FROM CHECK-OUT, SKIP IF NOT AVAILABLE/ALREADY DELETED CloudQueueMessage rawMessage; string queueName; byte[] data; lock (_sync) { // ignoring message if already deleted InProcessMessage inProcessMessage; if (!_inProcessMessages.TryGetValue(message, out inProcessMessage)) { continue; } queueName = inProcessMessage.QueueName; rawMessage = inProcessMessage.RawMessages[0]; data = inProcessMessage.Data; } // 2. PERSIST MESSAGE AND DELETE FROM QUEUE PersistRawMessage(rawMessage, data, queueName, storeName, reason); // 3. REMOVE MESSAGE FROM CHECK-OUT CheckInMessage(message); } } public IEnumerable<string> ListPersisted(string storeName) { var blobPrefix = PersistedMessageBlobName.GetPrefix(storeName); return _blobStorage.ListBlobNames(blobPrefix).Select(blobReference => blobReference.Key); } public Maybe<PersistedMessage> GetPersisted(string storeName, string key) { // 1. GET PERSISTED MESSAGE BLOB var blobReference = new PersistedMessageBlobName(storeName, key); var blob = _blobStorage.GetBlob(blobReference); if (!blob.HasValue) { return Maybe<PersistedMessage>.Empty; } var persistedMessage = blob.Value; var data = persistedMessage.Data; var dataXml = Maybe<XElement>.Empty; // 2. IF WRAPPED, UNWRAP; UNPACK XML IF SUPPORTED bool dataForRestorationAvailable; var messageWrapper = _serializer.TryDeserializeAs<MessageWrapper>(data); if (messageWrapper.IsSuccess) { string ignored; dataXml = _blobStorage.GetBlobXml(messageWrapper.Value.ContainerName, messageWrapper.Value.BlobName, out ignored); // We consider data to be available only if we can access its blob's data // Simplification: we assume that if we can get the data as xml, then we can also get its binary data dataForRestorationAvailable = dataXml.HasValue; } else { var intermediateSerializer = _serializer as IIntermediateDataSerializer; if (intermediateSerializer != null) { using (var stream = new MemoryStream(data)) { var unpacked = intermediateSerializer.TryUnpackXml(stream); dataXml = unpacked.IsSuccess ? unpacked.Value : Maybe<XElement>.Empty; } } // The message is not wrapped (or unwrapping it failed). // No matter whether we can get the xml, we do have access to the binary data dataForRestorationAvailable = true; } // 3. RETURN return new PersistedMessage { QueueName = persistedMessage.QueueName, StoreName = storeName, Key = key, InsertionTime = persistedMessage.InsertionTime, PersistenceTime = persistedMessage.PersistenceTime, DequeueCount = persistedMessage.DequeueCount, Reason = persistedMessage.Reason, DataXml = dataXml, IsDataAvailable = dataForRestorationAvailable, }; } public void DeletePersisted(string storeName, string key) { // 1. GET PERSISTED MESSAGE BLOB var blobReference = new PersistedMessageBlobName(storeName, key); var blob = _blobStorage.GetBlob(blobReference); if (!blob.HasValue) { return; } var persistedMessage = blob.Value; // 2. IF WRAPPED, UNWRAP AND DELETE BLOB var messageWrapper = _serializer.TryDeserializeAs<MessageWrapper>(persistedMessage.Data); if (messageWrapper.IsSuccess) { _blobStorage.DeleteBlobIfExist(messageWrapper.Value.ContainerName, messageWrapper.Value.BlobName); } // 3. DELETE PERSISTED MESSAGE _blobStorage.DeleteBlobIfExist(blobReference); } public void RestorePersisted(string storeName, string key) { // 1. GET PERSISTED MESSAGE BLOB var blobReference = new PersistedMessageBlobName(storeName, key); var blob = _blobStorage.GetBlob(blobReference); if(!blob.HasValue) { return; } var persistedMessage = blob.Value; // 2. PUT MESSAGE TO QUEUE var queue = _queueStorage.GetQueueReference(persistedMessage.QueueName); var rawMessage = new CloudQueueMessage(persistedMessage.Data); PutRawMessage(rawMessage, queue); // 3. DELETE PERSISTED MESSAGE _blobStorage.DeleteBlobIfExist(blobReference); } void PersistRawMessage(CloudQueueMessage message, byte[] data, string queueName, string storeName, string reason) { var timestamp = _countPersistMessage.Open(); var queue = _queueStorage.GetQueueReference(queueName); // 1. PERSIST MESSAGE TO BLOB var blobReference = PersistedMessageBlobName.GetNew(storeName); var persistedMessage = new PersistedMessageData { QueueName = queueName, InsertionTime = message.InsertionTime.Value, PersistenceTime = DateTimeOffset.UtcNow, DequeueCount = message.DequeueCount, Reason = reason, Data = data, }; _blobStorage.PutBlob(blobReference, persistedMessage); // 2. DELETE MESSAGE FROM QUEUE DeleteRawMessage(message, queue); _countPersistMessage.Close(timestamp); } bool DeleteRawMessage(CloudQueueMessage message, CloudQueue queue) { try { _azureServerPolicy.Do(() => queue.DeleteMessage(message)); return true; } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return false; } var info = ex.ExtendedErrorInformation; if (info == null) { throw; } if (info.ErrorCode == QueueErrorCodeStrings.PopReceiptMismatch) { if (_log != null) { _log.WarnFormat("Cloud Storage: A message to be deleted in queue {0} was already remotely deleted or the invisibility timeout has elapsed.", queue.Name); } return false; } if (info.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return false; } throw; } } void PutRawMessage(CloudQueueMessage message, CloudQueue queue) { try { _azureServerPolicy.Do(() => queue.AddMessage(message)); } catch (StorageClientException ex) { // HACK: not storage status error code yet if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { // It usually takes time before the queue gets available // (the queue might also have been freshly deleted). AzurePolicies.SlowInstantiation.Do(() => { queue.Create(); queue.AddMessage(message); }); } else { throw; } } } void CheckOutMessage(object message, CloudQueueMessage rawMessage, byte[] data, string queueName, bool isOverflowing, int dequeueCount) { lock (_sync) { // If T is a value type, _inprocess could already contain the message // (not the same exact instance, but an instance that is value-equal to this one) InProcessMessage inProcessMessage; if (!_inProcessMessages.TryGetValue(message, out inProcessMessage)) { inProcessMessage = new InProcessMessage { QueueName = queueName, RawMessages = new List<CloudQueueMessage> {rawMessage}, Data = data, IsOverflowing = isOverflowing, DequeueCount = dequeueCount }; _inProcessMessages.Add(message, inProcessMessage); } else { inProcessMessage.RawMessages.Add(rawMessage); } } } void CheckOutRelink(object originalMessage, object newMessage) { lock (_sync) { var inProcessMessage = _inProcessMessages[originalMessage]; _inProcessMessages.Remove(originalMessage); _inProcessMessages.Add(newMessage, inProcessMessage); } } void CheckInMessage(object message) { lock (_sync) { var inProcessMessage = _inProcessMessages[message]; inProcessMessage.RawMessages.RemoveAt(0); if (0 == inProcessMessage.RawMessages.Count) { _inProcessMessages.Remove(message); } } } /// <summary> /// Deletes a queue. /// </summary> /// <returns><c>true</c> if the queue name has been actually deleted.</returns> /// <remarks> /// This implementation takes care of deleting overflowing blobs as /// well. /// </remarks> public bool DeleteQueue(string queueName) { try { // Caution: call to 'DeleteOverflowingMessages' comes first (BASE). DeleteOverflowingMessages(queueName); var queue = _queueStorage.GetQueueReference(queueName); _azureServerPolicy.Do(queue.Delete); return true; } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return false; } throw; } } /// <summary> /// Gets the approximate number of items in this queue. /// </summary> public int GetApproximateCount(string queueName) { try { var queue = _queueStorage.GetQueueReference(queueName); return _azureServerPolicy.Get(queue.RetrieveApproximateMessageCount); } catch (StorageClientException ex) { // if the queue does not exist, return 0 (no queue) if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return 0; } throw; } } /// <summary> /// Gets the approximate age of the top message of this queue. /// </summary> public Maybe<TimeSpan> GetApproximateLatency(string queueName) { var queue = _queueStorage.GetQueueReference(queueName); CloudQueueMessage rawMessage; try { rawMessage = _azureServerPolicy.Get(queue.PeekMessage); } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return Maybe<TimeSpan>.Empty; } throw; } if(rawMessage == null || !rawMessage.InsertionTime.HasValue) { return Maybe<TimeSpan>.Empty; } var latency = DateTimeOffset.UtcNow - rawMessage.InsertionTime.Value; // don't return negative values when clocks are slightly out of sync return latency > TimeSpan.Zero ? latency : TimeSpan.Zero; } } /// <summary>Represents a set of value-identical messages that are being processed by workers, /// i.e. were hidden from the queue because of calls to Get{T}.</summary> internal class InProcessMessage { /// <summary>Name of the queue where messages are originating from.</summary> public string QueueName { get; set; } /// <summary> /// The multiple, different raw <see cref="CloudQueueMessage" /> /// objects as returned from the queue storage. /// </summary> public List<CloudQueueMessage> RawMessages { get; set; } /// <summary> /// The unpacked message data. Can still be a message wrapper, but never an envelope. /// </summary> public byte[] Data { get; set; } /// <summary> /// A flag indicating whether the original message was bigger than the max /// allowed size and was therefore wrapped in <see cref="MessageWrapper" />. /// </summary> public bool IsOverflowing { get; set; } /// <summary> /// The number of times this message has already been dequeued, /// so we can track it safely even when abandoning it later /// </summary> public int DequeueCount { get; set; } } internal class OverflowingMessageBlobName<T> : BlobName<T> { public override string ContainerName { get { return QueueStorageProvider.OverflowingMessagesContainerName; } } /// <summary>Indicates the name of the queue where the message has been originally pushed.</summary> [Rank(0)] public string QueueName; /// <summary>Message identifiers as specified by the queue storage itself.</summary> [Rank(1)] public Guid MessageId; OverflowingMessageBlobName(string queueName, Guid guid) { QueueName = queueName; MessageId = guid; } /// <summary>Used to iterate over all the overflowing messages /// associated to a queue.</summary> public static OverflowingMessageBlobName<T> GetNew(string queueName) { return new OverflowingMessageBlobName<T>(queueName, Guid.NewGuid()); } } [DataContract] internal class PersistedMessageData { [DataMember(Order = 1)] public string QueueName { get; set; } [DataMember(Order = 2)] public DateTimeOffset InsertionTime { get; set; } [DataMember(Order = 3)] public DateTimeOffset PersistenceTime { get; set; } [DataMember(Order = 4)] public int DequeueCount { get; set; } [DataMember(Order = 5, IsRequired = false)] public string Reason { get; set; } [DataMember(Order = 6)] public byte[] Data { get; set; } } internal class PersistedMessageBlobName : BlobName<PersistedMessageData> { public override string ContainerName { get { return "lokad-cloud-persisted-messages"; } } /// <summary>Indicates the name of the swap out store where the message is persisted.</summary> [Rank(0)] public string StoreName; [Rank(1)] public string Key; public PersistedMessageBlobName(string storeName, string key) { StoreName = storeName; Key = key; } public static PersistedMessageBlobName GetNew(string storeName, string key) { return new PersistedMessageBlobName(storeName, key); } public static PersistedMessageBlobName GetNew(string storeName) { return new PersistedMessageBlobName(storeName, Guid.NewGuid().ToString("N")); } public static PersistedMessageBlobName GetPrefix(string storeName) { return new PersistedMessageBlobName(storeName, null); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Azure/QueueStorageProvider.cs
C#
bsd
40,416
#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.Linq; using System.Data.Services.Client; using System.Net; using System.Text.RegularExpressions; using System.Threading; using Lokad.Cloud.Storage.Shared.Diagnostics; using Lokad.Diagnostics; using Microsoft.WindowsAzure.StorageClient; using Lokad.Cloud.Storage.Shared.Policies; namespace Lokad.Cloud.Storage.Azure { /// <summary> /// Azure retry policies for corner-situation and server errors. /// </summary> public static class AzurePolicies { /// <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 Shared.Policies.ActionPolicy TransientServerErrorBackOff { get; private set; } /// <summary>Similar to <see cref="TransientServerErrorBackOff"/>, yet /// the Table Storage comes with its own set or exceptions/.</summary> public static Shared.Policies.ActionPolicy TransientTableErrorBackOff { get; private set; } /// <summary> /// Very patient retry policy to deal with container, queue or table instantiation /// that happens just after a deletion. /// </summary> public static Shared.Policies.ActionPolicy SlowInstantiation { get; private set; } /// <summary> /// Limited retry related to MD5 validation failure. /// </summary> public static Shared.Policies.ActionPolicy NetworkCorruption { get; private set; } /// <summary> /// Retry policy for optimistic concurrency retrials. The exception parameter is ignored, it can be null. /// </summary> public static ShouldRetry OptimisticConcurrency() { var random = new Random(); return delegate(int currentRetryCount, Exception lastException, out TimeSpan retryInterval) { retryInterval = TimeSpan.FromMilliseconds(random.Next(Math.Min(10000, 10 + currentRetryCount * currentRetryCount * 10))); return currentRetryCount <= 30; }; } // Instrumentation static readonly ExecutionCounter CountOnTransientServerError; static readonly ExecutionCounter CountOnTransientTableError; static readonly ExecutionCounter CountOnSlowInstantiation; static readonly ExecutionCounter CountOnNetworkCorruption; /// <summary> /// Static Constructor /// </summary> static AzurePolicies() { // Instrumentation ExecutionCounters.Default.RegisterRange(new[] { CountOnTransientServerError = new ExecutionCounter("Policies.ServerErrorRetryWait", 0, 0), CountOnTransientTableError = new ExecutionCounter("Policies.TableErrorRetryWait", 0, 0), CountOnSlowInstantiation = new ExecutionCounter("Policies.SlowInstantiationRetryWait", 0, 0), CountOnNetworkCorruption = new ExecutionCounter("Policies.NetworkCorruption", 0, 0) }); // Initialize Policies TransientServerErrorBackOff = Shared.Policies.ActionPolicy.With(TransientServerErrorExceptionFilter) .Retry(30, OnTransientServerErrorRetry); TransientTableErrorBackOff = Shared.Policies.ActionPolicy.With(TransientTableErrorExceptionFilter) .Retry(30, OnTransientTableErrorRetry); SlowInstantiation = Shared.Policies.ActionPolicy.With(SlowInstantiationExceptionFilter) .Retry(30, OnSlowInstantiationRetry); NetworkCorruption = Shared.Policies.ActionPolicy.With(NetworkCorruptionExceptionFilter) .Retry(2, OnNetworkCorruption); } static void OnTransientServerErrorRetry(Exception exception, int count) { // NOTE: we can't log here, since logging would fail as well var timestamp = CountOnTransientServerError.Open(); // quadratic backoff, capped at 5 minutes var c = count + 1; Thread.Sleep(TimeSpan.FromSeconds(Math.Min(300, c*c))); CountOnTransientServerError.Close(timestamp); } static void OnTransientTableErrorRetry(Exception exception, int count) { // NOTE: we can't log here, since logging would fail as well var timestamp = CountOnTransientTableError.Open(); // quadratic backoff, capped at 5 minutes var c = count + 1; Thread.Sleep(TimeSpan.FromSeconds(Math.Min(300, c * c))); CountOnTransientTableError.Close(timestamp); } static void OnSlowInstantiationRetry(Exception exception, int count) { var timestamp = CountOnSlowInstantiation.Open(); // linear backoff Thread.Sleep(TimeSpan.FromMilliseconds(100 * count)); CountOnSlowInstantiation.Close(timestamp); } static void OnNetworkCorruption(Exception exception, int count) { var timestamp = CountOnNetworkCorruption.Open(); // no backoff, retry immediately CountOnNetworkCorruption.Close(timestamp); } static bool IsErrorCodeMatch(StorageException exception, params StorageErrorCode[] codes) { return exception != null && codes.Contains(exception.ErrorCode); } static bool IsErrorStringMatch(StorageException exception, params string[] errorStrings) { return exception != null && exception.ExtendedErrorInformation != null && errorStrings.Contains(exception.ExtendedErrorInformation.ErrorCode); } static bool IsErrorStringMatch(string exceptionErrorString, params string[] errorStrings) { return errorStrings.Contains(exceptionErrorString); } static bool TransientServerErrorExceptionFilter(Exception exception) { var serverException = exception as StorageServerException; if (serverException != null) { if (IsErrorCodeMatch(serverException, StorageErrorCode.ServiceInternalError, StorageErrorCode.ServiceTimeout)) { return true; } if (IsErrorStringMatch(serverException, StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, StorageErrorCodeStrings.OperationTimedOut)) { return true; } return false; } // HACK: StorageClient does not catch internal errors very well. // Hence we end up here manually catching exception that should have been correctly // typed by the StorageClient: // System.Net.InternalException is internal, but uncaught on some race conditions. // We therefore assume this is a transient error and retry. var exceptionType = exception.GetType(); if (exceptionType.FullName == "System.Net.InternalException") { return true; } return false; } static bool TransientTableErrorExceptionFilter(Exception exception) { var dataServiceRequestException = exception as DataServiceRequestException; if (dataServiceRequestException != null) { if (IsErrorStringMatch(GetErrorCode(dataServiceRequestException), StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, StorageErrorCodeStrings.OperationTimedOut, TableErrorCodeStrings.TableServerOutOfMemory)) { return true; } } var dataServiceQueryException = exception as DataServiceQueryException; if (dataServiceQueryException != null) { if (IsErrorStringMatch(GetErrorCode(dataServiceQueryException), StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, StorageErrorCodeStrings.OperationTimedOut, TableErrorCodeStrings.TableServerOutOfMemory)) { return true; } } // HACK: StorageClient does not catch internal errors very well. // Hence we end up here manually catching exception that should have been correctly // typed by the StorageClient: // The remote server returned an error: (500) Internal Server Error. var webException = exception as WebException; if (null != webException && (webException.Status == WebExceptionStatus.ProtocolError || webException.Status == WebExceptionStatus.ConnectionClosed)) { return true; } // System.Net.InternalException is internal, but uncaught on some race conditions. // We therefore assume this is a transient error and retry. var exceptionType = exception.GetType(); if (exceptionType.FullName == "System.Net.InternalException") { return true; } return false; } static bool SlowInstantiationExceptionFilter(Exception exception) { var storageException = exception as StorageClientException; // Blob Storage or Queue Storage exceptions // Table Storage may throw exception of type 'StorageClientException' if (storageException != null) { // 'client' exceptions reflect server-side problems (delayed instantiation) if (IsErrorCodeMatch(storageException, StorageErrorCode.ResourceNotFound, StorageErrorCode.ContainerNotFound)) { return true; } if (IsErrorStringMatch(storageException, QueueErrorCodeStrings.QueueNotFound, QueueErrorCodeStrings.QueueBeingDeleted, StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, TableErrorCodeStrings.TableServerOutOfMemory, TableErrorCodeStrings.TableNotFound, TableErrorCodeStrings.TableBeingDeleted)) { return true; } } // Table Storage may also throw exception of type 'DataServiceQueryException'. var dataServiceException = exception as DataServiceQueryException; if (null != dataServiceException) { if (IsErrorStringMatch(GetErrorCode(dataServiceException), TableErrorCodeStrings.TableBeingDeleted, TableErrorCodeStrings.TableNotFound, TableErrorCodeStrings.TableServerOutOfMemory)) { return true; } } return false; } static bool NetworkCorruptionExceptionFilter(Exception exception) { // Upload MD5 mismatch var clientException = exception as StorageClientException; if (clientException != null && clientException.ErrorCode == StorageErrorCode.BadRequest && clientException.ExtendedErrorInformation != null && clientException.ExtendedErrorInformation.ErrorCode == StorageErrorCodeStrings.InvalidHeaderValue && clientException.ExtendedErrorInformation.AdditionalDetails["HeaderName"] == "Content-MD5") { // network transport corruption (automatic), try again return true; } // Download MD5 mismatch if (exception is DataCorruptionException) { // network transport corruption (manual), try again return true; } return false; } public static string GetErrorCode(DataServiceRequestException ex) { var r = new Regex(@"<code>(\w+)</code>", RegexOptions.IgnoreCase); var match = r.Match(ex.InnerException.Message); return match.Groups[1].Value; } // HACK: just dupplicating the other overload of 'GetErrorCode' public static string GetErrorCode(DataServiceQueryException ex) { var r = new Regex(@"<code>(\w+)</code>", RegexOptions.IgnoreCase); var match = r.Match(ex.InnerException.Message); return match.Groups[1].Value; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Azure/AzurePolicies.cs
C#
bsd
13,683
#region Copyright (c) Lokad 2010-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.IO; using System.Linq; using Lokad.Cloud.Storage.Shared; using Microsoft.WindowsAzure.StorageClient; namespace Lokad.Cloud.Storage.Azure { /// <summary>This entity is basically a workaround the 64KB limitation /// for entity properties. 15 properties represents a total storage /// capability of 960KB (entity limit is at 1024KB).</summary> /// <remarks>This class is basically a hack against the Table Storage /// to work-around the 64KB limitation for properties.</remarks> public class FatEntity : TableServiceEntity { /// <summary> /// Maximal entity size is 1MB. Out of that, we keep only /// 960kb (1MB - 64kb as a safety margin). Then, it should be taken /// into account that byte[] are Base64 encoded which represent /// a penalty overhead of 4/3 - hence the reduced capacity. /// </summary> public const int MaxByteCapacity = (960 * 1024 * 3) / 4; // ReSharper disable InconsistentNaming // ReSharper disable MemberCanBePrivate.Global public byte[] P0 { get; set; } public byte[] P1 { get; set; } public byte[] P2 { get; set; } public byte[] P3 { get; set; } public byte[] P4 { get; set; } public byte[] P5 { get; set; } public byte[] P6 { get; set; } public byte[] P7 { get; set; } public byte[] P8 { get; set; } public byte[] P9 { get; set; } public byte[] P10 { get; set; } public byte[] P11 { get; set; } public byte[] P12 { get; set; } public byte[] P13 { get; set; } public byte[] P14 { get; set; } IEnumerable<byte[]> GetProperties() { if (null != P0) yield return P0; if (null != P1) yield return P1; if (null != P2) yield return P2; if (null != P3) yield return P3; if (null != P4) yield return P4; if (null != P5) yield return P5; if (null != P6) yield return P6; if (null != P7) yield return P7; if (null != P8) yield return P8; if (null != P9) yield return P9; if (null != P10) yield return P10; if (null != P11) yield return P11; if (null != P12) yield return P12; if (null != P13) yield return P13; if (null != P14) yield return P14; } public byte[] GetData() { var arrays = GetProperties().ToArray(); var buffer = new byte[arrays.Sum(a => a.Length)]; var i = 0; foreach (var array in arrays) { Buffer.BlockCopy(array, 0, buffer, i, array.Length); i += array.Length; } return buffer; } public void SetData(byte[] data) { if(null == data) throw new ArgumentNullException("data"); if(data.Length >= MaxByteCapacity) throw new ArgumentOutOfRangeException("data"); var setters = new Action<byte[]>[] { b => P0 = b, b => P1 = b, b => P2 = b, b => P3 = b, b => P4 = b, b => P5 = b, b => P6 = b, b => P7 = b, b => P8 = b, b => P9 = b, b => P10 = b, b => P11 = b, b => P12 = b, b => P13 = b, b => P14 = b, }; for (int i = 0; i < 15; i++) { if (i * 64 * 1024 < data.Length) { var start = i * 64 * 1024; var length = Math.Min(64 * 1024, data.Length - start); var buffer = new byte[length]; Buffer.BlockCopy(data, start, buffer, 0, buffer.Length); setters[i](buffer); } else { setters[i](null); // discarding potential leftover } } } /// <summary>Returns an upper bound approximation of the payload associated to /// the entity once serialized as XML Atom (used for communication with the /// Table Storage).</summary> public int GetPayload() { // measurements indicates overhead is closer to 1300 chars, but we take a bit of margin const int envelopOverhead = 1500; // Caution: there is a loss when converting byte[] to Base64 representation var binCharCount = (GetProperties().Sum(a => a.Length) * 4 + 3) / 3; var partitionKeyCount = PartitionKey.Length; var rowKeyCount = RowKey.Length; // timestamp is already accounted for in the envelop overhead. return binCharCount + partitionKeyCount + rowKeyCount + envelopOverhead; } /// <summary>Converts a <c>FatEntity</c> toward a <c>CloudEntity</c>.</summary> public static CloudEntity<T> Convert<T>(FatEntity fatEntity, IDataSerializer serializer, string etag) { using (var stream = new MemoryStream(fatEntity.GetData()) { Position = 0 }) { var val = (T)serializer.Deserialize(stream, typeof(T)); return new CloudEntity<T> { PartitionKey = fatEntity.PartitionKey, RowKey = fatEntity.RowKey, Timestamp = fatEntity.Timestamp, ETag = etag, Value = val }; } } /// <summary>Converts a <c>CloudEntity</c> toward a <c>FatEntity</c>.</summary> public static FatEntity Convert<T>(CloudEntity<T> cloudEntity, IDataSerializer serializer) { var fatEntity = new FatEntity { PartitionKey = cloudEntity.PartitionKey, RowKey = cloudEntity.RowKey, Timestamp = cloudEntity.Timestamp }; using (var stream = new MemoryStream()) { serializer.Serialize(cloudEntity.Value, stream); fatEntity.SetData(stream.ToArray()); return fatEntity; } } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Azure/FatEntity.cs
C#
bsd
6,799
// compile me with // csc /out:sample.dll /t:library sample.cs namespace Lokad.Example { public class MyClass { public string MyMethod() { return "foo"; } } }
zyyin2005-lokadclone
Test/Lokad.Cloud.Framework.Test/Sample/sample.cs
C#
bsd
181
using System; using System.Collections.Generic; using System.Linq; namespace Lokad.Cloud.Shared.Test { /// <summary> /// Helper class with shortcut methods for managing enumerations. /// Useful for inlining object generation in tests /// </summary> public static class Range { /// <summary> Returns empty enumerator </summary> /// <typeparam name="T">type of the item to enumerate</typeparam> /// <returns>singleton instance of the empty enumerator</returns> public static IEnumerable<T> Empty<T>() { return Enumerable.Empty<T>(); } /// <summary> /// returns enumeration from 0 with <paramref name="count"/> numbers /// </summary> /// <param name="count">Number of items to create</param> /// <returns>enumerable</returns> public static IEnumerable<int> Create(int count) { return Enumerable.Range(0, count); } /// <summary> /// Creates sequence of the integral numbers within the specified range /// </summary> /// <param name="start">The value of the first integer in sequence.</param> /// <param name="count">The number of values in the sequence.</param> /// <returns>sequence of the integral numbers within the specified range</returns> public static IEnumerable<int> Create(int start, int count) { return Enumerable.Range(start, count); } /// <summary> /// Creates sequence that consists of a repeated value. /// </summary> /// <typeparam name="TResult">The type of the value to repeat.</typeparam> /// <param name="item">The value to repeat.</param> /// <param name="count">The number of times to repeat.</param> /// <returns>sequence that consists of a repeated value</returns> public static IEnumerable<TResult> Repeat<TResult>(TResult item, int count) { return Enumerable.Repeat(item, count); } /// <summary> /// Creates the generator to iterate from 1 to <see cref="int.MaxValue"/>. /// </summary> /// <typeparam name="T">type of the item to generate</typeparam> /// <param name="generator">The generator.</param> /// <returns>new enumerator</returns> public static IEnumerable<T> Create<T>(Func<int, T> generator) { for (int i = 0; i < int.MaxValue; i++) { yield return generator(i); } throw new InvalidOperationException("Generator has reached the end"); } /// <summary> /// Creates the enumerable using the provided generator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="count">The count.</param> /// <param name="generator">The generator.</param> /// <returns>enumerable instance</returns> public static IEnumerable<T> Create<T>(int count, Func<int, T> generator) { for (int i = 0; i < count; i++) { yield return generator(i); } } /// <summary> /// Creates the enumerable using the provided generator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="count">The count.</param> /// <param name="generator">The generator.</param> /// <returns>enumerable instance</returns> public static IEnumerable<T> Create<T>(int count, Func<T> generator) { for (int i = 0; i < count; i++) { yield return generator(); } } /// <summary> /// Creates the array populated with the provided generator /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="count">The count.</param> /// <param name="generator">The generator.</param> /// <returns>array</returns> public static TValue[] Array<TValue>(int count, Func<int, TValue> generator) { if (generator == null) throw new ArgumentNullException("generator"); var array = new TValue[count]; for (int i = 0; i < array.Length; i++) { array[i] = generator(i); } return array; } /// <summary> /// Creates the array of integers /// </summary> /// <param name="count">The count.</param> /// <returns></returns> public static int[] Array(int count) { var array = new int[count]; for (int i = 0; i < array.Length; i++) { array[i] = i; } return array; } } }
zyyin2005-lokadclone
Test/Lokad.Cloud.Framework.Test/Shared/Range.cs
C#
bsd
4,978
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("Lokad.Cloud.Framework.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lokad.com")] [assembly: AssemblyProduct("Lokad.Cloud.Framework.Test")] [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("8a3d64f3-fa8f-4936-971f-c41712a8310e")] // 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-lokadclone
Test/Lokad.Cloud.Framework.Test/Properties/AssemblyInfo.cs
C#
bsd
1,478
#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 Autofac; using Autofac.Configuration; namespace Lokad.Cloud.Test { public sealed class GlobalSetup { static IContainer _container; static IContainer Setup() { var builder = new ContainerBuilder(); builder.RegisterModule(new CloudModule()); builder.RegisterModule(new ConfigurationSettingsReader("autofac")); return builder.Build(); } /// <summary>Gets the IoC container as initialized by the setup.</summary> public static IContainer Container { get { return _container ?? (_container = Setup()); } } } }
zyyin2005-lokadclone
Test/Lokad.Cloud.Framework.Test/GlobalSetup.cs
C#
bsd
829
#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-lokadclone
Samples/Source/SimpleBlob/Program.cs
C#
bsd
2,263
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-lokadclone
Samples/Source/SimpleBlob/Properties/AssemblyInfo.cs
C#
bsd
1,450
#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-lokadclone
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 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-lokadclone
Samples/Source/IoCforService/MyProvider.cs
C#
bsd
497
#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-lokadclone
Samples/Source/IoCforService/MyModule.cs
C#
bsd
441
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-lokadclone
Samples/Source/IoCforService/Properties/AssemblyInfo.cs
C#
bsd
1,438
#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-lokadclone
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-lokadclone
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-lokadclone
Samples/Source/MapReduce/MapReduceService/JobMessage.cs
C#
bsd
1,044
 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-lokadclone
Samples/Source/MapReduce/MapReduceService/IMapReduceFunctions.cs
C#
bsd
791
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-lokadclone
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-lokadclone
Samples/Source/MapReduce/MapReduceService/MapReduceBlobSet.cs
C#
bsd
17,772
 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-lokadclone
Samples/Source/MapReduce/MapReduceClientLib/Helpers.cs
C#
bsd
3,828
 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-lokadclone
Samples/Source/MapReduce/MapReduceClientLib/HistogramMapReduceFunctions.cs
C#
bsd
532
#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-lokadclone
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("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-lokadclone
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.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-lokadclone
Samples/Source/MapReduce/MapReduceClient/Program.cs
C#
bsd
458
#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-lokadclone
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-lokadclone
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 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-lokadclone
Samples/Source/PingPong/PingPongClient/Program.cs
C#
bsd
1,102
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-lokadclone
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 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-lokadclone
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-lokadclone
Samples/Source/PingPong/PingPongService/Properties/AssemblyInfo.cs
C#
bsd
1,476
#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-lokadclone
Samples/Source/SimpleTable/Program.cs
C#
bsd
1,875
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-lokadclone
Samples/Source/SimpleTable/Properties/AssemblyInfo.cs
C#
bsd
1,448
<html> <head></head> <body> Dear ${firstName} ${lastName}, <br/>You new password is : ${newPassword} <br/>Please reset it when you login! <br/> <br/> <br/> Thank you. <br/> Best Regards. <br/><a href="###" >${appName}</a> <br/><a href="${appUrl}" >${appUrl}</a> <br/> ${todayDate} </body> </html>
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/resource/emailTemplate/forgotPassword.ftl
Fluent
gpl3
332
package com.infindo.appcreate.zzyj.controller.scheduler; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.httpclient.NameValuePair; import org.json.JSONException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.springframework.web.bind.annotation.RequestMapping; import com.infindo.appcreate.zzyj.entity.Activity; import com.infindo.appcreate.zzyj.entity.ActivityTalk; import com.infindo.appcreate.zzyj.entity.Expert; import com.infindo.appcreate.zzyj.entity.ExpertProject; import com.infindo.appcreate.zzyj.entity.Infomation; import com.infindo.appcreate.zzyj.entity.Project; import com.infindo.appcreate.zzyj.entity.ProjectComment; import com.infindo.appcreate.zzyj.entity.ProjectHot; import com.infindo.appcreate.zzyj.entity.ProjectSupporter; import com.infindo.appcreate.zzyj.httpclient.HttpProtocolHandler; import com.infindo.appcreate.zzyj.httpclient.HttpRequest; import com.infindo.appcreate.zzyj.httpclient.HttpResponse; import com.infindo.appcreate.zzyj.httpclient.HttpResultType; import com.infindo.appcreate.zzyj.service.ZzyjSpiderService; import com.infindo.appcreate.zzyj.util.StringUtil; @RequestMapping(value = "/scheduler") public class SchedulerManager { @Resource private ZzyjSpiderService zzyjSpiderService; private final String ZZYJ_SITE = "http://www.zhongzhiyunji.com"; private final String ZZYJ_PROJECT_LIST = "http://www.zhongzhiyunji.com/project/display/index/time/desc/"; private final String ZZYJ_PROJECT_SUPPORTER = "http://www.zhongzhiyunji.com/project/display_action/ajax_top/"; private final String ZZYJ_PROJEDT_COMMENT = "http://www.zhongzhiyunji.com/project/display_action/ajax_reply/"; private final String ZZYJ_PROJECT_HOT = "http://www.zhongzhiyunji.com/project/display/index/hot/desc/"; private final String ZZYJ_EXPERT_LIST = "http://www.zhongzhiyunji.com/expert/index/"; private final String ZZYJ_EXPERT_DETAIL = "http://www.zhongzhiyunji.com/user/qzone/"; private final String ZZYJ_EXPERT_DESC = "http://www.zhongzhiyunji.com/ajax/getInfo"; private final String ZZYJ_EXPERT_PROJECT_SUPPORT = "http://www.zhongzhiyunji.com/user/qzone/"; private final String ZZYJ_SERVICE = "http://www.zhongzhiyunji.com/service/fund/index/1"; private final String ZZYJ_SERVICE_INFORM = "http://www.zhongzhiyunji.com/news/info/43"; private final String ZZYJ_SERVICE_DECLVIDEOS = "http://www.zhongzhiyunji.com/news/info/44"; private final String ZZYJ_ACTIVITY_LIST = "http://www.zhongzhiyunji.com/activity/index/index/"; private final String ZZYJ_ACTIVITY_DETAIL = "http://www.zhongzhiyunji.com/activity/index/info/"; private final String ZZYJ_INFOMATION_LIST = "http://www.zhongzhiyunji.com/news/lists/createdAt/"; private final String ZZYJ_INFOMATION_DETAIL = "http://www.zhongzhiyunji.com/news/info/"; private final Integer CON_TIMEOUT = 60000; private final Integer EXPERT_PERPAGE_COUNT = 5; private final Integer PAGE_COUNT = 5; List voList = new ArrayList(); private void spideData() { voList = new ArrayList(); System.out.println(">>>>>>>>>> spide project begin.................."); spideProject(voList); spideProjectHot(voList); System.out.println(">>>>>>>>>> spide project end...................."); //spider expert info System.out.println(">>>>>>>>>> spide expert begin.................."); spideExpertInfo(voList); System.out.println(">>>>>>>>>> spide expert end...................."); //spider Service info System.out.println(">>>>>>>>>> spide Service begin.................."); spideService(voList); System.out.println(">>>>>>>>>> spide Service end...................."); //--spider activity list System.out.println(">>>>>>>>>> spide activity begin.................."); spideActivity(voList); System.out.println(">>>>>>>>>> spide activity end...................."); //spide infomation code list System.out.println(">>>>>>>>>> spide infomation begin.................."); spideInfomation(voList); System.out.println(">>>>>>>>>> spide infomation end...................."); } /** * spide infomation * @param voList * @return */ private int spideInfomation(List voList){ List<Infomation> infoList = new ArrayList<Infomation>(); Map<String,String> infoCodeMap = new HashMap<String,String>(); List<String> infoCodeList = new ArrayList<String>(); List<String> infoImageList = new ArrayList<String>(); List<String> infoTimeList = new ArrayList<String>(); List<String> infoOriginList = new ArrayList<String>(); Elements infoEls = null; Document doc = null; boolean shouldBreak = false; int pagingCount = 1; while(true){//for pagination if(shouldBreak){ break; } try { doc = Jsoup.connect(ZZYJ_INFOMATION_LIST+pagingCount).timeout(CON_TIMEOUT).get(); infoEls = doc.select("div.news_box div[class *= clearfix mt10] img"); if(infoEls.size() > 0){ String curInfoCode = ""; for(Element el: infoEls){ curInfoCode = getCodeFromUrl(el.parent().attr("href")); if(infoCodeMap.containsKey(curInfoCode)){ shouldBreak = true; curInfoCode = null; break; }else{ infoCodeMap.put(curInfoCode, curInfoCode); infoCodeList.add(curInfoCode); infoImageList.add(el.attr("src")); infoEls = el.parent().parent().select("div.news_con p span"); if(infoEls.size() > 0){ infoOriginList.add(infoEls.get(1).text()); infoTimeList.add(getPostStringOfColon(infoEls.get(2).text())); } } } }else{ break; } pagingCount ++; }catch(IOException e){ e.printStackTrace(); break; } } //loop to get infomation detail Long iCode = 0l; String iTitle = ""; String iImage = ""; String iOrigin = ""; Date iTime = null; String iDesc = ""; int _c = 0; for(String code : infoCodeList){ iCode = Long.valueOf(code); iImage = infoImageList.get(_c); iOrigin = infoOriginList.get(_c); iTime = getTimeFromStrByF2(infoTimeList.get(_c),"yyyy.MM.dd"); _c++; try { doc = Jsoup.connect(ZZYJ_INFOMATION_DETAIL+code).timeout(CON_TIMEOUT).get(); infoEls = doc.select("div.news_info_left div.title"); if(infoEls.size() > 0){ iTitle = infoEls.first().text(); } infoEls = doc.select("div.news_detail"); if(infoEls.size() > 0){ iDesc = infoEls.first().html(); } voList.add(new Infomation(iCode, iTitle, iImage, iOrigin, iTime, iDesc)); //System.out.println(iCode+";"+iTitle+";"+iTitle+";"+iOrigin+";"+iTime+";"); } catch (IOException e) { e.printStackTrace(); return 0; } } //this.saveSpiderData(infoList); return 1; } /** * spide Activity info * @param voList * @return */ private int spideActivity(List voList){ List<Activity> activityList = new ArrayList<Activity>(); List<ActivityTalk> activityTalkList = new ArrayList<ActivityTalk>(); Map<String,String> actCodeMap = new HashMap<String,String>(); List<String> actCodeList = new ArrayList<String>(); List<String> actListImageList = new ArrayList<String>(); Document doc = null; Elements aEls = null; int pagingCount = 1; boolean shouldBreak = false; while(true){//for pagination if(shouldBreak){ break; } try { doc = Jsoup.connect(ZZYJ_ACTIVITY_LIST+pagingCount).timeout(CON_TIMEOUT).get(); aEls = doc.select("div.project_left li div.showpic a[href *= index/info]"); if(aEls.size() > 0){ String curActCode = ""; for(Element el:aEls){ curActCode = getCodeFromUrl(el.attr("href")); if(actCodeMap.containsKey(curActCode)){ shouldBreak = true; curActCode = null; break; }else{ actCodeMap.put(curActCode, curActCode); actCodeList.add(curActCode); actListImageList.add(el.select("img").first().attr("src")); } } }else{ break; } pagingCount ++; }catch(IOException e){ e.printStackTrace(); } } //loop to get activity detail String aCode = ""; String aTitle = ""; Date aTime = null; String aAddress = ""; String aImage = ""; String aImages = ""; String aDesc = ""; int _c = 0; for(String code :actCodeList){ aImages = ""; aCode = code; aImage = actListImageList.get(_c++); try { doc = Jsoup.connect(ZZYJ_ACTIVITY_DETAIL+code).timeout(CON_TIMEOUT).get(); aEls = doc.select("h4.activity_info_title"); if(aEls.size() > 0){ aTitle = aEls.first().text(); } aEls = doc.select("ul.activity_info_sub li"); if(aEls.size() > 1){ aAddress = getPostStringOfColon(aEls.get(0).text()); if(StringUtil.isNotBlank(aEls.get(1).text())){ aTime = getTimeFromStrByF2(getPostStringOfColon(aEls.get(1).text()),"yyyy.MM.dd"); } } aEls = doc.select("h4.activity_info_title"); if(aEls.size() > 0){ aTitle = aEls.first().text(); } aEls = doc.select("div.act_box1"); if(aEls.size() > 0){ aDesc = aEls.first().html(); } aEls = doc.select("div.act_phone li img"); for(Element el :aEls){ aImages += el.attr("src")+","; } if(aImages.endsWith(",")){ aImages = aImages.substring(0,aImages.length() - 1); } voList.add(new Activity(aCode, aTitle, aTime, aAddress, aImage,aImages, aDesc)); //System.out.println(aCode+";"+aTitle+";"+aTime+";"+aAddress+";"+aImage+";"+aImages+";"+aDesc); //--spide activity talk spideActTalk(voList,code); } catch (IOException e) { e.printStackTrace(); return 0; } } //this.saveSpiderData(activityList); //this.saveSpiderData(activityTalkList); return 1; } private int spideActTalk(List voList, String actCode){ String atActCode = actCode; String atExpertCode = "";//public or expert code String atImage = ""; String atNickName = ""; Date atTime = null; String atDesc = ""; Document doc; Elements aEls; try { doc = Jsoup.connect(ZZYJ_ACTIVITY_DETAIL+actCode+"#discus").timeout(CON_TIMEOUT).get(); aEls = doc.select("div.activity_discus"); for(Element el :aEls){ aEls = el.select("img.avater"); if(aEls.size() > 0){ atImage = aEls.first().attr("src"); } aEls = el.select("p a[href *= /user/qzone]"); if(aEls.size() > 0){ atExpertCode = getCodeFromUrl(aEls.first().attr("href")); atNickName = aEls.first().text(); } aEls = el.select("div.comment_arae p"); if(aEls.size() > 0){ if(StringUtil.isNotBlank(aEls.get(1).text())){ atTime = getTimeFromStrByF2(aEls.get(1).text(),"yyyy.MM.dd hh:mm:ss"); } atDesc = aEls.get(2).text(); } voList.add(new ActivityTalk(atActCode, atExpertCode, atImage, atNickName, atTime, atDesc)); //System.out.println(atActCode+";"+atExpertCode+";"+atImage+";"+atNickName+";"+atTime+";"+atDesc); } } catch (IOException e) { e.printStackTrace(); return 0; } return 1; } /** * spide service * @param voList * @return */ private int spideService(List voList){ List<com.infindo.appcreate.zzyj.entity.Service> serviceList= new ArrayList<com.infindo.appcreate.zzyj.entity.Service>(); String sImage = ""; String sTitle = ""; String sOrgan = ""; String sDesc = ""; String sDeclInforms = "";//多个 dot 隔开, 声明通知 String sOpeDetails = "";//多个 dot 隔开,操作细节 String sDeclVideos = "";//多个 dot 隔开,声明视频 Document doc ; Elements els; try { doc = Jsoup.connect(ZZYJ_SERVICE).timeout(CON_TIMEOUT).get(); els = doc.select("div.service_banner"); if(els.size() > 0){ Element el = els.first(); els = el.select("div.fl img"); if(els.size() > 0){ sImage = els.first().attr("src"); } els = el.select("div.service_banner_right h4"); if(els.size() > 0){ sTitle = els.first().text(); } els = el.select("div[class *= con]"); if(els.size() > 0){ sDesc = els.first().text(); } els = el.select("p span"); if(els.size() > 0){ sOrgan = els.get(1).text(); } els = doc.select("div.service_main p img"); if(els.size() > 0){ sDeclInforms = els.first().attr("src"); sOpeDetails = els.last().attr("src"); } } //--spide service declare videos doc = Jsoup.connect(ZZYJ_SERVICE_DECLVIDEOS).timeout(CON_TIMEOUT).get(); els = doc.select("div.news_detail p"); if(els.size() > 0){ sDeclVideos = cutStrByReg(els.first().text(),"http"); } voList.add(new com.infindo.appcreate.zzyj.entity.Service(sImage, sTitle, sOrgan, sDesc, sDeclInforms, sOpeDetails, sDeclVideos)); //System.out.println(sImage+";"+sTitle+";"+sOrgan+";"+sDesc+";"+sDeclInforms+";"+sOpeDetails+";"+sDeclVideos); } catch (IOException e) { e.printStackTrace(); return 0; } //this.saveSpiderData(serviceList); return 1; } /** * spide expert info * @param voList * @return */ private int spideExpertInfo(List voList){ List<String> expertCodeList = new ArrayList<String>(); List<Expert> experList = new ArrayList<Expert>(); List<ExpertProject> expertSupList = new ArrayList<ExpertProject>(); Document doc; Elements els ; //--spider expert list Map<String,String> preExpertCodeMap = new HashMap<String,String>(); boolean shouldBreak = false; int pagingCount = 1; while(true){//for pagination if(shouldBreak){ break; } try { doc = Jsoup.connect(ZZYJ_EXPERT_LIST+pagingCount).timeout(CON_TIMEOUT).get(); els = doc.select("div.expert_col img[src *= avatar]"); if(els.size() > 0){ String curExpertCode = ""; for(Element el:els){ curExpertCode = getCodeFromUrl(el.parent().attr("href")); if(preExpertCodeMap.containsKey(curExpertCode)){ shouldBreak = true; preExpertCodeMap = null; break; }else{ preExpertCodeMap.put(curExpertCode, curExpertCode); expertCodeList.add(curExpertCode); } } }else{ break; } pagingCount ++; }catch(IOException e){ e.printStackTrace(); break; } } //loop to get expert detail String _code = ""; String _name = ""; String _image = ""; String _desc = ""; String _authIcon = "";//专家认证图标 V Integer _authIconType = 0;//0 blue v; 1 yellow v; String _weiBo = ""; for(String code :expertCodeList){ _code = code; try { doc = Jsoup.connect(ZZYJ_EXPERT_DETAIL+code).timeout(CON_TIMEOUT).get(); els = doc.select("img.bigavater"); if(els.size() > 0){ _image = els.first().attr("src"); } els = doc.select("span[class *= ucname showverifyinfo]"); if(els.size() > 0){ Element el = els.first(); _name = el.text(); _authIcon = ZZYJ_SITE+el.select("img").first().attr("src"); } els = doc.select("div[class *= fr ucright] p"); if(els.size() > 0){ Element el = els.last(); _weiBo = cutStrByReg(el.text(),"http"); } HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance(); HttpRequest req = new HttpRequest(HttpResultType.STRING); req.setCharset("UTF-8"); NameValuePair[] nameValuePair = new NameValuePair[1]; nameValuePair[0] = new NameValuePair("userId",code); req.setParameters(nameValuePair); req.setMethod(HttpRequest.METHOD_POST); req.setUrl(ZZYJ_EXPERT_DESC); HttpResponse response = httpProtocolHandler.execute(req,"",""); _desc = response.getStringResult(); if(StringUtil.isNotBlank(_desc)){ try { org.json.JSONObject infoJason = new org.json.JSONObject(_desc); _desc = (String) infoJason.get("content"); } catch (JSONException e) { e.printStackTrace(); } } voList.add(new Expert(_code, _name, _image, _desc, _authIcon, _weiBo)); //System.out.println(_weiBo+";"+_desc+";"+_authIcon+";"+_code+";"+_image+";"+_name); //spider expert suport project spideExpertSupport(voList,code); //spider expert arise project spideExpertArise(voList,code); } catch (IOException e) { e.printStackTrace(); return 0; } } //this.saveSpiderData(experList); //this.saveSpiderData(expertSupList); return 1; } private int spideExpertArise(List voList, String expertCode){ Document doc; Elements els; try { doc = Jsoup.connect(ZZYJ_EXPERT_PROJECT_SUPPORT+expertCode+"/arise").timeout(CON_TIMEOUT).get(); els = doc.select("div.project_left li div.showpic a"); if(els.size() > 0){ String _expertCode = expertCode; String _projectCode; Integer _type = 1;//0 支持的; 1 发起的 for(Element el :els){ _projectCode = getCodeFromUrl(el.attr("href")); voList.add(new ExpertProject(_expertCode, _projectCode, _type)); } } } catch (IOException e) { e.printStackTrace(); return 0; } return 1; } private int spideExpertSupport(List voList, String expertCode){ Document doc; Elements els; try { doc = Jsoup.connect(ZZYJ_EXPERT_PROJECT_SUPPORT+expertCode+"/support").timeout(CON_TIMEOUT).get(); els = doc.select("div.project_left li div.showpic a"); if(els.size() > 0){ String _expertCode = expertCode; String _projectCode; Integer _type = 0;//0 支持的; 1 发起的 for(Element el :els){ _projectCode = getCodeFromUrl(el.attr("href")); voList.add(new ExpertProject(_expertCode, _projectCode, _type)); } } } catch (IOException e) { e.printStackTrace(); return 0; } return 1; } private int spideProjectHot(List voList){ Document doc = null; Document docSub = null; Map<String,String> proCodeMap = new HashMap<String,String>(); //spider project list int pagingCount = 1; boolean shouldBreak = false; while(true){//for pagination /*if(pagingCount > PAGE_COUNT){ break; }*/ if(shouldBreak){ break; } try { doc = Jsoup.connect(ZZYJ_PROJECT_HOT+pagingCount).timeout(CON_TIMEOUT).get(); Elements els = doc.select("div.project_left ul li"); if(els.size() > 0){ String projectCode = ""; for(Element el:els){ Elements divPicAEls = el.select("div.showpic a"); if(divPicAEls.size() > 0){ Element picAEl = divPicAEls.first(); projectCode = getCodeFromUrl(picAEl.attr("href")); if(proCodeMap.containsKey(projectCode)){ shouldBreak = true; proCodeMap = new HashMap<String,String>(); break; }else{ proCodeMap.put(projectCode, projectCode); } } voList.add(new ProjectHot(projectCode)); //System.out.println(projectCode); } }else{ break; } pagingCount ++; } catch (IOException e) { e.printStackTrace(); return 0; } } return 1; } /** * spide project info * @param voList * @return */ private int spideProject(List voList){ Document doc = null; Document docSub = null; Map<String,String> proCodeMap = new HashMap<String,String>(); List<Project> proList = new ArrayList<Project>(); List<ProjectSupporter> proSupList = new ArrayList<ProjectSupporter>(); List<ProjectComment> proCommList = new ArrayList<ProjectComment>(); //spider project list int pagingCount = 1; boolean shouldBreak = false; while(true){//for pagination /*if(pagingCount > PAGE_COUNT){ break; }*/ if(shouldBreak){ break; } try { doc = Jsoup.connect(ZZYJ_PROJECT_LIST+pagingCount).timeout(CON_TIMEOUT).get(); Elements els = doc.select("div.project_left ul li"); if(els.size() > 0){ for(Element el:els){ String listImage = ""; String code = ""; String title = ""; Date time = null; String place = ""; Integer score = 0; Integer expertScore = 0; Integer crowdScore = 0; String proDetailRelUrl = ""; String user = ""; String promoteImages = ""; Integer promoteType = 0; String desc = ""; Elements divPicAEls = el.select("div.showpic a"); if(divPicAEls.size() > 0){ Element picAEl = divPicAEls.first(); proDetailRelUrl = picAEl.attr("href"); code = getCodeFromUrl(proDetailRelUrl); if(proCodeMap.containsKey(code)){ shouldBreak = true; proCodeMap = new HashMap<String,String>(); break; }else{ proCodeMap.put(code, code); } } Elements aH4TitleEls = el.select("a h4.box_title"); if(aH4TitleEls.size() > 0){ Element aH4TitleEl = aH4TitleEls.first(); title = aH4TitleEl.ownText(); } Elements divMt10Els = el.select("div.mt10"); if(divMt10Els.size() > 0){ Element divMt10El = divMt10Els.first(); String timeStr = divMt10El.ownText(); time = getTimeFromStrByF(timeStr,"yyyy-MM-dd"); } Elements spanM15AEls = el.select("span a.c96"); if(spanM15AEls.size() > 0){ Element spanM15AEl = spanM15AEls.first(); place = spanM15AEl.ownText(); } Elements scoreEls = el.select("span[class *= ml15 fs24 c0078B6 italic fwb]"); if(scoreEls.size() > 0){ Element scoreEl = scoreEls.first(); score = Integer.valueOf(scoreEl.ownText().trim()); } Elements spanExpertEls = el.select("span[class ~= expert]").parents().first().select("span"); if(spanExpertEls.size() > 0){ Element spanExpertEl = spanExpertEls.last(); expertScore = Integer.valueOf(spanExpertEl.ownText().trim()); } Elements spanPublicEls = el.select("span[class ~= public]").parents().first().select("span"); if(spanPublicEls.size() > 0){ Element spanPublicEl = spanPublicEls.last(); crowdScore = Integer.valueOf(spanPublicEl.ownText().trim()); } Elements divPicImgEls = el.select("div.showpic img"); if(divPicImgEls.size() > 0){ Element divPicImgEl = divPicImgEls.first(); listImage = divPicImgEl.attr("src"); } docSub = Jsoup.connect(ZZYJ_SITE+proDetailRelUrl).timeout(CON_TIMEOUT).get(); Elements divAUserEls = docSub.select("a[href *= user/qzone]"); if(divAUserEls.size() > 0){ Element divAUserEl = divAUserEls.first(); user = divAUserEl.ownText(); } Elements promoteImagesEls = docSub.select("ul.ad-thumb-list li"); if(promoteImagesEls.size() > 0){ String promoteSrc; promoteType = 0; if(promoteImagesEls.size() > 0){ for(Element el1: promoteImagesEls){ promoteSrc = el1.select("a").first().attr("href"); promoteImages += promoteSrc+","; } if(promoteImages.endsWith(",")){ promoteImages.substring(0, promoteImages.length()-1); } } } promoteImagesEls = docSub.select("div.projectflv_banner_left embed"); if(promoteImagesEls.size() > 0){ promoteType = 1; promoteImages = promoteImagesEls.first().attr("src"); } Elements descEls = docSub.select("div.project_info"); if(descEls.size() > 0){ Element descEl = descEls.first(); desc = descEl.html(); } voList.add(new Project(code, title, time, user, place, score, expertScore,crowdScore, listImage, promoteImages, promoteType, desc)); //System.out.println(score); //spide project supporter spideProSupporter(voList, code); //spider project comment spideProComment(voList, code); } }else{ break; } pagingCount ++; } catch (IOException e) { e.printStackTrace(); return 0; } } //this.saveSpiderData(proList); //this.saveSpiderData(proSupList); //this.saveSpiderData(proCommList); return 1; } private int spideProComment(List voList, String proCode){ String cProjectCode = proCode; String cExpertCode = ""; Date cTime = null; String cDesc = ""; Integer cType = 0;//0 expert; 1 public String cImage = ""; String cAuthIcon = ""; String cNickName = ""; Document doc = null; Elements els = null; try { int cc = 1; while(true){ doc = Jsoup.connect(ZZYJ_PROJEDT_COMMENT+proCode+"/public/"+cc).timeout(CON_TIMEOUT).get(); els = doc.select("div.commbox"); cType = 1; if(els.select("div.fl").size() > 0){ for(Element _el :els){ cImage = _el.child(0).select("img").first().attr("src"); if(!cImage.contains("http")){ cImage = ZZYJ_SITE+cImage; } els = _el.child(1).select("p"); if(els.size() > 0){ Elements __els = els.first().select("a"); if(__els.size() > 0){ cExpertCode = getCodeFromUrl(__els.first().attr("href")); cNickName = __els.first().text(); } cTime = getTimeFromStrByF2(els.get(1).text(),"yyyy-MM-dd hh:mm:ss"); cDesc = els.last().text(); } voList.add(new ProjectComment(cProjectCode, cExpertCode, cTime, cDesc, cType,cImage.trim(), cAuthIcon.trim(), cNickName.trim())); //System.out.println(cImage+";"+cAuthIcon+";"+cNickName+";"+cProjectCode+";"+cExpertCode+";"+cTime+";"+cDesc+";"+cType); } }else{ break; } cc++; } cc = 1; while(true){ if(cc > PAGE_COUNT){ break; } doc = Jsoup.connect(ZZYJ_PROJEDT_COMMENT+proCode+"/expert/"+cc).timeout(CON_TIMEOUT).get(); els = doc.select("div.commbox"); cType = 0; if(els.select("div.fl").size() > 0){ for(Element _el :els){ cImage = _el.child(0).select("img").first().attr("src"); if(!cImage.contains("http")){ cImage = ZZYJ_SITE+cImage; } els = _el.child(1).select("p"); if(els.size() > 0){ Elements __els = els.first().select("a"); if(__els.size() > 0){ cExpertCode = this.getCodeFromUrl(__els.first().attr("href")); cNickName = __els.first().text(); if(__els.first().select("img").size() > 0){ cAuthIcon = ZZYJ_SITE+__els.first().select("img").first().attr("src"); } } cTime = getTimeFromStrByF2(els.get(1).text(),"yyyy-MM-dd hh:mm:ss"); cDesc = els.last().text(); } voList.add(new ProjectComment(cProjectCode, cExpertCode, cTime, cDesc, cType,cImage.trim(), cAuthIcon.trim(), cNickName.trim())); //System.out.println(">>>comment>> "+cAuthIcon+";"+cImage+";"+cNickName+";"+cProjectCode+";"+cExpertCode+";"+cTime+";"+cDesc+";"+cType); } }else{ break; } cc++; } } catch (IOException e) { e.printStackTrace(); return 0; } return 1; } private int spideProSupporter(List voList, String proCode){ String _projectCode = proCode; String _expertCode = ""; Date _time = null; Integer _score = 0; Integer _type = 0;//0 expert; 1 public; String _image = ""; String _nickName = ""; String _authIcon = ""; Document doc = null; Elements els = null; int c = 1; try { while(true){ if(c > PAGE_COUNT){ break; } doc = Jsoup.connect(ZZYJ_PROJECT_SUPPORTER+proCode+"/public/"+c).timeout(CON_TIMEOUT).get(); els = doc.select("div.commbox"); _type = 1; if(els.select("div.fl").size() > 0){ for(Element _el :els){ els = _el.select("img.avater"); if(els.size() > 0){ _image = els.first().attr("src"); if(_image.contains("http")){ _image = ZZYJ_SITE + _image.trim(); } } els = _el.select("div").last().select("p"); if(els.size() > 0){ _time = getTimeFromStrByF2(els.first().text(),"yyyy-MM-dd hh:mm:ss"); } els = _el.select("a[href *= /user/qzone]"); if(els.size() > 0){ _nickName = els.first().text(); _expertCode = this.getCodeFromUrl(els.first().attr("href")); els = els.first().parent().parent().select("p").last().select("span"); if(els.size() > 0){ if(StringUtil.isNotBlank(els.first().text().trim())){ _score = Integer.valueOf(els.first().text().trim()); } } } voList.add(new ProjectSupporter(_projectCode, _expertCode, _time, _score, _type,_image.trim(),_authIcon.trim(),_nickName.trim())); //System.out.println(_nickName+";"+_authIcon+";"+_image+";"+_projectCode+";"+_expertCode+";"+_time+";"+_score+";"+_type); } }else{ break; } c++; } c = 1; while(true){ if(c > PAGE_COUNT){ break; } doc = Jsoup.connect(ZZYJ_PROJECT_SUPPORTER+proCode+"/expert/"+c).timeout(CON_TIMEOUT).get(); els = doc.select("div.commbox"); _type = 0; if(els.select("div.fl").size() > 0){ for(Element _el :els){ els = _el.select("img.avater"); if(els.size() > 0){ _image = els.first().attr("src"); if(_image.contains("http")){ _image = ZZYJ_SITE + _image.trim(); } } els = _el.select("div").last().select("p"); if(els.size() > 0){ _time = getTimeFromStrByF2(els.first().text(),"yyyy-MM-dd hh:mm:ss"); } els = _el.select("a[href *= /user/qzone]"); if(els.size() > 0){ _expertCode = this.getCodeFromUrl(els.first().attr("href")); _nickName = els.first().text(); if(els.first().select("span.vtd2 img").size() > 0){ _authIcon = ZZYJ_SITE+els.first().select("span.vtd2 img").first().attr("src"); } els = els.first().parent().parent().select("p").last().select("span"); if(els.size() > 0){ if(StringUtil.isNotBlank(els.first().text().trim())){ _score = Integer.valueOf(els.first().text().trim()); } } } voList.add(new ProjectSupporter(_projectCode, _expertCode, _time, _score, _type,_image.trim(),_authIcon.trim(),_nickName.trim())); //System.out.println(_nickName+";"+_authIcon+";"+_image+";"+_projectCode+";"+_expertCode+";"+_time+";"+_score+";"+_type); } }else{ break; } c++; } } catch (IOException e) { e.printStackTrace(); return 0; } return 1; } private String cutStrByReg(String text, String reg){ if(StringUtil.isNotBlank(text)){ if(text.contains(reg)){ return text.substring(text.indexOf(reg)); } } return ""; } private String getCodeFromUrl(String url){ if(StringUtil.isNotBlank(url)){ return url.substring(url.lastIndexOf("/")+1); } return ""; } private String getPostStringOfColon(String str){ if(StringUtil.isNotBlank(str)){ str = str.replace(":", "#").replace(":","#"); String temp = str.substring(str.indexOf("#")+1); return temp; } return null; } private Date getTimeFromStrByF(String dateStr,String formate){ if(StringUtil.isNotBlank(dateStr)){ dateStr = dateStr.replace(":", "#").replace(":","#"); String temp = dateStr.substring(dateStr.indexOf("#")+1); SimpleDateFormat sf = new SimpleDateFormat(formate); try { return sf.parse(temp); } catch (ParseException e) { e.printStackTrace(); } } return null; } private Date getTimeFromStrByF2(String dateStr,String formate){ if(StringUtil.isNotBlank(dateStr)){ SimpleDateFormat sf = new SimpleDateFormat(formate); try { return sf.parse(dateStr.trim()); } catch (ParseException e) { e.printStackTrace(); } } return null; } public void updateSpideData(){ spideData(); zzyjSpiderService.updateSpideData(voList); } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/controller/scheduler/SchedulerManager.java
Java
gpl3
46,138
package com.infindo.appcreate.zzyj.controller.mobi; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONObject; import org.apache.cxf.common.util.StringUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.infindo.appcreate.zzyj.entity.Activity; import com.infindo.appcreate.zzyj.entity.ActivityTalk; import com.infindo.appcreate.zzyj.entity.Expert; import com.infindo.appcreate.zzyj.entity.ExpertProject; import com.infindo.appcreate.zzyj.entity.Infomation; import com.infindo.appcreate.zzyj.entity.Project; import com.infindo.appcreate.zzyj.entity.ProjectComment; import com.infindo.appcreate.zzyj.entity.ProjectSupporter; import com.infindo.appcreate.zzyj.entity.Service; import com.infindo.appcreate.zzyj.service.ZzyjSpiderService; import com.infindo.appcreate.zzyj.util.ACConstant; import com.infindo.appcreate.zzyj.util.StringUtil; import com.infindo.framework.common.utils.PaginationSupport; import com.infindo.framework.spring.mvc.tiles2.Tiles; @Controller @RequestMapping("/mobi/") public class ZzyjSpiderController { @Resource private ZzyjSpiderService zzyjSpiderService; /* ------------- start project --------------*/ /** * get projects list * @param mCode : 11 time; 12 score; 13 expert; 14 public; 15 hot (to do) * @param request * @param model * @return */ @RequestMapping(value = "projects/{mCode}", method = RequestMethod.GET) public @ResponseBody Map<String,List<Project>> project(@PathVariable String mCode,HttpServletRequest request, Model model) { Map<String,List<Project>> map = new HashMap<String,List<Project>>(); List<Project> proList = null; if(StringUtil.isNotBlank(mCode)){ proList =zzyjSpiderService.getProjListByMcode(mCode); } if(proList != null){ map.put("projects", proList); } return map; } /** * get projects list by paging * @param mCode : 11 time; 12 score; 13 expert; 14 public; 15 hot (to do) * @param request * @param model * @return */ @RequestMapping(value = "projsByPage/{mCode}/{page}", method = RequestMethod.GET) public @ResponseBody Map<String,Object> projsByPage(@PathVariable String mCode,@PathVariable String page,HttpServletRequest request, Model model) { Map<String,Object> map = new HashMap<String,Object>(); if (StringUtils.isEmpty(page)) { page = "1"; } int rpp = ACConstant.PAGE_SIZE_10;//request.getParameter("rpp"); Integer startIndex = 0; if (StringUtil.isNotEmpty(page)) { startIndex = (Integer.valueOf(page) - 1) * rpp; } List<Project> proList = zzyjSpiderService.getProjsByPage(mCode,rpp,startIndex); int count = zzyjSpiderService.getObjCount(new Project()); if(proList != null){ map.put("projects", proList); map.put("count", count+""); } return map; } /** * project supporters list * @param proCode: project code * @param request * @param model * @param type: 0 expert; 1 public; * @return */ @RequestMapping(value = "supporters/{proCode}/{type}", method = RequestMethod.GET) public @ResponseBody Map<String,List<ProjectSupporter>> supporters(@PathVariable String proCode,@PathVariable Integer type,HttpServletRequest request, Model model) { Map<String,List<ProjectSupporter>> map = new HashMap<String,List<ProjectSupporter>>(); List<ProjectSupporter> proSList = null; if(type == null){ type = 0; } if(StringUtil.isNotBlank(proCode)){ proSList =zzyjSpiderService.getProjSupListByCodes(proCode,type); } if(proSList != null){ map.put("proSupporters", proSList); } return map; } @RequestMapping(value = "supptersByPage/{proCode}/{type}/{page}", method = RequestMethod.GET) public @ResponseBody Map<String,Object> supportersByPage(@PathVariable String proCode,@PathVariable Integer type,@PathVariable String page,HttpServletRequest request, Model model) { Map<String,Object> map = new HashMap<String,Object>(); List<ProjectSupporter> proSList = null; if (StringUtils.isEmpty(page)) { page = "1"; } if(type == null){ type = 0; } int rpp = ACConstant.PAGE_SIZE_10;//request.getParameter("rpp"); Integer startIndex = 0; if (StringUtil.isNotEmpty(page)) { startIndex = (Integer.valueOf(page) - 1) * rpp; } if(StringUtil.isNotBlank(proCode)){ proSList =zzyjSpiderService.getProjSupListByCodesPage(proCode,type,rpp,startIndex); } int count = zzyjSpiderService.getObjCount(new ProjectSupporter()); if(proSList != null){ map.put("proSupporters", proSList); } map.put("count", count); return map; } /** * project comments * @param proCode * @param type: 0 expert; 1 public; * @param request * @param model * @return */ @RequestMapping(value = "comments/{proCode}/{type}", method = RequestMethod.GET) public @ResponseBody Map<String,List<ProjectComment>> comments(@PathVariable String proCode,@PathVariable Integer type,HttpServletRequest request, Model model) { Map<String,List<ProjectComment>> map = new HashMap<String,List<ProjectComment>>(); List<ProjectComment> proCList = null; if(type == null){ type = 0; } if(StringUtil.isNotBlank(proCode)){ proCList =zzyjSpiderService.getProjComtListByCodes(proCode,type); } if(proCList != null){ map.put("proComments", proCList); } return map; } /** * project comments * @param proCode * @param type: 0 expert; 1 public; * @param request * @param model * @return */ @RequestMapping(value = "commentsByPage/{proCode}/{type}/{page}", method = RequestMethod.GET) public @ResponseBody Map<String,Object> commentsByPage(@PathVariable String proCode,@PathVariable Integer type,@PathVariable String page,HttpServletRequest request, Model model) { Map<String,Object> map = new HashMap<String,Object>(); List<ProjectComment> proSList = null; if (StringUtils.isEmpty(page)) { page = "1"; } if(type == null){ type = 0; } int rpp = ACConstant.PAGE_SIZE_10;//request.getParameter("rpp"); Integer startIndex = 0; if (StringUtil.isNotEmpty(page)) { startIndex = (Integer.valueOf(page) - 1) * rpp; } if(StringUtil.isNotBlank(proCode)){ proSList =zzyjSpiderService.getCommentsByPage(proCode,type,rpp,startIndex); } int count = zzyjSpiderService.getObjCount(new ProjectComment()); if(proSList != null){ map.put("proComments", proSList); } map.put("count", count); return map; } /* ------------- end project --------------*/ /* ------------- start service -------------- */ @RequestMapping(value = "service", method = RequestMethod.GET) public @ResponseBody Map<String,Service> service(HttpServletRequest request, Model model) { Map<String,Service> map = new HashMap<String,Service>(); List<Service> t =zzyjSpiderService.getObjList(Service.class); if(t.size() > 0){ map.put("service", t.get(0)); } return map; } /* ------------- end service --------------*/ /* ------------- start expert -------------- */ @RequestMapping(value = "experts", method = RequestMethod.GET) public @ResponseBody Map<String,List<Expert>> expert(HttpServletRequest request, Model model) { Map<String,List<Expert>> map = new HashMap<String,List<Expert>>(); List<Expert> expertList = null; expertList =zzyjSpiderService.getExpertList(); if(expertList != null){ map.put("experts", expertList); } return map; } /** * get projects list by paging * @param mCode : 11 time; 12 score; 13 expert; 14 public; 15 hot (to do) * @param request * @param model * @return */ @RequestMapping(value = "expertsByPage/{page}", method = RequestMethod.GET) public @ResponseBody Map<String,Object> expertsByPage(@PathVariable String page,HttpServletRequest request, Model model) { Map<String,Object> map = new HashMap<String,Object>(); if (StringUtils.isEmpty(page)) { page = "1"; } int rpp = ACConstant.PAGE_SIZE_10;//request.getParameter("rpp"); Integer startIndex = 0; if (StringUtil.isNotEmpty(page)) { startIndex = (Integer.valueOf(page) - 1) * rpp; } List<Expert> expertList = zzyjSpiderService.getExpertsByPage(rpp,startIndex); int count = zzyjSpiderService.getObjCount(new Expert()); if(expertList != null){ map.put("experts", expertList); map.put("count", count+""); } return map; } /** * get expert projects * @param type: 0 support; 1 arise * @param request * @param model * @return */ @RequestMapping(value = "expertProjs/{expertCode}/{type}", method = RequestMethod.GET) public @ResponseBody Map<String,List<Project>> expertProjs(@PathVariable String expertCode,@PathVariable Integer type,HttpServletRequest request, Model model) { Map<String,List<Project>> map = new HashMap<String,List<Project>>(); List<Project> expProjsList = null; expProjsList =zzyjSpiderService.getExpertProjsList(expertCode,type); if(expProjsList != null){ map.put("expertProjs", expProjsList); } return map; } /** * comments by expert * @param expertCode * @param request * @param model * @return */ @RequestMapping(value = "expertComts/{expertCode}", method = RequestMethod.GET) public @ResponseBody Map<String,List<Object>> expertComts(@PathVariable String expertCode,HttpServletRequest request, Model model) { Map<String,List<Object>> map = new HashMap<String,List<Object>>(); List<Object> commentList = null; commentList =zzyjSpiderService.getExpertComtsList(expertCode); if(commentList != null){ map.put("expertComts", commentList); } return map; } /* ------------- end expert -------------- */ /* ------------- activity start -------------*/ @RequestMapping(value = "activitys", method = RequestMethod.GET) public @ResponseBody Map<String,List<Activity>> activitys(HttpServletRequest request, Model model) { Map<String,List<Activity>> map = new HashMap<String,List<Activity>>(); List<Activity> actsList = null; actsList = zzyjSpiderService.getActivityList(); if(actsList != null){ map.put("projects", actsList); } return map; } @RequestMapping(value = "activitysByPage/{page}", method = RequestMethod.GET) public @ResponseBody Map<String,Object> activitysByPage(@PathVariable String page, HttpServletRequest request, Model model) { Map<String,Object> map = new HashMap<String,Object>(); if (StringUtils.isEmpty(page)) { page = "1"; } int rpp = ACConstant.PAGE_SIZE_10;//request.getParameter("rpp"); Integer startIndex = 0; if (StringUtil.isNotEmpty(page)) { startIndex = (Integer.valueOf(page) - 1) * rpp; } List<Activity> actList = zzyjSpiderService.getExpertsByPage(rpp,startIndex); int count = zzyjSpiderService.getObjCount(new Activity()); if(actList != null){ map.put("activitys", actList); map.put("count", count+""); } return map; } @RequestMapping(value = "activityTalk/{actCode}", method = RequestMethod.GET) public @ResponseBody Map<String,List<ActivityTalk>> activityTalk(@PathVariable String actCode,HttpServletRequest request, Model model) { Map<String,List<ActivityTalk>> map = new HashMap<String,List<ActivityTalk>>(); List<ActivityTalk> actsList = null; actsList = zzyjSpiderService.getActivityTalks(actCode); if(actsList != null){ map.put("activityTalks", actsList); } return map; } /* ------------- activity end ---------------*/ /* ------------- infomation start -----------*/ @RequestMapping(value = "infos", method = RequestMethod.GET) public @ResponseBody Map<String,List<Infomation>> infos(HttpServletRequest request, Model model) { Map<String,List<Infomation>> map = new HashMap<String,List<Infomation>>(); List<Infomation> infoList = null; infoList = zzyjSpiderService.getInfomationList(); if(infoList != null){ map.put("infomations", infoList); } return map; } @RequestMapping(value = "infosByPage/{page}", method = RequestMethod.GET) public @ResponseBody Map<String,Object> infosByPage(@PathVariable String page, HttpServletRequest request, Model model) { Map<String,Object> map = new HashMap<String,Object>(); if (StringUtils.isEmpty(page)) { page = "1"; } int rpp = ACConstant.PAGE_SIZE_10;//request.getParameter("rpp"); Integer startIndex = 0; if (StringUtil.isNotEmpty(page)) { startIndex = (Integer.valueOf(page) - 1) * rpp; } List<Infomation> actList = zzyjSpiderService.getInfomatinsByPage(rpp,startIndex); int count = zzyjSpiderService.getObjCount(new Infomation()); if(actList != null){ map.put("infomations", actList); map.put("count", count+""); } return map; } /* ------------- infomation end -----------*/ @RequestMapping(value = "content") public @ResponseBody String content(HttpServletRequest request, Model model) { //JSONObject json = JSONObject.fromObject(dataMap); //String prettyJsonString = jsonFormatter(json.toString()); //System.out.println( prettyJsonString); return ""; } public static String jsonFormatter(String uglyJSONString){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(uglyJSONString); String prettyJsonString = gson.toJson(je); return prettyJsonString; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/controller/mobi/ZzyjSpiderController.java
Java
gpl3
16,281
package com.infindo.appcreate.zzyj.controller.mobi; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.infindo.appcreate.zzyj.dao.UserDao; import com.infindo.appcreate.zzyj.entity.SysUser; import com.infindo.appcreate.zzyj.service.UserService; import com.infindo.appcreate.zzyj.util.RandomUtil; import com.infindo.appcreate.zzyj.util.StringUtil; @Controller @RequestMapping(value = "/mobi/user/") public class UserController { protected final Logger log = Logger.getLogger(getClass()); @Resource UserService userService; @Resource UserDao userDao; @RequestMapping(value = "signon.jsonp") public Map<String, Object> signon(HttpServletRequest request, ModelMap modelMap) throws IOException { Map<String, Object> res = new HashMap<String, Object>(); String account = request.getParameter("account"); String password = request.getParameter("passwd"); if (StringUtil.isEmpty(account) || StringUtil.isEmpty(password)) { res.put("success", false); return res; } DetachedCriteria dc = DetachedCriteria.forClass(SysUser.class); dc.add(Restrictions.eq("account", account)); dc.add(Restrictions.eq("passwd", password)); List<SysUser> ls = userDao.findByCriteria(dc); SysUser user = null; String token = null; if (ls.size() > 0) { user = ls.get(0); token = RandomUtil.RandomString(); //user.setSignonToken(token); userDao.update(user); request.getSession().setAttribute("user", user); res.put("success", true); res.put("account", account); res.put("token", token); //res.put("guestToken", user.getGuestToken()); return res; } else { res.put("success", false); return res; } } @RequestMapping(value = "signonWithToken.jsonp") public Map<String, Object> signonWithToken(HttpServletRequest request, ModelMap modelMap) throws IOException { Map<String, Object> res = new HashMap<String, Object>(); String token = request.getParameter("token"); if (StringUtil.isEmpty(token)) { res.put("success", false); return res; } DetachedCriteria dc = DetachedCriteria.forClass(SysUser.class); dc.add(Restrictions.eq("signonToken", token)); List<SysUser> ls = userDao.findByCriteria(dc); SysUser user = null; if (ls.size() > 0) { user = ls.get(0); request.getSession().setAttribute("user", user); res.put("success", true); res.put("account", user.getAccount()); res.put("token", token); //res.put("guestToken", user.getGuestToken()); return res; } else { res.put("success", false); return res; } } @RequestMapping(value = "signonAsGuest.jsonp") public Map<String, Object> signonAsGuest(HttpServletRequest request, ModelMap modelMap) throws IOException { Map<String, Object> res = new HashMap<String, Object>(); String token = request.getParameter("token"); if (StringUtil.isEmpty(token)) { res.put("success", false); return res; } DetachedCriteria dc = DetachedCriteria.forClass(SysUser.class); dc.add(Restrictions.eq("guestToken", token)); List<SysUser> ls = userDao.findByCriteria(dc); SysUser user = null; if (ls.size() > 0) { user = ls.get(0); request.getSession().setAttribute("user", user); res.put("success", true); res.put("account", user.getAccount()); //res.put("guestToken", user.getGuestToken()); return res; } else { res.put("success", false); return res; } } @RequestMapping(value = "signup.jsonp") public Map<String, Object> signup(HttpServletRequest request, ModelMap modelMap) throws IOException { Map<String, Object> res = new HashMap<String, Object>(); String account = request.getParameter("account"); String password = request.getParameter("passwd"); if (StringUtil.isEmpty(account) || StringUtil.isEmpty(password)) { res.put("success", false); return res; } DetachedCriteria dc = DetachedCriteria.forClass(SysUser.class); dc.add(Restrictions.eq("account", account)); List<SysUser> ls = userDao.findByCriteria(dc); if (ls.size() > 0) { res.put("success", false); res.put("msg", "账户已存在"); return res; } SysUser user = new SysUser(); user.setAccount(account); user.setPasswd(password); String token = RandomUtil.RandomString(); String guestToken = RandomUtil.RandomString(); // user.setSignonToken(token); // user.setGuestToken(guestToken); user.setStatus(1); user.setUpdateTime(new Date()); userDao.save(user); request.getSession().setAttribute("user", user); res.put("success", true); res.put("account", account); res.put("token", token); res.put("guestToken", guestToken); return res; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/controller/mobi/UserController.java
Java
gpl3
5,262
package com.infindo.appcreate.zzyj.httpclient; import org.apache.commons.httpclient.HttpException; import java.io.IOException; import java.net.UnknownHostException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpConnectionManager; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.FilePartSource; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.httpclient.params.HttpMethodParams; import java.io.File; import java.util.ArrayList; import java.util.List; /* * *类名:HttpProtocolHandler *功能:HttpClient方式访问 *详细:获取远程HTTP数据 */ public class HttpProtocolHandler { private static String DEFAULT_CHARSET = "UTF-8"; /** 连接超时时间,由bean factory设置,缺省为8秒钟 */ private int defaultConnectionTimeout = 100000; /** 回应超时时间, 由bean factory设置,缺省为30秒钟 */ private int defaultSoTimeout = 30000; /** 闲置连接超时时间, 由bean factory设置,缺省为60秒钟 */ private int defaultIdleConnTimeout = 60000; private int defaultMaxConnPerHost = 30; private int defaultMaxTotalConn = 80; /** 默认等待HttpConnectionManager返回连接超时(只有在达到最大连接数时起作用):1秒*/ private static final long defaultHttpConnectionManagerTimeout = 3 * 1000; /** * HTTP连接管理器,该连接管理器必须是线程安全的. */ private HttpConnectionManager connectionManager; private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler(); /** * 工厂方法 * * @return */ public static HttpProtocolHandler getInstance() { return httpProtocolHandler; } /** * 私有的构造方法 */ private HttpProtocolHandler() { // 创建一个线程安全的HTTP连接池 connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost); connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn); IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread(); ict.addConnectionManager(connectionManager); ict.setConnectionTimeout(defaultIdleConnTimeout); ict.start(); } /** * 执行Http请求 * * @param request 请求数据 * @param strParaFileName 文件类型的参数名 * @param strFilePath 文件路径 * @return * @throws HttpException, IOException */ public HttpResponse execute(HttpRequest request, String strParaFileName, String strFilePath) throws HttpException, IOException { HttpClient httpclient = new HttpClient(connectionManager); // 设置连接超时 int connectionTimeout = defaultConnectionTimeout; if (request.getConnectionTimeout() > 0) { connectionTimeout = request.getConnectionTimeout(); } httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // 设置回应超时 int soTimeout = defaultSoTimeout; if (request.getTimeout() > 0) { soTimeout = request.getTimeout(); } httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout); // 设置等待ConnectionManager释放connection的时间 httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout); String charset = request.getCharset(); charset = charset == null ? DEFAULT_CHARSET : charset; HttpMethod method = null; //get模式且不带上传文件 if (request.getMethod().equals(HttpRequest.METHOD_GET)) { method = new GetMethod(request.getUrl()); method.getParams().setCredentialCharset(charset); // parseNotifyConfig会保证使用GET方法时,request一定使用QueryString method.setQueryString(request.getQueryString()); } else if(strParaFileName.equals("") && strFilePath.equals("")) { //post模式且不带上传文件 method = new PostMethod(request.getUrl()); ((PostMethod) method).addParameters(request.getParameters()); //method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset); } else { //post模式且带上传文件 method = new PostMethod(request.getUrl()); List<Part> parts = new ArrayList<Part>(); for (int i = 0; i < request.getParameters().length; i++) { parts.add(new StringPart(request.getParameters()[i].getName(), request.getParameters()[i].getValue(), charset)); } //增加文件参数,strParaFileName是参数名,使用本地文件 parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath)))); // 设置请求体 ((PostMethod) method).setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams())); } // 设置Http Header中的User-Agent属性 //method.addRequestHeader("User-Agent", "Mozilla/4.0"); HttpResponse response = new HttpResponse(); //try { int code = httpclient.executeMethod(method); if (code == HttpStatus.SC_OK) { if (request.getResultType().equals(HttpResultType.STRING)) { response.setStringResult(method.getResponseBodyAsString()); } else if (request.getResultType().equals(HttpResultType.BYTES)) { response.setByteResult(method.getResponseBody()); } response.setResponseHeaders(method.getResponseHeaders()); }else{ return null; } /*} catch (UnknownHostException ex) { return null; } catch (IOException ex) { return null; } catch (Exception ex) { return null;*/ //} finally { method.releaseConnection(); //} return response; } /** * 将NameValuePairs数组转变为字符串 * * @param nameValues * @return */ protected String toString(NameValuePair[] nameValues) { if (nameValues == null || nameValues.length == 0) { return "null"; } StringBuffer buffer = new StringBuffer(); for (int i = 0; i < nameValues.length; i++) { NameValuePair nameValue = nameValues[i]; if (i == 0) { buffer.append(nameValue.getName() + "=" + nameValue.getValue()); } else { buffer.append("&" + nameValue.getName() + "=" + nameValue.getValue()); } } return buffer.toString(); } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/httpclient/HttpProtocolHandler.java
Java
gpl3
7,999
package com.infindo.appcreate.zzyj.httpclient; import java.io.UnsupportedEncodingException; import org.apache.commons.httpclient.Header; public class HttpResponse { /** * 返回中的Header信息 */ private Header[] responseHeaders; /** * String类型的result */ private String stringResult; /** * btye类型的result */ private byte[] byteResult; public Header[] getResponseHeaders() { return responseHeaders; } public void setResponseHeaders(Header[] responseHeaders) { this.responseHeaders = responseHeaders; } public byte[] getByteResult() { if (byteResult != null) { return byteResult; } if (stringResult != null) { return stringResult.getBytes(); } return null; } public void setByteResult(byte[] byteResult) { this.byteResult = byteResult; } public String getStringResult() throws UnsupportedEncodingException { if (stringResult != null) { return stringResult; } if (byteResult != null) { return new String(byteResult, "utf-8"); } return null; } public void setStringResult(String stringResult) { this.stringResult = stringResult; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/httpclient/HttpResponse.java
Java
gpl3
1,380
package com.infindo.appcreate.zzyj.httpclient; import org.apache.commons.httpclient.NameValuePair; public class HttpRequest { /** HTTP GET method */ public static final String METHOD_GET = "GET"; /** HTTP POST method */ public static final String METHOD_POST = "POST"; /** * 待请求的url */ private String url = null; /** * 默认的请求方式 */ private String method = METHOD_POST; private int timeout = 0; private int connectionTimeout = 0; /** * Post方式请求时组装好的参数值对 */ private NameValuePair[] parameters = null; /** * Get方式请求时对应的参数 */ private String queryString = null; /** * 默认的请求编码方式 */ private String charset = "GBK"; /** * 请求发起方的ip地址 */ private String clientIp; /** * 请求返回的方式 */ private HttpResultType resultType = HttpResultType.BYTES; public HttpRequest(HttpResultType resultType) { super(); this.resultType = resultType; } /** * @return Returns the clientIp. */ public String getClientIp() { return clientIp; } /** * @param clientIp The clientIp to set. */ public void setClientIp(String clientIp) { this.clientIp = clientIp; } public NameValuePair[] getParameters() { return parameters; } public void setParameters(NameValuePair[] parameters) { this.parameters = parameters; } public String getQueryString() { return queryString; } public void setQueryString(String queryString) { this.queryString = queryString; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public int getConnectionTimeout() { return connectionTimeout; } public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } /** * @return Returns the charset. */ public String getCharset() { return charset; } /** * @param charset The charset to set. */ public void setCharset(String charset) { this.charset = charset; } public HttpResultType getResultType() { return resultType; } public void setResultType(HttpResultType resultType) { this.resultType = resultType; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/httpclient/HttpRequest.java
Java
gpl3
3,116
package com.infindo.appcreate.zzyj.httpclient; public enum HttpResultType { STRING,BYTES }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/httpclient/HttpResultType.java
Java
gpl3
101
package com.infindo.appcreate.zzyj.service; import java.io.File; public class EmailSenderImpl extends EmailServiceImpl implements EmailSender { private String supportEmail; @Override public void updateMailSender() { } public String getSupportEmail() { return supportEmail; } public void setSupportEmail(String supportEmail) { this.supportEmail = supportEmail; } @Override public void sendSupportMail(String replyTo, String subject, String content, File[] attachments) { super.sendMimeMail(new String[] { supportEmail }, replyTo, subject, content, attachments); } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/service/EmailSenderImpl.java
Java
gpl3
625
package com.infindo.appcreate.zzyj.service; import com.infindo.appcreate.zzyj.entity.SysUser; public interface UserService { SysUser update(String email); }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/service/UserService.java
Java
gpl3
173
package com.infindo.appcreate.zzyj.service; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.Properties; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.MailException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import com.infindo.appcreate.zzyj.util.StringUtil; public class EmailServiceImpl extends JavaMailSenderImpl implements EmailService { private static class MailTask implements Runnable { private JavaMailSender mailSender; private MimeMessage msg; public void run() { try { synchronized (mailSender) { mailSender.send(msg); } } catch (MailException e) { e.printStackTrace(); } } public MailTask(JavaMailSender mailSender, MimeMessage msg) { this.mailSender = mailSender; this.msg = msg; } } private static Logger logger = LoggerFactory .getLogger(EmailServiceImpl.class); private Executor executor; public static final String BEAN_NAME = "emailService"; private Properties javaMailProperties; public EmailServiceImpl() { javaMailProperties = new Properties(); executor = Executors.newFixedThreadPool(2); } public void init() throws Exception { updateMailSender(); } public void updateMailSender() { setDefaultEncoding("UTF-8"); setUsername("polygonsmtp"); setPassword("PS1288#a"); setHost("smtp.infindo.com"); javaMailProperties.setProperty("mail.smtp.auth", "true"); javaMailProperties.setProperty("mail.smtp.starttls.enable", "true"); setJavaMailProperties(javaMailProperties); } public void sendTextMail(String receviers[], String replyTo, String subject, String content) { if (receviers == null || receviers.length < 1) return; SimpleMailMessage msg = new SimpleMailMessage(); msg.setFrom("bloggerapp@infindo.com"); msg.setTo(receviers); msg.setSubject(subject); msg.setText(content); if (StringUtil.isNotBlank(replyTo)) msg.setReplyTo(replyTo); send(msg); } public void sendMimeMail(String receviers[], String replyTo, String subject, String content, File attachments[]) { if (receviers == null || receviers.length < 1) return; MimeMessage msg = createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8"); helper.setTo(receviers); helper.setFrom("noReplyEmail@infindo.com", "BloApp"); helper.setSubject(subject); helper.setText(content, true); if (StringUtil.isNotBlank(replyTo)) helper.setReplyTo(replyTo); if (attachments != null && attachments.length > 0) { File arr$[] = attachments; int len$ = arr$.length; for (int i$ = 0; i$ < len$; i$++) { File file = arr$[i$]; helper.addAttachment(file.getName(), file); } } } catch (MessagingException e) { e.printStackTrace(); return; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return; } try { MailTask mailTask = new MailTask(this, msg); (new Thread(mailTask)).start(); } catch (Exception e) { e.printStackTrace(); } } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/service/EmailServiceImpl.java
Java
gpl3
3,501
package com.infindo.appcreate.zzyj.service; import java.io.File; public interface EmailSender extends EmailService { public void sendSupportMail(String replyTo, String subject, String content, File[] attachments); }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/service/EmailSender.java
Java
gpl3
234
package com.infindo.appcreate.zzyj.service; import java.io.File; public interface EmailService { public abstract void sendTextMail(String as[], String s, String s1, String s2); public abstract void sendMimeMail(String as[], String s, String s1, String s2, File afile[]); }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/service/EmailService.java
Java
gpl3
297
package com.infindo.appcreate.zzyj.service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.infindo.appcreate.zzyj.dao.UserDao; import com.infindo.appcreate.zzyj.entity.SysUser; @Service public class UserServiceImpl implements UserService { @Resource UserDao userDao; @Override public SysUser update(String email) { SysUser user = userDao.get(Long.valueOf(1)); userDao.saveOrUpdate(user); return user; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/service/UserServiceImpl.java
Java
gpl3
491
package com.infindo.appcreate.zzyj.service; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import org.hibernate.LockMode; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.type.Type; import org.springframework.dao.DataAccessException; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.stereotype.Service; import com.infindo.appcreate.zzyj.entity.Activity; import com.infindo.appcreate.zzyj.entity.ActivityTalk; import com.infindo.appcreate.zzyj.entity.Expert; import com.infindo.appcreate.zzyj.entity.Infomation; import com.infindo.appcreate.zzyj.entity.Project; import com.infindo.appcreate.zzyj.entity.ProjectComment; import com.infindo.appcreate.zzyj.entity.ProjectSupporter; import com.infindo.framework.base.service.BaseServiceImpl; import com.infindo.framework.base.vo.TableModel; import com.infindo.framework.common.utils.PaginationSupport; @Service("zzyjSpiderService") public class ZzyjSpiderServiceImpl<T> extends BaseServiceImpl implements ZzyjSpiderService { @Override public void deleteAllData(String ... tables){ try { for(String table:tables){ super.deleteAll(super.findAll(Class.forName("com.infindo.appcreate.zzyj.entity."+table))); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } @Override public void saveSpiderData(List ... dataList) { this.deleteAllData("Project","Expert","ExpertProject","ProjectComment","ProjectSupporter","Service","Activity","ActivityTalk","Infomation","ProjectHot"); for(List<?> objList :dataList){ for(Object obj :objList){ super.save(obj); } } } @Override public void updateSpideData(List voList) { if(voList.size() > 0){ this.saveSpiderData(voList); } } @Override public List<Project> getProjListByMcode(String mCode) { DetachedCriteria dc = DetachedCriteria.forClass(Project.class); int mCodeInt = Integer.valueOf(mCode); switch(mCodeInt){ case 11://time dc.addOrder(Order.desc("time")); break; case 12://score dc.addOrder(Order.desc("score")); break; case 13://expert dc.addOrder(Order.desc("expertScore")); break; case 14://public dc.addOrder(Order.desc("crowdScore")); break; case 15://hot //dc.addOrder(Order.desc("crowdScore")); String hql = "select p from Project p, ProjectHot ph where p.code = ph.projectCode order by ph.id "; return super.find(hql); default: dc.addOrder(Order.desc("time")); break; } return findByCriteria(dc); } @Override public List<Project> getProjsByPage(String mCode, int pageSize, Integer startIndex) { DetachedCriteria dc = DetachedCriteria.forClass(Project.class); int mCodeInt = Integer.valueOf(mCode); switch(mCodeInt){ case 11://time dc.addOrder(Order.desc("time")); break; case 12://score dc.addOrder(Order.desc("score")); break; case 13://expert dc.addOrder(Order.desc("expertScore")); break; case 14://public dc.addOrder(Order.desc("crowdScore")); break; case 15://host String hql = "select p from Project p, ProjectHot ph where p.code = ph.projectCode order by ph.id "; return super.find(hql); default: dc.addOrder(Order.desc("time")); break; } return findByCriteria(dc,pageSize,startIndex); } @Override public List<ProjectSupporter> getProjSupListByCodes(String proCode, Integer type) { DetachedCriteria dc = DetachedCriteria.forClass(ProjectSupporter.class); dc.add(Restrictions.eq("projectCode", proCode)); switch(type){ case 0://expert dc.add(Restrictions.eq("type", 0)); break; case 1://public dc.add(Restrictions.eq("type", 1)); break; default: dc.add(Restrictions.eq("type", 0)); break; } dc.addOrder(Order.desc("time")); return findByCriteria(dc); } @Override public List<ProjectSupporter> getProjSupListByCodesPage(String proCode, Integer type,int pageSize, Integer startIndex) { DetachedCriteria dc = DetachedCriteria.forClass(ProjectSupporter.class); dc.add(Restrictions.eq("projectCode", proCode)); switch(type){ case 0://expert dc.add(Restrictions.eq("type", 0)); break; case 1://public dc.add(Restrictions.eq("type", 1)); break; default: dc.add(Restrictions.eq("type", 0)); break; } dc.addOrder(Order.desc("time")); return findByCriteria(dc,pageSize,startIndex); } @Override public int getObjCount(Object t) { DetachedCriteria dc = DetachedCriteria.forClass(t.getClass()); return this.getCountByCriteria(dc); } @Override public List<ProjectComment> getProjComtListByCodes(String proCode, Integer type) { DetachedCriteria dc = DetachedCriteria.forClass(ProjectComment.class); dc.add(Restrictions.eq("projectCode", proCode)); switch(type){ case 0://expert dc.add(Restrictions.eq("type", 0)); break; case 1://public dc.add(Restrictions.eq("type", 1)); break; default: dc.add(Restrictions.eq("type", 0)); break; } dc.addOrder(Order.desc("time")); return findByCriteria(dc); } @Override public List<ProjectComment> getCommentsByPage(String proCode, Integer type, int pageSize, Integer startIndex) { DetachedCriteria dc = DetachedCriteria.forClass(ProjectComment.class); dc.add(Restrictions.eq("projectCode", proCode)); switch(type){ case 0://expert dc.add(Restrictions.eq("type", 0)); break; case 1://public dc.add(Restrictions.eq("type", 1)); break; default: dc.add(Restrictions.eq("type", 0)); break; } dc.addOrder(Order.desc("time")); return findByCriteria(dc,pageSize,startIndex); } @Override public List<T> getObjList(Class class1) { DetachedCriteria dc = DetachedCriteria.forClass(class1); return findByCriteria(dc); } @Override public List<Expert> getExpertList() { DetachedCriteria dc = DetachedCriteria.forClass(Expert.class); dc.addOrder(Order.asc("id")); return findByCriteria(dc); } @Override public List<Expert> getExpertsByPage(int pageSize, Integer startIndex) { DetachedCriteria dc = DetachedCriteria.forClass(Expert.class); dc.addOrder(Order.asc("id")); return findByCriteria(dc,pageSize,startIndex); } @Override public List<Project> getExpertProjsList(String expertCode, int type) { String hql = "select p from Project p,ExpertProject ep where p.code = ep.projectCode and ep.expertCode = ? and ep.type = ? order by ep.id asc "; return super.find(hql, new Object[]{expertCode,type}); } @Override public List getExpertComtsList(String expertCode) { String hql = "select new com.infindo.appcreate.zzyj.entity.ExpertCommentVO(p.code, p.title, pc.desc) from Project p, ProjectComment pc where pc.expertCode = ? and p.code = pc.projectCode order by pc.time desc "; return super.find(hql, new Object[]{expertCode}); } @Override public List<Activity> getActivityList() { DetachedCriteria dc = DetachedCriteria.forClass(Activity.class); dc.addOrder(Order.desc("time")); return findByCriteria(dc); } @Override public List<ActivityTalk> getActivityTalks(String actCode) { DetachedCriteria dc = DetachedCriteria.forClass(ActivityTalk.class); dc.add(Restrictions.eq("actCode", actCode)); dc.addOrder(Order.desc("time")); return findByCriteria(dc); } @Override public List<Infomation> getInfomationList() { DetachedCriteria dc = DetachedCriteria.forClass(Infomation.class); dc.addOrder(Order.desc("time")); return findByCriteria(dc); } @Override public List<Infomation> getInfomatinsByPage(int pageSize, Integer startIndex) { DetachedCriteria dc = DetachedCriteria.forClass(Infomation.class); dc.addOrder(Order.desc("time")); return findByCriteria(dc,pageSize,startIndex); } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/service/ZzyjSpiderServiceImpl.java
Java
gpl3
9,771
package com.infindo.appcreate.zzyj.service; import java.util.List; import com.infindo.appcreate.zzyj.entity.Activity; import com.infindo.appcreate.zzyj.entity.ActivityTalk; import com.infindo.appcreate.zzyj.entity.Expert; import com.infindo.appcreate.zzyj.entity.ExpertProject; import com.infindo.appcreate.zzyj.entity.Infomation; import com.infindo.appcreate.zzyj.entity.Project; import com.infindo.appcreate.zzyj.entity.ProjectComment; import com.infindo.appcreate.zzyj.entity.ProjectSupporter; import com.infindo.appcreate.zzyj.entity.Service; import com.infindo.framework.base.service.BaseService; public interface ZzyjSpiderService<T> extends BaseService { public void deleteAllData(String ... tables); public void saveSpiderData(List ... dataList); public void updateSpideData(List voList); public List<Project> getProjListByMcode(String mCode); public List<Project> getProjsByPage(String mCode, int rpp, Integer startIndex); public int getObjCount(T t); public List<ProjectSupporter> getProjSupListByCodes(String proCode, Integer type); public List<ProjectSupporter> getProjSupListByCodesPage(String proCode, Integer type, int pageSize, Integer startIndex); public List<ProjectComment> getProjComtListByCodes(String proCode, Integer type); public List<ProjectComment> getCommentsByPage(String proCode, Integer type, int rpp, Integer startIndex); public List<Service> getObjList(Class<Service> class1); public List<Expert> getExpertList(); public List<Expert> getExpertsByPage(int rpp, Integer startIndex); public List<Project> getExpertProjsList(String expertCode, int type); public List<Object> getExpertComtsList(String expertCode); public List<Activity> getActivityList(); public List<ActivityTalk> getActivityTalks(String actCode); public List<Infomation> getInfomationList(); public List<Infomation> getInfomatinsByPage(int rpp, Integer startIndex); }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/service/ZzyjSpiderService.java
Java
gpl3
2,027
package com.infindo.appcreate.zzyj.service; import java.util.HashSet; import java.util.Set; import org.springframework.dao.DataAccessException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; public class UserDetailsServiceImpl implements UserDetailsService { public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException, DataAccessException { // UserInfo user = loadUserByEmail(email); // if (user == null) { // throw new UsernameNotFoundException((new StringBuilder()) // .append("the user '").append(email) // .append("' dont't exist").toString()); // } else { // Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user); // boolean credentialsNonExpired = true; // boolean accountNonLocked = !user.getLocked().booleanValue(); // boolean accountNonExpired = !user.getExpired().booleanValue(); // UserInfo userDetails = new UserInfo(); // userDetails.setUsername(user.getUserName()); // return userDetails; // } return null; } private Set<GrantedAuthority> obtainGrantedAuthorities(Long userId) { Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>(); return authSet; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/service/UserDetailsServiceImpl.java
Java
gpl3
1,436
package com.infindo.appcreate.zzyj.util; import java.util.Random; public class RandomUtil { private static final String[] l = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; private static int count = 100; private static int getCount(){ if(count>999)count = 100; return count++; } //TentoN(这里是你想转换的数 ,这里是你想转换为多少进制 2-62之间) public static String TentoN(long value, int number) { if (number <= 1 || number > l.length) { throw new RuntimeException("Faild"); } //负数处理 if (value < 0) { return "-" + TentoN(0 - value, number); } if (value < number) { return l[(int)value]; } else { long n = value % (long)number; return (TentoN(value / number, number) + l[(int)n]); } } /** * 返回4位随机数 * @return */ public static Integer getRandom2(){ Integer i = new Random().nextInt(9999); while(i<1000) i=i<<1; return i; } public static String RandomString(){ String s = TentoN((System.currentTimeMillis()-1323333000000L), 62)+TentoN((long)getCount(),62); return s; } // public static void main(String[] args) throws InterruptedException { // long a = System.currentTimeMillis(); // HashSet<String> hs = new HashSet<String>(); // for(int i=0;i<1000;i++){ // String s = RandomString(); // hs.add(s); // System.out.println(s); // } // System.out.println(hs.size()); // // long b = System.currentTimeMillis(); // System.out.println("毫秒:"+(b-a)); // } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/RandomUtil.java
Java
gpl3
1,840
package com.infindo.appcreate.zzyj.util; public class TimerUtil { long start; long end; public void start() { start = System.nanoTime(); } public void stop() { end = System.nanoTime(); } public double getTime() { long time = this.end - this.start; double t = ((double) time) / 1000000000; return t; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/TimerUtil.java
Java
gpl3
325
package com.infindo.appcreate.zzyj.util; public class Constant { public static String IOS_APP_BUILD_DIR = null; public static final String PATH_UPLOAD = "uploads"; public static String SYSTEM_ROOT_PATH; public static String CONTENT_PATH; //android apk public static final String PUSH_SERVER_URL = "PUSH_SERVER_URL"; public static final String SENDER_ID="SENDERID"; public static final String EXTERNAL_URL="SERVER_URL"; public static final String PUSH_CONSTANT_SRC_PATH="/src/com/infindo/frame/data/constant/PushConstant.java"; public static final String PLATFORM_NAME_IOS = "iOS"; public static final String PLATFORM_NAME_ANDROID = "Android"; public static final String SYS_CONFIG_FILENAME = "appConfig"; //2012/09/12 public static String BUILD_PENDING ="Pending"; public static String BUILD_RUNNING ="Running"; public static String BUILD_DONE ="Done"; public static String BUILD_FAIL ="Failure"; public static String BUILD_EXCEPTION="Exception"; public static Long THREAD_IDLE = 1000l; public static Integer REQUEST_COUNT = 2; public static Integer CALL_BACK_COUNT = 2; public static final Integer TASK_COUNT = 1; public static final Integer YES = 1; public static final Integer NO = 0; public static String HOST_URL; public static final int THREE = 3; public static final int FOUR = 4; }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/Constant.java
Java
gpl3
1,468
package com.infindo.appcreate.zzyj.util; public enum ThreadGroupEnum { zip,build }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/ThreadGroupEnum.java
Java
gpl3
90
package com.infindo.appcreate.zzyj.util; public class UserInfoUtil { public static Object getCurrentUser() { return null; } // public static UserInfoService userInfoService; // public static UserInfo getCurrentUser() // { // if (SecurityContextHolder.getContext().getAuthentication() == null) // return null; // if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() // instanceof UserInfo) // { // UserInfo userInfo = // (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // userInfo = userInfoService.loadUserByUsername(userInfo.getUsername()); // return userInfo; // } else // { // return null; // } // } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/UserInfoUtil.java
Java
gpl3
711
package com.infindo.appcreate.zzyj.util; public class PaginationSupport { }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/PaginationSupport.java
Java
gpl3
83
package com.infindo.appcreate.zzyj.util; import java.util.Random; import org.apache.commons.lang3.StringUtils; public class StringUtil extends StringUtils { private static Random randGen = null; private static char[] numbersAndLetters = null; private static Object initLock = new Object(); public static boolean isEmpty(String s) { if (s == null) { return true; } s = s.trim(); if (s.equals("")) { return true; } return false; } public static String getNumString(String s, Integer m) { if (s.length() < m) { for (int i = 0; i < m - s.length(); i++) s = "0" + s; } return s; } public static final String randomString(int length) { if (length < 1) { return null; } if (randGen == null) { synchronized (initLock) { if (randGen == null) { randGen = new Random(); numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") .toCharArray(); // numbersAndLetters = // ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); } } } char[] randBuffer = new char[length]; for (int i = 0; i < randBuffer.length; i++) { randBuffer[i] = numbersAndLetters[randGen.nextInt(71)]; // randBuffer[i] = numbersAndLetters[randGen.nextInt(35)]; } return new String(randBuffer); } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/StringUtil.java
Java
gpl3
1,365
package com.infindo.appcreate.zzyj.util; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public class RequestObserver { public static void observe(HttpServletRequest request) { String name, pvalue; Object avalue; Enumeration enum1; System.out .println("/***************** Request Observer (Author: Alex Nie)**************/"); // observe Request Header enum1 = request.getHeaderNames(); System.out.println("Request Header:"); while (enum1.hasMoreElements()) { name = (String) enum1.nextElement(); pvalue = request.getHeader(name); System.out.println(" " + name + " ---- " + pvalue); } enum1 = request.getParameterNames(); // observe Request Parameters System.out.println("Request Parameters:"); while (enum1.hasMoreElements()) { name = (String) enum1.nextElement(); pvalue = request.getParameter(name); System.out.println(" " + name + " ---- " + pvalue); } enum1 = request.getAttributeNames(); // observe Request Attributes System.out.println("Request Attributes:"); while (enum1.hasMoreElements()) { name = (String) enum1.nextElement(); avalue = request.getAttribute(name); System.out.println(" " + name + " ---- " + avalue); } // observe Request Session HttpSession session = request.getSession(false); System.out.println("session: " + session); if (session != null) { System.out.println(" sessionId: " + session.getId()); enum1 = session.getAttributeNames(); System.out.println("Session Attributes:"); while (enum1.hasMoreElements()) { name = (String) enum1.nextElement(); avalue = session.getAttribute(name); System.out.println(" " + name + " ---- " + avalue); } } System.out .println("/***************** End of Request Observer (Author: Alex Nie)**************/"); } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/RequestObserver.java
Java
gpl3
1,933
package com.infindo.appcreate.zzyj.util; import org.apache.log4j.Logger; import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; public class Log4jListener implements BuildListener { Logger log = null; Logger rootLog = null; private final boolean initialized = true; public Log4jListener(Logger lg) { log = lg; } public void buildStarted(BuildEvent event) { if (initialized) { log.info("Build started."); } } public void buildFinished(BuildEvent event) { if (initialized) { if (event.getException() == null) { log.info("Build finished."); } else { log.error("Build finished with error.", event.getException()); } } } public void targetStarted(BuildEvent event) { if (initialized) { log.info("Target \"" + event.getTarget().getName() + "\" started."); } } public void targetFinished(BuildEvent event) { if (initialized) { String targetName = event.getTarget().getName(); if (event.getException() == null) { log.info("Target \"" + targetName + "\" finished."); } else { log.error("Target \"" + targetName + "\" finished with error.", event.getException()); } } } public void taskStarted(BuildEvent event) { if (initialized) { Task task = event.getTask(); log.info("Task \"" + task.getTaskName() + "\" started."); } } public void taskFinished(BuildEvent event) { if (initialized) { Task task = event.getTask(); if (event.getException() == null) { log.info("Task \"" + task.getTaskName() + "\" finished."); } else { log.error("Task \"" + task.getTaskName() + "\" finished with error.", event.getException()); } } } public void messageLogged(BuildEvent event) { if (initialized) { Object categoryObject = event.getTask(); if (categoryObject == null) { categoryObject = event.getTarget(); if (categoryObject == null) { categoryObject = event.getProject(); } } switch (event.getPriority()) { case Project.MSG_ERR: log.error(event.getMessage()); break; case Project.MSG_WARN: log.warn(event.getMessage()); break; case Project.MSG_INFO: log.info(event.getMessage()); break; case Project.MSG_VERBOSE: log.debug(event.getMessage()); break; case Project.MSG_DEBUG: log.debug(event.getMessage()); break; default: log.error(event.getMessage()); break; } } } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/Log4jListener.java
Java
gpl3
3,333
package com.infindo.appcreate.zzyj.util; import java.util.List; import java.util.Map; public class ACConstant { public static final String PLATFORM_NAME_IOS = "iOS"; public static final String PLATFORM_NAME_ANDROID = "Android"; public static final String PLATFORM_DEFAULT = PLATFORM_NAME_IOS; public static final String PLATFORM_TYPE_IOS = "*.ipa;*.zip"; public static final String PLATFORM_TYPE_ANDROID = "*.apk;*.zip"; public static final int STATUS_ENABLE = 1; public static final int STATUS_DISABLE = 0; public static final int STATUS_YES = 1; public static final int STATUS_NO = 0; public static final Integer YES = 1; public static final Integer NO = 0; public static final String ONE = "1"; public static final String TWO = "2"; public static final int PAGE_SIZE = 20; public static final int PAGE_SIZE_10 = 10; public static final int PAGE_SIZE_MOBI = 50; public static final int DEFAULT_VERSION_1 = 1; public static final int DEFAULT_VERSION_0 = 0; public static final String DEFAULT_VERSION_S = "1.0"; public static final int DEFAULT_PACK_VERSION_0= 0; public static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_FORMAT = "yyyy-MM-dd"; public static final String PENDING_PROVISION = "pending_provision"; public static final String PENDING_BINARY = "pending_binary"; public static final String PENDING_BUG_FIX = "pending_bug_fix"; public static final String PENDING_QC = "pending_qc"; public static final String PENDING_SUB = "pending_sub"; public static final String PENDING_APP_APPROVAL = "pending_app_approval"; public static final String PENDING_CLIENT_APPROVAL = "pending_client_approval"; public static final String PROVISION = "Provision"; public static final String PROVISION_STATUS_YES = "PROVISION_STATUS_YES"; public static final String PROVISION_STATUS_NO = "PROVISION_STATUS_NO"; public static final String PATH_UPLOAD = "uploads"; public static final String PATH_PROVISION = "provision"; public static final double IMAGE_SIZE_FULL_WIDTH = 320; public static final double IMAGE_SIZE_FULL_HEIGHT = 415; public static final double IMAGE_SIZE_SMALL_WIDTH = 95; public static final double IMAGE_SIZE_SMALL_HEIGHT = 118; public static final double IMAGE_SIZE_APP = 72; public static final double IMAGE_SIZE_APP_M = 512; public static final double IMAGE_SIZE_MOBI_BANNER_WIDTH = 320; public static final double IMAGE_SIZE_MOBI_BANNER_HEIGHT = 137; public static final double IMAGE_SIZE_MOBI_CONTENT_BANNER_WIDTH = 320; public static final double IMAGE_SIZE_MOBI_CONTENT_BANNER_HEIGHT = 200; public static final double IMAGE_SIZE_MOBI_CONTENT_ICON_WIDTH = 78; public static final double IMAGE_SIZE_MOBI_CONTENT_ICON_HEIGHT = 78; /*public static final int W_640 = 640; public static final int W_320 = 320; public static final int H_960 = 960; public static final int H_920 = 920; public static final int H_480 = 480; public static final int H_460 = 460; public static final int H_1096 = 1096; public static final int H_1136 = 1136; public static final int W_H_114 = 114; public static final int W_H_57 = 57; public static final int W_H_96 = 96;*/ /*public enum Module{ album, contact, content, content_single, html, directory, event, rss, weblink, video, table; }*/ public static final int PAYMENT_TYPE_PAYPAL = 1; public static final String PAYMENT_STATUS_SENT = "Sent"; public static final String PAYMENT_STATUS_PENDING = "Pending"; public static final String PAYMENT_STATUS_PASS = "Pass"; public static final String PAYMENT_STATUS_FAIL = "Fail"; public static final String VIDEO_URL_START = "http://www.youtube.com/watch?"; public static final String VIDEO_URL_PARAM = "v="; public static final String STATISTICS_TYPE_MONTH = "month"; public static final String STATISTICS_TYPE_COUNTRY = "country"; public static final String STATISTICS_TYPE_DEVICE = "device"; public static final String STATISTICS_TYPE_BROWSER = "browser"; public static final String STATISTICS_TYPE_DEVICEOS = "deviceOS"; public static final int MAX_LENGTH_255 = 255; public static final String KEY_OF_LAYOUT = "key_of_layout"; public static final int PREVIOUS_PAGE = -1; public static final int CURRENT_PAGE = 0; public static final int NEXT_PAGE = 1; public static final String PAID_NO = "NO"; public static final String PAID_YES = "YES"; /*public static final String ICON_SET_PATH = "res/icon_sets/black/"; public static final String MODULE_CODE_ALBUM = "album"; public static final String MODULE_CODE_CONTACT = "contact"; public static final String MODULE_CODE_DIRECTORY = "directory"; public static final String MODULE_CODE_EVENT = "event"; public static final String MODULE_CODE_CONTENT_SINGLE = "content_single"; public static final String MODULE_CODE_CONTENT_MUTI = "content"; public static final String MODULE_CODE_RSS = "rss"; public static final String MODULE_CODE_HTML = "html"; public static final String MODULE_CODE_VIDEO = "video"; public static final String MODULE_LABEL_HOME = "Home"; public static final String MODULE_LABEL_EVENT = "Events"; public static final String MODULE_LABEL_CONTENT_MUTI = "Product"; public static final String MODULE_LABEL_ALBUM = "Gallery"; public static final String MODULE_LABEL_CONTACT = "Contact"; public static final String MODULE_LABEL_DIRECTORY = "Directory"; public static final String MODULE_LABEL_RSS = "Rss"; public static final String MODULE_LABEL_HTML = "Html"; public static final String ICON_SET_PATH = "res/icon_sets/black/"; public static final String PLUGIN_CODE_ALBUM = "photoAlbum";*/ //sandy added 2012-4-1 public static final int APP_DASHBOARD = 0; public static final int APP_STEP_ONE = 1; public static final int APP_STEP_TWO = 2; public static final int APP_STEP_THREE = 3; public static final int APP_STEP_FOUR= 4; //public static final String THEME_DARKGREY = "darkgrey"; public static final String ICONS_WHITE = "white"; public static final String ICONS_DARK = "dark"; public static final long PLUGIN_ID_ZERO = 0; /* public static final String DEFAULT_APP_ICON="m/images/icons/icon.png";*/ public static final String DEFAULT_APP_ICON="m/images/icons/default/icon-10@2x8.png"; public static final String DEFAULT_APP_STARTUP="m_resource/bootup/bootupappx.png"; /*lenao add*/ //add pugin visible size public static int PLUGIN_VISIBLE_SIZE = 11; //plugin preview root path public static String PLUGIN_PREVIRE_ROOT_PATH = "m_resource/preview/"; public static String PLUGIN_ICONS_ROOT_PATH = "m/icons/"; public static String THEME_ICON_FILTER_SUFFIX_H = "_h"; public static String THEME_ICON_FILTER_SUFFIX_HAT2X = "_h@2x"; public static String THEME_ICON_FILTER_SUFFIX_AT2X = "@2x"; public static String APP_DEFAULTICONS_ROOT_PATH = "m/images/icons/default/"; //payment terms unit public static String PAY_TERMS_UNIT_M = "Months"; //sandy add public static String PUSH_SERVER_URL="http://m.infindo.com/push.appsquare/mobileObjectFeed.action"; //2012/09/12 public static String BUILD_PENDING="Pending"; public static String BUILD_RUNNING ="Running"; public static String BUILD_DONE ="Done"; public static String BUILD_FAIL ="Failure"; //public static String BUILD_EXCEPTION="Exception"; //email template public static String APP_SUBMINT_TO_ADMIN="AppSubmitToAdmin.ftl"; public static String APP_SUBMINT_TO_USER= "AppSubmitToUser.ftl"; public static String APP_REJECT= "AppReject.ftl"; public static String APP_SUSPEND= "AppSuspend.ftl"; public static String APP_RESUME= "AppResume.ftl"; public static String APP_LIVE= "AppLive.ftl"; public static String APP_CLOSE= "AppClose.ftl"; public static String APP_REGENERATE= "AppReGenerate.ftl"; public static String APP_BUILD_FAIL= "AppBinayFail.ftl"; public static String APP_RENEW= "AppRenew.ftl"; public static String APP_EXPIRED= "AppExpired.ftl"; public static String APP_PAYSUCCESS= "paySuccess.ftl"; public static String messageFileName="message.properties"; //android apk public static final String SERVER_URL = "SERVER_URL"; public static final String SENDER_ID="SENDERID"; public static final String PUSH_CONSTANT_SRC_PATH="/src/com/infindo/frame/data/constant/PushConstant.java"; //public static String BINARY_PENDING="Pending"; //public static String BINARY_DONE ="Done"; public static String BINARY_FAIL ="Fail"; public static int FREE =0; public static int PAY =1; public static int ADVANCED =2; public static int PAY_NO = 0; public static int PAY_YES = 1; public static int PAY_PENDING =2; public static int PAYPAL_ID = 1; public static int Amazon_Payment_ID = 2; public static int GOOGLE_CHECKOUT_PAYMENT_ID = 3; public static int TWO_CheckOut_Payment_ID = 4; public static int AliPay_ID = 5; public static int COMPILE_INTERVAL_HOURS = 3; }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/ACConstant.java
Java
gpl3
9,577
package com.infindo.appcreate.zzyj.util; import org.apache.commons.lang3.StringUtils; import org.im4java.core.ConvertCmd; import org.im4java.core.IMOperation; import org.im4java.process.StandardStream; public class ImageUtil extends StringUtils { public static String ScaleImage(String folder, String srcFilePath, String postfix, double height, double width) { String dectFilePath = srcFilePath.replace(".", postfix + "."); IMOperation op = new IMOperation(); op.addImage(); op.resize(Integer.valueOf((int) width), Integer.valueOf((int) height), "^"); op.addImage(); ConvertCmd convert = new ForWinConvertCmd(); convert.setErrorConsumer(StandardStream.STDERR); try { convert.run(op, new Object[] { folder + srcFilePath, folder + dectFilePath }); } catch (Exception e) { e.printStackTrace(); } return dectFilePath; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/ImageUtil.java
Java
gpl3
897
package com.infindo.appcreate.zzyj.util; import java.io.File; import java.io.InputStream; import java.util.Properties; import org.apache.commons.lang3.StringUtils; public class FileUtil { public static boolean removeFile(String path) { File file = new File(path); boolean result = false; if (file.exists()) result = file.delete(); return result; } public static String getExtension(String fileName, String defExt) { if ((fileName != null) && (fileName.length() > 0)) { int i = fileName.lastIndexOf('.'); if ((i > -1) && (i < (fileName.length() - 1))) { return fileName.substring(i + 1); } } return defExt; } public static String getFileName(String filePath) { if (StringUtils.isEmpty(filePath)) { return ""; } return filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length()); } public static String getParamFromConfig(String path,String key){ Properties config = new Properties(); String result = ""; try { InputStream in = FileUtil.class.getClassLoader().getResourceAsStream(path); config.load(in); result = (String) config.get(key); in.close(); } catch (Exception e) { e.printStackTrace(); } return result; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/FileUtil.java
Java
gpl3
1,339
package com.infindo.appcreate.zzyj.util; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class OneUrlConnction { public static OneUrlConnction oneUrlConnction = null; private HttpURLConnection urlConnection= null; private OneUrlConnction() {} public synchronized static OneUrlConnction getSingleOneUrlConnction( ){ if(null == oneUrlConnction){ oneUrlConnction = new OneUrlConnction(); } return oneUrlConnction; } public HttpURLConnection getHttpUrlConnection(String urlStr) throws Exception{ URL url; HttpURLConnection urlConnection = null; /*try {*/ url = new URL(urlStr); if(null == urlConnection){ urlConnection = (HttpURLConnection)url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setUseCaches(true); urlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object"); urlConnection.setRequestMethod("POST"); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(300000); urlConnection.setReadTimeout(600000); } /*}catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }*/ return urlConnection; } public void disconnect() { if(null != urlConnection){ urlConnection.disconnect(); urlConnection = null; } } public void connect() throws IOException { if(null != urlConnection){ urlConnection.connect(); } } public static void main(String[] args){ //http://192.168.1.104:8080/appcreate/back/buildCallBack?appId=6650&result=true&pcode=Android&zipUrl=download/5/5_18_Android.zip&binaryUrl=download/5/5_18_Android.apk } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/OneUrlConnction.java
Java
gpl3
1,779
package com.infindo.appcreate.zzyj.util; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateTimeUtil { private static final String[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; private static final String[] WEEK_DAYS = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; public static Date StringToDate(String format, String dateStr) { SimpleDateFormat dateFormat = new SimpleDateFormat(format); try { Date date = dateFormat.parse(dateStr.trim()); return date; } catch (Exception e) { e.printStackTrace(); } return null; } public static String DateToString(String format, Date dt) { if (dt == null) return ""; SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(dt); } public static String ToDateStr(Date dt) { if (dt == null) return ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(dt); } public static String ToTimeStr(Date dt) { if (dt == null) return ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); return sdf.format(dt); } public static String ToEnglishDayWithMon(Date dt) { if (dt == null) return ""; DateFormatSymbols sym = new DateFormatSymbols(); sym.setMonths(MONTHS); SimpleDateFormat f = new SimpleDateFormat("dd MMM, yyyy", sym); return getWeekDay(dt) + ", " + f.format(dt); } public static String ToEnglishDay(Date dt) { if (dt == null) return ""; DateFormatSymbols sym = new DateFormatSymbols(); sym.setMonths(MONTHS); SimpleDateFormat f = new SimpleDateFormat("dd MMM, yyyy", sym); return f.format(dt); } public static Date GetTodayMorning() { Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); return c.getTime(); } public static Date combineDateAndTime(String dt, String tm) { if (StringUtil.isEmpty(dt)) { return null; } if (StringUtil.isEmpty(tm)){ tm = "08:00"; } String fullStr2 = dt + " " + tm; return DateTimeUtil.StringToDate("yyyy-MM-dd HH:mm", fullStr2); } private static String getWeekDay(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int idx = cal.get(Calendar.DAY_OF_WEEK) - 1; return WEEK_DAYS[idx]; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/DateTimeUtil.java
Java
gpl3
2,655
package com.infindo.appcreate.zzyj.util; import java.lang.reflect.Field; import java.util.Arrays; import java.util.List; import org.im4java.core.ConvertCmd; public class ForWinConvertCmd extends ConvertCmd { public ForWinConvertCmd() { initForWin(); } public ForWinConvertCmd(boolean useGM) { super(useGM); initForWin(); } protected void initForWin() { if (System.getProperty("os.name").startsWith("Windows")) try { Field field = getClass().getSuperclass().getSuperclass() .getDeclaredField("iCommands"); field.setAccessible(true); List value = (List) field.get(this); value.addAll(0, Arrays.asList(new String[] { "cmd", "/C" })); } catch (Exception e) { throw new RuntimeException(e); } } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/util/ForWinConvertCmd.java
Java
gpl3
779
package com.infindo.appcreate.zzyj.vo; public class BuildCallBackVo implements java.io.Serializable { private static final long serialVersionUID = 5933924538834844385L; private Long appId; private String pcode; private String result; private String msg; private String zipUrl; private String binaUrl; public Long getAppId() { return appId; } public void setAppId(Long appId) { this.appId = appId; } public String getPcode() { return pcode; } public void setPcode(String pcode) { this.pcode = pcode; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getZipUrl() { return zipUrl; } public void setZipUrl(String zipUrl) { this.zipUrl = zipUrl; } public String getBinaUrl() { return binaUrl; } public void setBinaUrl(String binaUrl) { this.binaUrl = binaUrl; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/vo/BuildCallBackVo.java
Java
gpl3
1,038
package com.infindo.appcreate.zzyj.vo; import java.util.List; public class CarVo implements java.io.Serializable { private static final long serialVersionUID = -7410472659802063569L; private Long id; private Long pid; private String name; private Integer imageWidth; private Integer imageNum; private List<String> images; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getPid() { return pid; } public void setPid(Long pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getImageWidth() { return imageWidth; } public void setImageWidth(Integer imageWidth) { this.imageWidth = imageWidth; } public Integer getImageNum() { return imageNum; } public void setImageNum(Integer imageNum) { this.imageNum = imageNum; } public List<String> getImages() { return images; } public void setImages(List<String> images) { this.images = images; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/vo/CarVo.java
Java
gpl3
1,094
package com.infindo.appcreate.zzyj.vo; import java.util.Date; public class BuildRequestVo implements java.io.Serializable { private static final long serialVersionUID = 4629413423561483666L; private Long id; private Long appId; private String appName; private String appNamespace; private String appVer; private String pushPassword; private String appstorePassword; private String appResUrl; private String appZipUrl; private Date createTime; private String status; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAppId() { return appId; } public void setAppId(Long appId) { this.appId = appId; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getAppNamespace() { return appNamespace; } public void setAppNamespace(String appNamespace) { this.appNamespace = appNamespace; } public String getAppVer() { return appVer; } public void setAppVer(String appVer) { this.appVer = appVer; } public String getPushPassword() { return pushPassword; } public void setPushPassword(String pushPassword) { this.pushPassword = pushPassword; } public String getAppstorePassword() { return appstorePassword; } public void setAppstorePassword(String appstorePassword) { this.appstorePassword = appstorePassword; } public String getAppResUrl() { return appResUrl; } public void setAppResUrl(String appResUrl) { this.appResUrl = appResUrl; } public String getAppZipUrl() { return appZipUrl; } public void setAppZipUrl(String appZipUrl) { this.appZipUrl = appZipUrl; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/vo/BuildRequestVo.java
Java
gpl3
2,007
package com.infindo.appcreate.zzyj.servlet; import java.util.Locale; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringUtil implements ApplicationContextAware { public static ApplicationContext appContext; public SpringUtil() { } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { appContext = applicationContext; } public static String getMessage(String key, Object params[]) { return getMessage(key, params, Locale.ENGLISH); } public static String getMessage(String key, Object params[], Locale locale) { return appContext.getMessage(key, params, locale); } public static Object getBean(String serviceName) { Object obj = new Object(); try { obj = appContext.getBean(serviceName); } catch (BeansException e) { e.printStackTrace(); return null; } return obj; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/servlet/SpringUtil.java
Java
gpl3
1,028
package com.infindo.appcreate.zzyj.servlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.infindo.appcreate.zzyj.entity.SysUser; public class AccessControlInterceptor extends HandlerInterceptorAdapter { static String[] frontKeywords = new String[] { "login" }; static String[] mobiKeywords = new String[] { "noPriviledgePage", "error" }; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String root = request.getContextPath(); String url = request.getRequestURL().toString(); boolean handlerOk = super.preHandle(request, response, handler); if (handlerOk) { // For statistics // if (url.indexOf("/mobi/") > 0) { // CltClient client = (CltClient) // request.getSession().getAttribute("currentClient"); // if (client == null) { // wrapRequestInfo(request); // } // } if (url.indexOf("/front") > 0) { if (checkKeywords(url, frontKeywords)) { return true; } HttpSession session = request.getSession(); SysUser client = (SysUser) session .getAttribute("currentClient"); if (client != null) { return true; } else { response.sendRedirect(root + "/front/login"); return false; } } else { return true; } } return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mv) throws Exception { String root = request.getContextPath(); String url = request.getRequestURL().toString(); boolean isLogin = false; boolean hasApp = false; boolean live = false; // if (url.indexOf("/mobi") > 0) { // if (checkKeywords(url, mobiKeywords)) { // return; // } // HttpSession session = request.getSession(); // CltClient client = (CltClient) session // .getAttribute("currentClient"); // if (client != null) { // isLogin = true; // } // // AppApplication app = (AppApplication) session // .getAttribute("appApplication"); // if (app != null) { // hasApp = true; // if (app.getStatus() != null // && app.getStatus().equals( // StatusEnum.App.Live.toString())) { // live = true; // } // } // // if (!hasApp || !(isLogin || live)) { // response.sendRedirect(root + "/mobi/noPriviledgePage"); // } // } } private boolean checkKeywords(String url, String[] frontKeywords) { String temp = url.toLowerCase(); for (String word : frontKeywords) { if (temp.indexOf(word.toLowerCase()) > 0) { return true; } } return false; } // private String getWholeUrl(HttpServletRequest request) { // StringBuffer sb = request.getRequestURL(); // StringBuffer parameters = new StringBuffer(); // Enumeration<String> attrNames = request.getParameterNames(); // while (attrNames.hasMoreElements()) { // String attrName = attrNames.nextElement(); // parameters.append(attrName); // parameters.append("="); // parameters.append(request.getParameter(attrName)); // parameters.append("&"); // } // String paramStr = parameters.toString(); // if (StringUtils.isNotEmpty(paramStr)) { // paramStr = "?" + paramStr.substring(0, parameters.length() - 1); // return sb.toString() + paramStr; // } else { // return sb.toString(); // } // } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/servlet/AccessControlInterceptor.java
Java
gpl3
3,608
package com.infindo.appcreate.zzyj.servlet; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.json.MappingJacksonJsonView; public class MappingJacksonJsonpView extends MappingJacksonJsonView { public static final String DEFAULT_CONTENT_TYPE = "application/javascript"; @Override public String getContentType() { return DEFAULT_CONTENT_TYPE; } @Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { if ("GET".equals(request.getMethod().toUpperCase())) { @SuppressWarnings("unchecked") Map<String, String[]> params = request.getParameterMap(); if (params.containsKey("callback")) { response.getOutputStream().write(new String(params.get("callback")[0] + "(").getBytes()); super.render(model, request, response); response.getOutputStream().write(new String(");").getBytes()); response.setContentType("application/javascript"); } else { super.render(model, request, response); } } else { super.render(model, request, response); } } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/servlet/MappingJacksonJsonpView.java
Java
gpl3
1,223
package com.infindo.appcreate.zzyj.servlet; public class AppConfig { private static AppConfig appConfig = null; private String resDownload; private String callBack; private String workDirName; private String iosSrcDir; private String iosDownload; private String iosUser; private String androidSdkDir; private String androidSrcDir; private String androidDownload; private String webUrl; public static AppConfig getInstanceOfSpring() { if (appConfig == null) { appConfig = (AppConfig)SpringUtil.getBean("appConfig"); } return appConfig; } public String getResDownload() { return resDownload; } public void setResDownload(String resDownload) { this.resDownload = resDownload; } public String getCallBack() { return callBack; } public void setCallBack(String callBack) { this.callBack = callBack; } public String getWorkDirName() { return workDirName; } public void setWorkDirName(String workDirName) { this.workDirName = workDirName; } public String getAndroidDownload() { return androidDownload; } public void setAndroidDownload(String androidDownload) { this.androidDownload = androidDownload; } public String getIosDownload() { return iosDownload; } public void setIosDownload(String iosDownload) { this.iosDownload = iosDownload; } public String getAndroidSdkDir() { return androidSdkDir; } public void setAndroidSdkDir(String androidSdkDir) { this.androidSdkDir = androidSdkDir; } public String getAndroidSrcDir() { return androidSrcDir; } public void setAndroidSrcDir(String androidSrcDir) { this.androidSrcDir = androidSrcDir; } public String getIosSrcDir() { return iosSrcDir; } public void setIosSrcDir(String iosSrcDir) { this.iosSrcDir = iosSrcDir; } public String getIosUser() { return iosUser; } public void setIosUser(String iosUser) { this.iosUser = iosUser; } public String getWebUrl() { return webUrl; } public void setWebUrl(String webUrl) { this.webUrl = webUrl; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/servlet/AppConfig.java
Java
gpl3
2,395
package com.infindo.appcreate.zzyj.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.infindo.appcreate.zzyj.util.Constant; import com.infindo.appcreate.zzyj.util.FileUtil; import com.infindo.appcreate.zzyj.util.RequestObserver; public class SingleFileUploader extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestObserver.observe(request); PrintWriter writer = response.getWriter(); try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(10240000); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(10002400000l); upload.setSizeMax(10002400000l); upload.setHeaderEncoding("UTF-8"); String sn = ""; String category = ""; FileItem fileItem = null; List<?> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (!item.isFormField() && item.getName().length() > 0) { fileItem = item; } else if (item.isFormField() && item.getFieldName().equals("category")) { category = item.getString(); } else if (item.isFormField() && item.getFieldName().equals("sn")) { sn = item.getString(); } } String dateString = new SimpleDateFormat("yyMMdd") .format(new Date()); String folderRelativePath = Constant.PATH_UPLOAD + "/" + category + "/" + dateString + "/"; String baseFolder = this.getServletConfig().getServletContext() .getRealPath("/").replace("\\", "/"); String folderAbsolutePath = baseFolder + folderRelativePath; String fullAbsolutePath = ""; String fullRelativePath = ""; File folder = new File(folderAbsolutePath); if (!folder.exists()) { folder.mkdirs(); } if (fileItem == null) { writer.print("{code:'-1', sn:'" + sn + "', filePath:'" + fullRelativePath + "'}"); return; } String extName = FileUtil.getExtension(fileItem.getName(), "jpg"); String fileName = new DecimalFormat("00000000").format(Math .random() * 100000000) + "." + extName; fullAbsolutePath = folderAbsolutePath + fileName; fullRelativePath = folderRelativePath + fileName; File file = new File(fullAbsolutePath); if (file.exists()) { file.delete(); } fileItem.write(new File(fullAbsolutePath)); response.setStatus(response.SC_OK); writer.print("{code:'0', sn:'" + sn + "', filePath:'" + fullRelativePath + "'}"); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{}"); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/servlet/SingleFileUploader.java
Java
gpl3
3,533
package com.infindo.appcreate.zzyj.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.Properties; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import com.infindo.appcreate.zzyj.util.Constant; public class SysListener extends HttpServlet implements ServletContextListener { private static final long serialVersionUID = 0xe5a9f33cc18dab6L; private static final Logger logger = LoggerFactory .getLogger(SysListener.class); public void contextInitialized(ServletContextEvent sce) { logger.info("ContextInitialized START..."); System.setProperty("java.awt.headless", "true"); System.setProperty("jmagick.systemclassloader", "no"); String rootpath = sce.getServletContext().getRealPath("/"); if (rootpath != null) rootpath = rootpath.replaceAll("\\\\", "/"); else rootpath = "/"; if (!rootpath.endsWith("/")) rootpath = (new StringBuilder()).append(rootpath).append("/") .toString(); Constant.SYSTEM_ROOT_PATH = rootpath; Constant.CONTENT_PATH = sce.getServletContext().getContextPath(); //HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest(); // String str=File.separator; // String p = str+"WEB-INF"+str+"classes"+str+"appConfig.properties"; // InputStream path=this.getServletContext().getResourceAsStream(p); // // Properties pros = new Properties(); // try { // pros.load(path); // } catch (IOException ex) { // System.out.println("file is not exist"); // } // Constant.IOS_APP_BUILD_DIR = pros.getProperty("username"); } public void contextDestroyed(ServletContextEvent servletcontextevent) { } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/servlet/SysListener.java
Java
gpl3
2,275
package com.infindo.appcreate.zzyj.servlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; public class ExceptionHandler implements HandlerExceptionResolver { private Log log = LogFactory.getLog(getClass()); public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { log.warn("Handle exception: " + ex.getClass().getName()); ex.printStackTrace(); String url = request.getRequestURL().toString(); // // mobile webpage error // if (url.indexOf("/mobi") > 0 || url.indexOf("/a/") > 0) { // return new ModelAndView("redirect:/nav/mobiError"); // } // // // frontend site error // if (url.indexOf("/front") > 0) { // return new ModelAndView("redirect:/nav/frontError"); // } // // // admin site error // if (url.indexOf("/back") > 0) { // return new ModelAndView("redirect:/nav/backError"); // } // // return new ModelAndView("redirect:/nav/frontError"); return null; } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/servlet/ExceptionHandler.java
Java
gpl3
1,263
package com.infindo.appcreate.zzyj.hibernet; import java.sql.Types; import java.util.Properties; import org.hibernate.cfg.reveng.DelegatingReverseEngineeringStrategy; import org.hibernate.cfg.reveng.ReverseEngineeringStrategy; import org.hibernate.cfg.reveng.TableIdentifier; /** * This class customizes the implementation of * DelegatingReverseEngineeringStrategy. It controls the way of the primary keys * are generated. The method getTableIdentifierStrategyName specifies the * choosen strategy for pk generation - in this case Oracle sequences are being * used. The method getTableIdentifierProperties alters the way the sequence * name is created. * * @author Nikolai Gagov * */ public class CustomReverseEngineeringStrategy extends DelegatingReverseEngineeringStrategy { /** * @param delegate */ public CustomReverseEngineeringStrategy(ReverseEngineeringStrategy delegate) { super(delegate); } @Override public String getTableIdentifierStrategyName(TableIdentifier tableIdentifier) { return "sequence"; } @Override public Properties getTableIdentifierProperties( TableIdentifier tableIdentifier) { final String name = tableIdentifier.getName(); Properties p = super.getTableIdentifierProperties(tableIdentifier); if (p == null) { p = new Properties(); } if (name != null) { p.put("sequence", name.toLowerCase() + "_seq"); p.put("generatorName", name.toLowerCase() + "_seq_gen"); } return p; } @Override public String columnToHibernateTypeName(TableIdentifier table, String columnName, int sqlType, int length, int precision, int scale, boolean nullable, boolean generatedIdentifier) { String result = null; switch (sqlType) { case Types.DATE: case Types.TIME: case Types.TIMESTAMP: { result = "timestamp"; break; } default: { result = super.columnToHibernateTypeName(table, columnName, sqlType, length, precision, scale, nullable, generatedIdentifier); break; } } if (table.getName().toLowerCase().indexOf("uvst") >= 0) { System.out.println("columnToHibernateTypeName = " + result + ", table = " + table + ", columnName = " + columnName + ", sqlType = " + sqlType + ", length = " + length + ", precision = " + precision + ", scale = " + scale + ", nullable = " + nullable + ", generatedIdentifier = " + generatedIdentifier); } return result; } @Override public String tableToCompositeIdName(TableIdentifier table) { String result = super.tableToCompositeIdName(table); if (table.getName().toLowerCase().indexOf("uvst") >= 0) { System.out.println("tableToCompositeIdName = " + result + ", table = " + table); } return result; } @Override public String classNameToCompositeIdName(String arg0) { return super.classNameToCompositeIdName(arg0); } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/hibernet/CustomReverseEngineeringStrategy.java
Java
gpl3
2,938
package com.infindo.appcreate.zzyj.hibernet; import java.util.Properties; import org.hibernate.mapping.KeyValue; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.SimpleValue; import org.hibernate.tool.hbm2x.Cfg2JavaTool; import org.hibernate.tool.hbm2x.pojo.EntityPOJOClass; /** * This class extends EntityPOJOClass in order to override the generation of * sequence generators. It retreives the settings for sequence and generator * from properties already set inside the Reverse Engineering Strategy * * @author Nikolai Gagov * */ public class CustomEntityPojoClass extends EntityPOJOClass { public CustomEntityPojoClass(PersistentClass clazz, Cfg2JavaTool cfg) { super(clazz, cfg); } /* * (non-Javadoc) * * @see org.hibernate.tool.hbm2x.pojo.POJOClass#generateAnnIdGenerator() */ @Override public String generateAnnIdGenerator() { final KeyValue identifier = ((PersistentClass) getDecoratedObject()) .getIdentifier(); if (identifier instanceof SimpleValue) { final SimpleValue simpleValue = (SimpleValue) identifier; final String strategy = simpleValue .getIdentifierGeneratorStrategy(); if ("sequence".equals(strategy)) { final Properties properties = simpleValue .getIdentifierGeneratorProperties(); final String generatorName = properties.getProperty( "generatorName", ""); final StringBuffer wholeString = new StringBuffer(" "); final StringBuffer id = new StringBuffer().append("@").append( importType("javax.persistence.Id")); id.append(" @") .append(importType("javax.persistence.GeneratedValue")) .append('(') .append("strategy=") .append(staticImport( "javax.persistence.GenerationType", "SEQUENCE")) .append(", generator=\"").append(generatorName) .append("\"").append(')'); buildAnnSequenceGenerator(wholeString, properties); wholeString.append(id); return wholeString.toString(); } } return super.generateAnnIdGenerator(); } private void buildAnnSequenceGenerator(StringBuffer wholeString, Properties properties) { wholeString .append("@") .append(importType("javax.persistence.SequenceGenerator") + "(name=\"" + properties.getProperty("generatorName", "") + "\", sequenceName=\"") .append(properties.getProperty( org.hibernate.id.SequenceGenerator.SEQUENCE, "")) .append("\")").append("\n "); } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/hibernet/CustomEntityPojoClass.java
Java
gpl3
2,548
package com.infindo.appcreate.zzyj.dao; import org.springframework.stereotype.Repository; import com.infindo.appcreate.zzyj.entity.SysUser; @Repository public class UserDaoImpl extends GenericHibernateDao<SysUser, Long> implements UserDao { }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/dao/UserDaoImpl.java
Java
gpl3
260
package com.infindo.appcreate.zzyj.dao; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.LockMode; import org.hibernate.criterion.DetachedCriteria; public interface GenericDao<T extends Serializable, PK extends Serializable> { // --------------------CRUD-------------------- // 根据主键获取实体。如果没有相应的实体,返回 null。 public T get(PK id); // 根据主键获取实体并加锁。如果没有相应的实体,返回 null。 public T getWithLock(PK id, LockMode lock); // 根据主键获取实体。如果没有相应的实体,抛出异常。 public T load(PK id); // 根据主键获取实体并加锁。如果没有相应的实体,抛出异常。 public T loadWithLock(PK id, LockMode lock); // 获取全部实体。 public List<T> loadAll(); // loadAllWithLock() ? // 更新实体 public void update(T entity); // 更新实体并加锁 public void updateWithLock(T entity, LockMode lock); // 存储实体到数据库 public void save(T entity); // saveWithLock() // 增加或更新实体 public void saveOrUpdate(T entity); // 增加或更新集合中的全部实体 public void saveOrUpdateAll(Collection<T> entities); // 删除指定的实体 public void delete(T entity); // 加锁并删除指定的实体 public void deleteWithLock(T entity, LockMode lock); // 根据主键删除指定实体 public void deleteByKey(PK id); // 根据主键加锁并删除指定的实体 public void deleteByKeyWithLock(PK id, LockMode lock); // 删除集合中的全部实体 public void deleteAll(Collection<T> entities); // --------------------HSQL-------------------- // 使用HSQL语句直接增加、更新、删除实体 public int bulkUpdate(String queryString); // 使用带参数的HSQL语句增加、更新、删除实体 public int bulkUpdate(String queryString, Object[] values); // 使用HSQL语句检索数据 public List find(String queryString); // 使用带参数的HSQL语句检索数据 public List find(String queryString, Object[] values); // 使用带命名的参数的HSQL语句检索数据 public List findByNamedParam(String queryString, String[] paramNames, Object[] values); // 使用命名的HSQL语句检索数据 public List findByNamedQuery(String queryName); // 使用带参数的命名HSQL语句检索数据 public List findByNamedQuery(String queryName, Object[] values); // 使用带命名参数的命名HSQL语句检索数据 public List findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values); // 使用HSQL语句检索数据,返回 Iterator public Iterator iterate(String queryString); // 使用带参数HSQL语句检索数据,返回 Iterator public Iterator iterate(String queryString, Object[] values); // 关闭检索返回的 Iterator public void closeIterator(Iterator it); // --------------------Criteria-------------------- // 创建与会话无关的检索标准对象 public DetachedCriteria createDetachedCriteria(); // 创建与会话绑定的检索标准对象 public Criteria createCriteria(); // 使用指定的检索标准检索数据 public List findByCriteria(DetachedCriteria criteria); // 使用指定的检索标准检索数据,返回部分记录 public List findByCriteria(DetachedCriteria criteria, int firstResult, int maxResults); // 使用指定的实体及属性检索(满足除主键外属性=实体值)数据 public List<T> findEqualByEntity(T entity, String[] propertyNames); // 使用指定的实体及属性(非主键)检索(满足属性 like 串实体值)数据 public List<T> findLikeByEntity(T entity, String[] propertyNames); // 使用指定的检索标准检索数据,返回指定范围的记录 public Integer getRowCount(DetachedCriteria criteria); // 使用指定的检索标准检索数据,返回指定统计值 public Object getStatValue(DetachedCriteria criteria, String propertyName, String StatName); // -------------------------------- Others -------------------------------- // 加锁指定的实体 public void lock(T entity, LockMode lockMode); // 强制初始化指定的实体 public void initialize(Object proxy); // 强制立即更新缓冲数据到数据库(否则仅在事务提交时才更新) public void flush(); }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/dao/GenericDao.java
Java
gpl3
4,574
package com.infindo.appcreate.zzyj.dao; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.commons.beanutils.PropertyUtils; import org.hibernate.Criteria; import org.hibernate.LockMode; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Example; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; @SuppressWarnings("unchecked") public class GenericHibernateDao<T extends Serializable, PK extends Serializable> extends HibernateDaoSupport implements GenericDao<T, PK> { // 实体类类型(由构造方法自动赋值) private Class<T> entityClass; // 构造方法,根据实例类自动获取实体类类型 public GenericHibernateDao() { this.entityClass = null; Class c = getClass(); Type t = c.getGenericSuperclass(); if (t instanceof ParameterizedType) { Type[] p = ((ParameterizedType) t).getActualTypeArguments(); this.entityClass = (Class<T>) p[0]; } } // -------------------- 基本检索、增加、修改、删除操作 -------------------- // 根据主键获取实体。如果没有相应的实体,返回 null。 public T get(PK id) { return (T) getHibernateTemplate().get(entityClass, id); } // 根据主键获取实体并加锁。如果没有相应的实体,返回 null。 public T getWithLock(PK id, LockMode lock) { T t = (T) getHibernateTemplate().get(entityClass, id, lock); if (t != null) { this.flush(); // 立即刷新,否则锁不会生效。 } return t; } // 根据主键获取实体。如果没有相应的实体,抛出异常。 public T load(PK id) { return (T) getHibernateTemplate().load(entityClass, id); } // 根据主键获取实体并加锁。如果没有相应的实体,抛出异常。 public T loadWithLock(PK id, LockMode lock) { T t = (T) getHibernateTemplate().load(entityClass, id, lock); if (t != null) { this.flush(); // 立即刷新,否则锁不会生效。 } return t; } // 获取全部实体。 public List<T> loadAll() { return (List<T>) getHibernateTemplate().loadAll(entityClass); } // loadAllWithLock() ? // 更新实体 public void update(T entity) { getHibernateTemplate().update(entity); } // 更新实体并加锁 public void updateWithLock(T entity, LockMode lock) { getHibernateTemplate().update(entity, lock); this.flush(); // 立即刷新,否则锁不会生效。 } // 存储实体到数据库 public void save(T entity) { getHibernateTemplate().save(entity); } // saveWithLock()? // 增加或更新实体 public void saveOrUpdate(T entity) { getHibernateTemplate().saveOrUpdate(entity); } // 增加或更新集合中的全部实体 public void saveOrUpdateAll(Collection<T> entities) { getHibernateTemplate().saveOrUpdateAll(entities); } // 删除指定的实体 public void delete(T entity) { getHibernateTemplate().delete(entity); } // 加锁并删除指定的实体 public void deleteWithLock(T entity, LockMode lock) { getHibernateTemplate().delete(entity, lock); this.flush(); // 立即刷新,否则锁不会生效。 } // 根据主键删除指定实体 public void deleteByKey(PK id) { this.delete(this.load(id)); } // 根据主键加锁并删除指定的实体 public void deleteByKeyWithLock(PK id, LockMode lock) { this.deleteWithLock(this.load(id), lock); } // 删除集合中的全部实体 public void deleteAll(Collection<T> entities) { getHibernateTemplate().deleteAll(entities); } // -------------------- HSQL ---------------------------------------------- // 使用HSQL语句直接增加、更新、删除实体 public int bulkUpdate(String queryString) { return getHibernateTemplate().bulkUpdate(queryString); } // 使用带参数的HSQL语句增加、更新、删除实体 public int bulkUpdate(String queryString, Object[] values) { return getHibernateTemplate().bulkUpdate(queryString, values); } // 使用HSQL语句检索数据 public List find(String queryString) { return getHibernateTemplate().find(queryString); } // 使用带参数的HSQL语句检索数据 public List find(String queryString, Object[] values) { return getHibernateTemplate().find(queryString, values); } // 使用带命名的参数的HSQL语句检索数据 public List findByNamedParam(String queryString, String[] paramNames, Object[] values) { return getHibernateTemplate().findByNamedParam(queryString, paramNames, values); } // 使用命名的HSQL语句检索数据 public List findByNamedQuery(String queryName) { return getHibernateTemplate().findByNamedQuery(queryName); } // 使用带参数的命名HSQL语句检索数据 public List findByNamedQuery(String queryName, Object[] values) { return getHibernateTemplate().findByNamedQuery(queryName, values); } // 使用带命名参数的命名HSQL语句检索数据 public List findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values) { return getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramNames, values); } // 使用HSQL语句检索数据,返回 Iterator public Iterator iterate(String queryString) { return getHibernateTemplate().iterate(queryString); } // 使用带参数HSQL语句检索数据,返回 Iterator public Iterator iterate(String queryString, Object[] values) { return getHibernateTemplate().iterate(queryString, values); } // 关闭检索返回的 Iterator public void closeIterator(Iterator it) { getHibernateTemplate().closeIterator(it); } // -------------------------------- Criteria ------------------------------ // 创建与会话无关的检索标准 public DetachedCriteria createDetachedCriteria() { return DetachedCriteria.forClass(this.entityClass); } // 创建与会话绑定的检索标准 public Criteria createCriteria() { return this.createDetachedCriteria().getExecutableCriteria( this.getSession()); } // 检索满足标准的数据 public List findByCriteria(DetachedCriteria criteria) { return getHibernateTemplate().findByCriteria(criteria); } // 检索满足标准的数据,返回指定范围的记录 public List findByCriteria(DetachedCriteria criteria, int firstResult, int maxResults) { return getHibernateTemplate().findByCriteria(criteria, firstResult, maxResults); } // 使用指定的实体及属性检索(满足除主键外属性=实体值)数据 public List<T> findEqualByEntity(T entity, String[] propertyNames) { Criteria criteria = this.createCriteria(); Example exam = Example.create(entity); exam.excludeZeroes(); String[] defPropertys = getSessionFactory().getClassMetadata( entityClass).getPropertyNames(); for (String defProperty : defPropertys) { int ii = 0; for (ii = 0; ii < propertyNames.length; ++ii) { if (defProperty.equals(propertyNames[ii])) { criteria.addOrder(Order.asc(defProperty)); break; } } if (ii == propertyNames.length) { exam.excludeProperty(defProperty); } } criteria.add(exam); return (List<T>) criteria.list(); } // 使用指定的实体及属性检索(满足属性 like 串实体值)数据 public List<T> findLikeByEntity(T entity, String[] propertyNames) { Criteria criteria = this.createCriteria(); for (String property : propertyNames) { try { Object value = PropertyUtils.getProperty(entity, property); if (value instanceof String) { criteria.add(Restrictions.like(property, (String) value, MatchMode.ANYWHERE)); criteria.addOrder(Order.asc(property)); } else { criteria.add(Restrictions.eq(property, value)); criteria.addOrder(Order.asc(property)); } } catch (Exception ex) { // 忽略无效的检索参考数据。 } } return (List<T>) criteria.list(); } // 使用指定的检索标准获取满足标准的记录数 public Integer getRowCount(DetachedCriteria criteria) { criteria.setProjection(Projections.rowCount()); List list = this.findByCriteria(criteria, 0, 1); return (Integer) list.get(0); } // 使用指定的检索标准检索数据,返回指定统计值(max,min,avg,sum) public Object getStatValue(DetachedCriteria criteria, String propertyName, String StatName) { if (StatName.toLowerCase().equals("max")) criteria.setProjection(Projections.max(propertyName)); else if (StatName.toLowerCase().equals("min")) criteria.setProjection(Projections.min(propertyName)); else if (StatName.toLowerCase().equals("avg")) criteria.setProjection(Projections.avg(propertyName)); else if (StatName.toLowerCase().equals("sum")) criteria.setProjection(Projections.sum(propertyName)); else return null; List list = this.findByCriteria(criteria, 0, 1); return list.get(0); } // -------------------------------- Others -------------------------------- // 加锁指定的实体 public void lock(T entity, LockMode lock) { getHibernateTemplate().lock(entity, lock); } // 强制初始化指定的实体 public void initialize(Object proxy) { getHibernateTemplate().initialize(proxy); } // 强制立即更新缓冲数据到数据库(否则仅在事务提交时才更新) public void flush() { getHibernateTemplate().flush(); } }
zzyj-mobi
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/dao/GenericHibernateDao.java
Java
gpl3
9,824