text:
<img src="http://nonvolatilecomputing.github.io/Mnemonic/images/mnemonic_logo.png" width=200 />

================================

Apache Mnemonic is an advanced hybrid memory storages oriented library, it proposed a non-volatile/durable Java object model and durable computing service that bring several advantages to significantly improve the performance of massive real-time data processing/analytics. developers are able to use this library to design their cache-less and SerDe-less high performance applications.

### Features:

* In-place data storage on local non-volatile memory
* Durable Object Model
* Object graphs lazy loading & sharing
* Auto-reclaim memory resources and Mnemonic objects
* Hierarchical cache pool for massive data caching
* Extensible memory services for new device adoption and allocation optimization
* Durable data structure collection(WIP)
* Durable computing service
* Minimize memory footprint on Java heap
* Reduce GC Overheads as the following chart shown (collected from Apache Spark experiments)

![Mnemonic_GC_stats](http://nonvolatilecomputing.github.io/Mnemonic/images/mnemonic_GC_stats.png)

### Mnemonic Way

![Mnemonic_Way](http://nonvolatilecomputing.github.io/Mnemonic/images/mnemonic_way.png)

![Mnemonic_Modes](http://nonvolatilecomputing.github.io/Mnemonic/images/mnemonic_modes.png)

### How to use it ?

#### Define a Non-Volatile class:

```java
/**
 * a durable class should be abstract, implement Durable interface and marked with @DurableEntity annotation
 */
@DurableEntity
public abstract class Person<E> implements Durable, Comparable<Person<E>> {
        E element; // Generic Type

        /**
         * callback for this durable object creation
         */
        @Override
        public void initializeAfterCreate() {
                System.out.println("Initializing After Created");
        }

        /**
         * callback for this durable object recovery
         */
        @Override
        public void initializeAfterRestore() {
                System.out.println("Initializing After Restored");
        }

        /**
         * setup generic info manually to avoid performance penalty
         */
        @Override
        public void setupGenericInfo(EntityFactoryProxy[] efproxies, GenericField.GType[] gftypes) {

        }

        @Test
        public void testOutput() throws RetrieveDurableEntityError {
                System.out.printf("Person %s, Age: %d ( %s ) \n", getName(), getAge(),
                                null == getMother()? "No Recorded Mother" : "Has Recorded Mother");
        }

        public int compareTo(Person<E> anotherPerson) {
                int ret = 0;
                if (0 == ret) ret = getAge().compareTo(anotherPerson.getAge());
                if (0 == ret) ret = getName().compareTo(anotherPerson.getName());
                return ret;
        }

        /**
         * Getters and Setters for non-volatile fields marked with @DurableGetter and @DurableSetter
         */
        @DurableGetter(Id = 1L)
        abstract public Short getAge();
        @DurableSetter
        abstract public void setAge(Short age);

        @DurableGetter(Id = 2L)
        abstract public String getName() throws RetrieveDurableEntityError;
        @DurableSetter
        abstract public void setName(String name, boolean destroy) throws OutOfPersistentMemory, RetrieveDurableEntityError;

        @DurableGetter(Id = 3L)
        abstract public Person<E> getMother() throws RetrieveDurableEntityError;
        @DurableSetter
        abstract public void setMother(Person<E> mother, boolean destroy) throws RetrieveDurableEntityError;

        @DurableGetter(Id = 4L)
        abstract public Person<E> getFather() throws RetrieveDurableEntityError;
        @DurableSetter
        abstract public void setFather(Person<E> mother, boolean destroy) throws RetrieveDurableEntityError;
}

```

#### Use a non-volatile class:

##### Setup an allocator for non-volatile object graphs.
```java
        // create an allocator instance
        NonVolatileMemAllocator act = new NonVolatileMemAllocator(1024 * 1024 * 8, "./pobj_person.dat", true);

        // fetch handler store capacity from this non-volatile storage managed by this allocator
        KEYCAPACITY = act.handlerCapacity();
        ....
        // close it after use
        act.close();
```

##### Generate structured non-volatile objects.
```java
        // create a new non-volatile person object from this specific allocator
        person = PersonFactory.create(act);

        // set attributes
        person.setAge((short)rand.nextInt(50));
        person.setName(String.format("Name: [%s]", UUID.randomUUID().toString()), true);

        // keep this person on non-volatile handler store
        act.setHandler(keyidx, person.getHandler());

        for (int deep = 0; deep < rand.nextInt(100); ++deep) {

                // create another person as mother
                mother = PersonFactory.create(act);
                mother.setAge((short)(50 + rand.nextInt(50)));
                mother.setName(String.format("Name: [%s]", UUID.randomUUID().toString()), true);

                // set the person's mother
                person.setMother(mother, true);

                person = mother;
        }

```
##### Use the non-volatile objects
```java
        for (long i = 0; i < KEYCAPACITY; ++i) {

                System.out.printf("----------Key %d--------------\n", i);
                // iterate non-volatile handlers from handler store of this specific allocator
                val = act.getHandler(i);
                if (0L == val) {
                        break;
                }

                // restore person objects from this specific allocator
                Person<Integer> person = PersonFactory.restore(act, val, true);

                while (null != person) {
                        person.testOutput();
                        // iterate all mother's ancestors
                        person = person.getMother();
                }
        }

```
##### Perform the durable native computing (e.g. printing) w/o packing/unpacking massive object graphs
```java
         // fetch print service
         GeneralComputingService gcsvr = Utils.getGeneralComputingService("print");
         // instantiate a value info for a value matrix
         ValueInfo vinfo = new ValueInfo();
         // instantiate a object stack
         List<long[][]> objstack = new ArrayList<long[][]>();
         // fill up with all durable object info in order
         objstack.add(firstnv.getNativeFieldInfo());
         objstack.add(person.getNativeFieldInfo());
         // configure the Id stack for each level of durable objects
         long[][] fidinfostack = {{2L, 1L}, {0L, 1L}};
         // configure the handler of a value matrix
         vinfo.handler = handler;
         // set translate table from handler's allocator
         vinfo.transtable = m_act.getTranslateTable();
         // specify the durable type of value
         vinfo.dtype = DurableType.SHORT;
         // generate frames for this value matri from both stacks
         vinfo.frames = Utils.genNativeParamForm(objstack, fidinfostack);
         // form an array of value infos
         ValueInfo[] vinfos = {vinfo};
         // perform the print operation
         gcsvr.perform(vinfos);
```

### How to build it ?

Please see the file LICENSE for information on how this library is licensed.

* **mnemonic-core** -- the submodule project for core
* **mnemonic-collections** -- the submodule project for generic collections
* **mnemonic-examples** -- the submodule project for examples, Please refer to the testcases of respective module as complete examples.
* **mnemonic-memory-services/mnemonic-pmalloc-service** -- the submodule project for pmalloc memory service
* **mnemonic-memory-services/mnemonic-nvml-vmem-service** -- the submodule project for vmem memory service
* **mnemonic-memory-services/mnemonic-nvml-pmem-service** -- the submodule project for pmem memory service
* **mnemonic-memory-services/service-dist** -- the location of extensive memory services (auto-generated)
* **mnemonic-computing-services/mnemonic-utilities-service** -- the submodule project for utilities computing service
* **mnemonic-computing-services/service-dist** -- the location of extensive computing services (auto-generated)

#### Durable Memory Service Comparison Table

|    Features                     |    NVML-VMEM    |    PMALLOC    |    NVML-PMEM    |
|---------------------------------|:---------------:|:-------------:|:---------------:|
|    Fixed   Durable K-V Store    |        NA       |       O       |        O        |
|    Support DOM                  |        O        |       O       |        O        |
|    Support DNCM                 |        O        |       O       |        O        |
|    Support OS X                 |        NA       |       O       |        NA       |
|    Memory Map Sync.             |        NA       |       O       |        O        |
|    PM Flush                     |        NA       |       NA      |        O        |
|    PM Drain                     |        NA       |       NA      |        O        |
|    PM Persist                   |        NA       |       NA      |        O        |
|    PM Atomic   Ops.             |        NA       |       NA      |        O        |
|    Performance                  |       High      |      High     |       Low       |

To build this library, you may need to install some required packages on the build system:

* **Maven** -- the building tool v3.2.1 or above [Required]
* **NVML** -- the NVM library (Please compile this library that was revised with 630862e82f) (http://pmem.io) [Optional if mnemonic-nvml-vmem-service/mnemonic-nvml-pmem-service are excluded, e.g. on MacOSX]
* **JDK** -- the Java Develop Kit 1.6 or above (please properly configure JAVA_HOME) [Required]
* **PMFS** -- the PMFS should be properly installed and configured on Linux system if you want to simulate read latency [Optional]
* **PMalloc** -- a supported durable memory native library(Latest) at https://github.com/NonVolatileComputing/pmalloc.git [Optional if mnemonic-pmalloc-service is excluded]

Once the build system is setup, this Library is built using this command at the top level:
```bash
  $ git clean -xdf # if pull from a git repo.
  $ mvn clean package install
```

To exclude a customized memory service for your platform e.g. OSX, note that if you excluded one or both memory services, some or all testcases/examples will fail since their dependent memory services are unavailable.
```bash
  $ git clean -xdf # if pull from a git repo.
  $ mvn -pl '!mnemonic-memory-services/mnemonic-nvml-vmem-service' clean package install
```

To install this package to local repository (required to run examples and testcases):
```bash
  $ mvn clean install
```

To run an example:
```bash
  $ # requires 'vmem' memory service to run, please refer to the code of test cases for more examples.
  $ mvn exec:exec -Pexample -pl mnemonic-examples
```

To run several test cases:
```bash
  $ # a testcase for module "mnemonic-core" that requires 'pmalloc' memory service to pass
  $ mvn -Dtest=DurablePersonNGTest test -pl mnemonic-core -DskipTests=false

  $ # a testcase for module "mnemonic-core" that requires 'pmalloc' memory service to pass
  $ mvn -Dtest=NonVolatileMemAllocatorNGTest test -pl mnemonic-core -DskipTests=false

  $ # a testcase for module "mnemonic-core" that requires 'vmem' memory service to pass
  $ mvn -Dtest=VolatileMemAllocatorNGTest test -pl mnemonic-core -DskipTests=false

  $ # a testcase for module "mnemonic-core" that requires 'vmem memory service to pass
  $ mvn -Dtest=MemClusteringNGTest test -pl mnemonic-core -DskipTests=false

  $ # a testcase for module "mnemonic-collection" that requires 'pmalloc' memory service to pass
  $ mvn -Dtest=DurableSinglyLinkedListNGTest  test -pl mnemonic-collections -DskipTests=false

  $ # a testcase for module "mnemonic-collection" that requires 'pmalloc' memory service to pass
  $ mvn -Dtest=DurablePersonNGTest  test -pl mnemonic-collections -DskipTests=false

  $ # a testcase for module "mnemonic-computing-services/mnemonic-utilities-service" that requires 'pmalloc' memory service to pass
  $ mvn -Dtest=DurableSinglyLinkedListNGPrintTest test -pl mnemonic-computing-services/mnemonic-utilities-service -DskipTests=false
```

### Where is the document ?
 * Source code comments
 * [API Documentation](http://nonvolatilecomputing.github.io/Mnemonic/apidocs/index.html)
 * [Mnemonic Presentation (.pdf)](https://wiki.apache.org/incubator/MnemonicProposal?action=AttachFile&do=get&target=Project_Mnemonic_Pub1.0.pdf)

### How to apply it for other projects ?
 * [Apache Spark Integration Demo](https://github.com/NonVolatileComputing/spark)
 * [Apache Arrow Integration Demo](https://github.com/NonVolatileComputing/arrow)


text:
namespace centipede::config {
namespace {

TEST(ConfigFileTest, AugmentedArgv) {
  const std::vector<std::string> kOrigArgv = {
      "--foo=bar",
      "--baz",
      "qux",
  };

  // None of the replacements match.
  {
    const AugmentedArgvWithCleanup augmented_argv{
        kOrigArgv,
        {
            {"--mismatching", "--mod_mismatching"},
        },
        nullptr};
    EXPECT_FALSE(augmented_argv.was_augmented());
    EXPECT_EQ(augmented_argv.argv()[0], kOrigArgv[0]);
    EXPECT_EQ(augmented_argv.argv()[1], kOrigArgv[1]);
    EXPECT_EQ(augmented_argv.argv()[2], kOrigArgv[2]);
  }

  {
    bool cleanup_worked = false;
    {
      const AugmentedArgvWithCleanup augmented_argv{
          kOrigArgv,
          {
              {"--foo", "--mod_foo"},
              {"bar", "mod_bar"},
              {"--baz", "--mod_baz"},
              {"qux", "mod_qux"},
          },
          [&cleanup_worked]() { cleanup_worked = true; }};
      const std::vector<std::string> kExpectedArgv = {
          "--mod_foo=mod_bar",
          "--mod_baz",
          "mod_qux",
      };
      EXPECT_TRUE(augmented_argv.was_augmented());
      EXPECT_EQ(augmented_argv.argv()[0], kExpectedArgv[0]);
      EXPECT_EQ(augmented_argv.argv()[1], kExpectedArgv[1]);
      EXPECT_EQ(augmented_argv.argv()[2], kExpectedArgv[2]);
    }
    EXPECT_TRUE(cleanup_worked);
  }
}

// TODO(ussuri): The rest of the module is tested by calling Centipede with
//  the new flags in centipede_main_cns_test.sh. Consider adding proper C++
//  tests here too.

}  // namespace
}  // namespace centipede::config

redpajama_set_name: RedPajamaGithub


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Batch;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Azure.Commands.Batch.Models
{
    internal class PSPagedEnumerable<T1, T2> : IPagedEnumerable<T1>
        where T1 : class
        where T2 : class
    {
        internal IPagedEnumerable<T2> omPagedEnumerable;
        private Func<T2, T1> mappingFunction;

        internal PSPagedEnumerable(IPagedEnumerable<T2> omPagedEnumerable, Func<T2, T1> mappingFunction)
        {
            if (omPagedEnumerable == null)
            {
                throw new ArgumentNullException("omAsyncEnumerable");
            }
            this.omPagedEnumerable = omPagedEnumerable;

            if (mappingFunction == null)
            {
                throw new ArgumentNullException("mappingFunction");
            }
            this.mappingFunction = mappingFunction;
        }

        IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return new PSPagedEnumerator<T1, T2>(this.omPagedEnumerable.GetPagedEnumerator(), this.mappingFunction);
        }

        // IEnumerable<T>
        public IEnumerator<T1> GetEnumerator()
        {
            return new PSPagedEnumerator<T1, T2>(this.omPagedEnumerable.GetPagedEnumerator(), this.mappingFunction);
        }

        // IPagedEnumerable
        public IPagedEnumerator<T1> GetPagedEnumerator()
        {
            return new PSPagedEnumerator<T1, T2>(this.omPagedEnumerable.GetPagedEnumerator(), this.mappingFunction);
        }

        internal static IEnumerable<T1> CreateWithMaxCount(
            IPagedEnumerable<T2> omAsyncEnumerable, Func<T2, T1> mappingFunction, int maxCount, Action logMaxCount = null)
        {
            PSPagedEnumerable<T1, T2> asyncEnumerable = new PSPagedEnumerable<T1, T2>(omAsyncEnumerable, mappingFunction);

            if (maxCount <= 0)
            {
                return asyncEnumerable;
            }
            else
            {
                if (logMaxCount != null)
                {
                    logMaxCount();
                }
                return asyncEnumerable.Take(maxCount);
            }
        }
    }

    internal class PSPagedEnumerator<T1, T2> : IPagedEnumerator<T1>, IEnumerator<T1>
        where T1 : class
        where T2 : class
    {
        internal IPagedEnumerator<T2> omEnumerator;
        private Func<T2, T1> mappingFunction;

        internal PSPagedEnumerator(IPagedEnumerator<T2> omEnumerator, Func<T2, T1> mappingFunction)
        {
            if (omEnumerator == null)
            {
                throw new ArgumentNullException("omEnumerator");
            }
            this.omEnumerator = omEnumerator;

            if (mappingFunction == null)
            {
                throw new ArgumentNullException("mappingFunction");
            }
            this.mappingFunction = mappingFunction;
        }

        object System.Collections.IEnumerator.Current
        {
            get
            {
                return this.Current;
            }
        }

        public T1 Current
        {
            get
            {
                return this.mappingFunction(this.omEnumerator.Current);
            }
        }

        public bool MoveNext()
        {
            return ((IEnumerator<T2>)this.omEnumerator).MoveNext();
        }

        public Task<bool> MoveNextAsync(CancellationToken cancellationToken)
        {
            return this.omEnumerator.MoveNextAsync(cancellationToken);
        }

        public Task ResetAsync(CancellationToken cancellationToken)
        {
            return this.omEnumerator.ResetAsync(cancellationToken);
        }

        public void Reset()
        {
            ((IEnumerator<T2>)this.omEnumerator).Reset();
        }

        public void Dispose()
        {
            this.omEnumerator.Dispose();
        }
    }
}


text:
<!DOCTYPE html>

  <title id="title">Error</title>

500

The page at this resource is causing a server error.


text:
extern NSString *const LAST_OPENED_PROJECT_PATH;
extern NSString *const LAST_VISIT_LEFT_PANEL_VISIBLE;
extern NSString *const LAST_VISIT_BOTTOM_PANEL_VISIBLE;
extern NSString *const LAST_VISIT_RIGHT_PANEL_VISIBLE;
extern NSString *const SECURITY_SCOPED_BOOKMARKS_KEY;


text:
using System;
using System.Collections.Generic;
using FullSerializer;
using UDBase.Controllers.LogSystem;

namespace UDBase.Utils.Json.Fullserializer {
	sealed class FsJsonListContainer : ILogContext {
		class NodeCache : Dictionary<string, Dictionary<string, object>> { }

		readonly FsJsonNodeContainer      _nodeContainer;
		readonly Dictionary<Type, string> _names      = new Dictionary<Type, string>();
		readonly fsSerializer             _serializer = new fsSerializer();
		readonly NodeCache                _nodeCache  = new NodeCache();

		ULogger _log;

		public FsJsonListContainer(FsJsonNodeContainer nodeContainer, ILog log) {
			_nodeContainer = nodeContainer;
			_log = log.CreateLogger(this);
		}

		public void Add<T>(string name) {
			var type = typeof(T);
			if( !_names.ContainsKey(type) ) {
				_names.Add(type, name);
			} else {
				_log.ErrorFormat("Type already exist: {0}!", type);
			}
		}

		public T LoadItem<T>(string nodeName, string itemName, bool autoFill) {
			Dictionary<string, object> cachedNode;
			if( _nodeCache.TryGetValue(nodeName, out cachedNode) ) {
				object value;
				cachedNode.TryGetValue(itemName, out value);
				return (T)value;
			} else {
				var node = _nodeContainer.LoadNode(nodeName);
				if( node != null ) {
					var nodeContent = node.AsDictionary;
					CacheContent<T>(nodeName, nodeContent);
					if( nodeContent != null ) {
						fsData fsValue;
						nodeContent.TryGetValue(itemName, out fsValue);
						T value = default(T);
						_serializer.TryDeserialize(fsValue, ref value);
						return value;
					}
				}
			}
			_log.ErrorFormat("ListContainer.LoadItem: Can't find node: {0}!", typeof(T));
			return autoFill ? Activator.CreateInstance<T>() : default(T);
		}

		void CacheContent<T>(string nodeName, Dictionary<string, fsData> nodeContent) {
			var nodeContentCache = new Dictionary<string, object>();
			var nodeContentIter = nodeContent.GetEnumerator();
			while( nodeContentIter.MoveNext() ) {
				var current = nodeContentIter.Current;
				T value = default(T);
				_serializer.TryDeserialize(current.Value, ref value);
				nodeContentCache.Add(current.Key, value);
			}
			_nodeCache.Add(nodeName, nodeContentCache);
		}

		public T LoadItem<T>(string itemName, bool autoFill) {
			string nodeName;
			if( _names.TryGetValue(typeof(T), out nodeName) ) {
				return LoadItem<T>(nodeName, itemName, autoFill);
			}
			return autoFill ? Activator.CreateInstance<T>() : default(T);
		}

		public Dictionary<string, T> LoadDict<T>() {
			string nodeName;
			if( _names.TryGetValue(typeof(T), out nodeName) ) {
				var node = _nodeContainer.LoadNode(nodeName);
				if( node != null ) {
					var nodeContent = node.AsDictionary;
					if( nodeContent != null ) {
						var dict = new Dictionary<string, T>();
						foreach( var itemName in nodeContent.Keys ) {
							fsData fsValue;
							nodeContent.TryGetValue(itemName, out fsValue);
							T value = default(T);
							_serializer.TryDeserialize(fsValue, ref value);
							dict.Add(itemName, value);
						}
						return dict;
					}
				}
			}
			return null;
		}
	}
}


text:
import dedemo.BasePathologyAnnotation;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.common.dynamicextensions.entitymanager.EntityManager;
import edu.common.dynamicextensions.entitymanager.EntityManagerInterface;
import edu.common.dynamicextensions.entitymanager.EntityManagerUtil;
import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException;
import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException;
import edu.wustl.clinportal.domain.ClinicalStudy;
import edu.wustl.clinportal.domain.ClinicalStudyEvent;
import edu.wustl.clinportal.domain.ClinicalStudyEventEntry;
import edu.wustl.clinportal.domain.ClinicalStudyRegistration;
import edu.wustl.clinportal.domain.EventEntry;
import edu.wustl.clinportal.domain.Participant;
import edu.wustl.clinportal.domain.RecordEntry;
import edu.wustl.clinportal.domain.StudyFormContext;
import edu.wustl.clinportal.domain.User;
import gov.nih.nci.system.applicationservice.ApplicationService;
import gov.nih.nci.system.applicationservice.ApplicationServiceProvider;
import gov.nih.nci.system.comm.client.ClientSession;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * ClientDemo.java demonstrates various ways to execute searches with and without
 * using Application Service Layer (convenience layer that abstracts building criteria
 * Uncomment different scenarios below to demonstrate the various types of searches
 */

public class ClientDemo
{

	private final static String STATIC_ENTITY_CLASS_NAME = "edu.wustl.clinportal.domain.RecordEntry";
	private final static String STATIC_CONDITION_ENTITY_CLASS_NAME = "edu.wustl.clinportal.domain.ClinicalStudyEvent";

	private final static String DE_CLASS_NAME = "BasePathologyAnnotation";

	static ApplicationService appServiceDEEntity = null;
	static ApplicationService appServiceCatissue = null;

	private static Long PARTICIPANT_IDENTIFIER = new Long(1);
	private static Long CLINICAL_STUDY_EVENT_ID = new Long(1);
	private static Long CLINICAL_STUDY_EVENT_ENTRY_ID = new Long(4);

	private static String CLINICAL_STUDY_TITLE = "CS44";
	private static String IRB_IDENTIFIER = "4444";
	private static String COLLECTION_POINT_LABEL = "Label44";

	private static String APPLICATION_URL = "https://localhost:8443/clinportal/http/remoteService";
	private static String JBOSS_HOME = "E:/jboss-4.2.2.GA";

	private static String USERNAME = "admin@admin.com";
	private static String PASSWORD = "Login123";

	static  List eventEntryList = new ArrayList();

	private static EntityManagerInterface entityManager = EntityManager.getInstance();

	public static void main(String[] args)
	{
		System.out.println("*** ClientDemo...");

		try
		{

			System.setProperty("javax.net.ssl.trustStore", JBOSS_HOME + "/server/default/conf/chap8.keystore");

			//caTissue Service
			initCaTissueService();
			ClientSession cs = ClientSession.getInstance();
			cs.startSession(USERNAME, PASSWORD);

			createClinicalStudy();

			/*EventEntry eventEntry = createEventEntry();

			RecordEntry re= new RecordEntry();
			re.setEventEntry(eventEntry);

			Long entityid = entityManager.getEntityId("BasePathologyAnnotation");
			Long containerID = entityManager.getContainerByEntityIdentifier(entityid).getId();
			StudyFormContext studyFormContext = getStudyFormContext(containerID);

			re.setStudyFormContext(studyFormContext);
			RecordEntry recordEntry = (RecordEntry)appServiceCatissue.createObject(re);

			BasePathologyAnnotation bp = new BasePathologyAnnotation();
			EntityInterface entityInterface = entityManager.getEntityByName("BasePathologyAnnotation");
			Long nextid = EntityManagerUtil.getNextIdentifier(entityInterface.getTableProperties().getName());
			bp.setId(nextid);
			bp.setComments("My Comments ABC");
			dedemo.RecordEntry dedemoRecordEntry  = new dedemo.RecordEntry();
			dedemoRecordEntry.setId(recordEntry.getId());
			bp.setRecordEntry(dedemoRecordEntry);

			initDEService();

			appServiceDEEntity.createObject(bp);*/

//			System.out.println("cid"+entityManager.getNextIdentifierForEntity("BasePathologyAnnotation"));
//			StudyFormContext sf = new StudyFormContext();
//			sf.setContainerId(cid);
//			ClinicalStudy cstudy = new ClinicalStudy();
//			cstudy.setTitle("CS2");
//
//			List l = appServiceCatissue.search(ClinicalStudyEvent.class.getName(), cstudy);
//			System.out.println("l.size(): "+l.size());
//			for(int i=0;i<l.size();i++)
//			{
//				ClinicalStudyEvent returnedEvent= (ClinicalStudyEvent)l.get(i);
//				ClinicalStudyEvent newEvent = new ClinicalStudyEvent();
//				HashSet studyFormContextCollection = new HashSet();
//				studyFormContextCollection.add(sf);
//				newEvent.setStudyFormContextCollection(studyFormContextCollection);
//				newEvent.setId(returnedEvent.getId());
//				List list = appServiceCatissue.search(StudyFormContext.class.getName(), newEvent);
//				System.out.println("list.size(): "+list.size());
//				for(int j=0;j<list.size();j++)
//				{
//					StudyFormContext f = (StudyFormContext)list.get(j);
//					System.out.println(f.getStudyFormLabel());
//					studyFormContext = f;
//				}
//			}

			System.out.println("Finished");
			cs.terminateSession();
		}
		catch (Exception ex)
		{
			System.out.println(ex.getMessage());
			ex.printStackTrace();
			return;
		}

	}

	/**
	 * Method creates clinical study object
	 * @throws Exception
	 */
	private static void createClinicalStudy() throws Exception
	{
		ClinicalStudy cs = new ClinicalStudy();
		cs.setActivityStatus("Active");
		cs.setTitle(CLINICAL_STUDY_TITLE);
		cs.setShortTitle(CLINICAL_STUDY_TITLE);
		cs.setStartDate(new Date());
		User user = new User();
		user.setId(1L);
		cs.setPrincipalInvestigator(user);
		cs.setIrbIdentifier(IRB_IDENTIFIER);
		Collection<ClinicalStudyEvent> clinicalStudyEventCollection = new HashSet<ClinicalStudyEvent>();

		ClinicalStudyEvent csEvent = new ClinicalStudyEvent();
		csEvent.setActivityStatus("Active");
		csEvent.setClinicalStudy(cs);
		csEvent.setCollectionPointLabel(COLLECTION_POINT_LABEL);
		csEvent.setIsInfiniteEntry(true);
		csEvent.setStudyCalendarEventPoint(1);
		csEvent.setNoOfEntries(-1);

		Collection<StudyFormContext> studyFormContextCollection = new HashSet<StudyFormContext>();

	/*	String containerCaption = "BasePathologyAnnotation";
		System.out.println(containerCaption);
		StudyFormContext studyFormContext = new StudyFormContext();
		studyFormContext.setCanHaveMultipleRecords(true);
		studyFormContext.setContainerId(entityManager.getContainerIdByCaption(containerCaption));
		studyFormContext.setActivityStatus("Active");
		studyFormContext.setClinicalStudyEvent(csEvent);
		studyFormContext.setStudyFormLabel(containerCaption);
		studyFormContextCollection.add(studyFormContext);*/

		csEvent.setStudyFormContextCollection(studyFormContextCollection);
		clinicalStudyEventCollection.add(csEvent);
		cs.setClinicalStudyEventCollection(clinicalStudyEventCollection);

		appServiceCatissue.createObject(cs);

		System.out.println("CREATE CLINICAL STUDY SUCCESSFULLY");
	}

	/**
	 *
	 * @return
	 */
	private static EventEntry createEventEntry() throws Exception
	{
		ClinicalStudyRegistration clinicalStudyRegistration = new ClinicalStudyRegistration();
		clinicalStudyRegistration.setId(getClinicalStudyRegistrationID());
		ClinicalStudyEvent clinicalStudyEvent = new ClinicalStudyEvent();
		clinicalStudyEvent.setId(CLINICAL_STUDY_EVENT_ID);
		EventEntry eventEntry = new EventEntry();
		eventEntry.setActivityStatus("Active");
		eventEntry.setClinicalStudyRegistration(clinicalStudyRegistration);
		eventEntry.setClinicalStudyEvent(clinicalStudyEvent);
		Date encounteredDate = new Date(System.currentTimeMillis());
		eventEntry.setEncounterDate(encounteredDate);

		EventEntry returnedEventEntry = (EventEntry)appServiceCatissue.createObject(eventEntry);
		EventEntry newEventEntry = new EventEntry();
		newEventEntry.setId(returnedEventEntry.getId());
		//newEventEntry.setId(21L);
		return newEventEntry;

	}
	/**
	 * @return
	 */
	private static void initCaTissueService()
	{

		appServiceCatissue = ApplicationServiceProvider
				.getRemoteInstance(APPLICATION_URL);
		System.out.println("appServiceCatissue = " + appServiceCatissue);
	}

	private static void initDEService()
	{
		appServiceDEEntity = ApplicationServiceProvider
				.getRemoteInstance("http://localhost:8080/dedemo/http/remoteService");
	}
/**
 * Get ClinicalStudy Registration ID Given Participant ID and Clinical Study Title
 * @return
 * @throws Exception
 */
	private static Long getClinicalStudyRegistrationID() throws Exception
	{
		Participant participant = new Participant();
		participant.setId(PARTICIPANT_IDENTIFIER);

		ClinicalStudy cs = new ClinicalStudy();
		cs.setTitle(CLINICAL_STUDY_TITLE);

		ClinicalStudyRegistration clinicalStudyRegistration = new ClinicalStudyRegistration();
		clinicalStudyRegistration.setParticipant(participant);
		clinicalStudyRegistration.setClinicalStudy(cs);
		List l = appServiceCatissue.search(ClinicalStudyRegistration.class.getName(), clinicalStudyRegistration);
		ClinicalStudyRegistration returnedCSR = (ClinicalStudyRegistration)l.get(0);
		return returnedCSR.getId();
	}

	private static StudyFormContext getStudyFormContext(Long containerID) throws Exception
	{
		ClinicalStudyEvent event = new ClinicalStudyEvent();
		event.setId(CLINICAL_STUDY_EVENT_ID);
		HashSet studyFormContextCollection = new HashSet();
		StudyFormContext sf = new StudyFormContext();
		sf.setContainerId(containerID);
		studyFormContextCollection.add(sf);
		event.setStudyFormContextCollection(studyFormContextCollection);
		List l = appServiceCatissue.search(StudyFormContext.class, event);
		StudyFormContext returnedForm = (StudyFormContext)l.get(0);
		System.out.println("returnedForm "+returnedForm.getStudyFormLabel());
		StudyFormContext newStudyFormContext = new StudyFormContext();
		newStudyFormContext.setId(returnedForm.getId());
		return newStudyFormContext;

	}
}


text:
[@kaoscript/ast](https://github.com/kaoscript/ast)
=================================================================

[![kaoscript](https://img.shields.io/badge/language-kaoscript-orange.svg)](https://github.com/kaoscript/kaoscript)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
[![NPM Version](https://img.shields.io/npm/v/@kaoscript/ast.svg?colorB=green)](https://www.npmjs.com/package/@kaoscript/ast)
[![Dependency Status](https://badges.depfu.com/badges/b4aacce128a011ba720469d301485843/overview.svg)](https://depfu.com/github/kaoscript/ast)

Enumerate types used in the syntax trees of kaoscript language.

Documentation available at [kaoscript](https://github.com/kaoscript/kaoscript).

License
-------

[MIT](http://www.opensource.org/licenses/mit-license.php) © Baptiste Augrain


text:
#include "ucp_int.h"

#define UCP_RMA_CHECK_PARAMS(_buffer, _length) \
    if ((_length) == 0) { \
        return UCS_OK; \
    } \
    if (ENABLE_PARAMS_CHECK && ((_buffer) == NULL)) { \
        return UCS_ERR_INVALID_PARAM; \
    }

#define UCP_RMA_RKEY_LOOKUP(_ep, _rkey) \
    ({ \
        if (ENABLE_PARAMS_CHECK && \
            !((_rkey)->pd_map & UCS_BIT((_ep)->uct.dst_pd_index))) \
        { \
            ucs_error("Remote key does not support current transport " \
                       "(remote pd index: %d rkey map: 0x%"PRIx64")", \
                       (_ep)->uct.dst_pd_index, (_rkey)->pd_map); \
            return UCS_ERR_UNREACHABLE; \
        } \
        \
        ucp_lookup_uct_rkey(_ep, _rkey); \
    })

/**
 * Unregister memory from all protection domains.
 * Save in *alloc_pd_memh_p the memory handle of the allocating PD, if such exists.
 */
static ucs_status_t ucp_memh_dereg_pds(ucp_context_h context, ucp_mem_h memh,
                                       uct_mem_h* alloc_pd_memh_p)
{
    unsigned pd_index, uct_index;
    ucs_status_t status;

    uct_index        = 0;
    *alloc_pd_memh_p = UCT_INVALID_MEM_HANDLE;

    for (pd_index = 0; pd_index < context->num_pds; ++pd_index) {
        if (!(memh->pd_map & UCS_BIT(pd_index))) {
            /* PD not present in the array */
            continue;
        }

        if (memh->alloc_pd == context->pds[pd_index]) {
            /* If we used a pd to register the memory, remember the memh - for
             * releasing the memory later. We cannot release the memory at this
             * point because we have to unregister it from other PDs first.
             */
            ucs_assert(memh->alloc_method == UCT_ALLOC_METHOD_PD);
            *alloc_pd_memh_p = memh->uct[uct_index];
        } else {
            status = uct_pd_mem_dereg(context->pds[pd_index],
                                      memh->uct[uct_index]);
            if (status != UCS_OK) {
                ucs_error("Failed to dereg address %p with pd %s", memh->address,
                         context->pd_rscs[pd_index].pd_name);
                return status;
            }
        }

        ++uct_index;
    }

    return UCS_OK;
}

/**
 * Register the memory on all PDs, except maybe for alloc_pd.
 * In case alloc_pd != NULL, alloc_pd_memh will hold the memory key obtained from
 * allocation. It will be put in the array of keys in the proper index.
 */
static ucs_status_t ucp_memh_reg_pds(ucp_context_h context, ucp_mem_h memh,
                                     uct_mem_h alloc_pd_memh)
{
    uct_mem_h dummy_pd_memh;
    unsigned uct_memh_count;
    ucs_status_t status;
    unsigned pd_index;

    memh->pd_map   = 0;
    uct_memh_count = 0;

    /* Register on all transports (except the one we used to allocate) */
    for (pd_index = 0; pd_index < context->num_pds; ++pd_index) {
        if (context->pds[pd_index] == memh->alloc_pd) {
            /* Add the memory handle we got from allocation */
            ucs_assert(memh->alloc_method == UCT_ALLOC_METHOD_PD);
            memh->pd_map |= UCS_BIT(pd_index);
            memh->uct[uct_memh_count++] = alloc_pd_memh;
        } else if (context->pd_attrs[pd_index].cap.flags & UCT_PD_FLAG_REG) {
            /* If the PD supports registration, register on it as well */
            status = uct_pd_mem_reg(context->pds[pd_index], memh->address,
                                    memh->length, &memh->uct[uct_memh_count]);
            if (status != UCS_OK) {
                ucp_memh_dereg_pds(context, memh, &dummy_pd_memh);
                return status;
            }

            memh->pd_map |= UCS_BIT(pd_index);
            ++uct_memh_count;
        }
    }
    return UCS_OK;
}

/**
 * @return Whether PD number 'pd_index' is selected by the configuration as part
 *         of allocation method number 'config_method_index'.
 */
static int ucp_is_pd_selected_by_config(ucp_context_h context,
                                        unsigned config_method_index,
                                        unsigned pd_index)
{
    const char *config_pdc_name = context->config.alloc_methods[config_method_index].pdc_name;
    const char *pdc_name        = context->pd_attrs[pd_index].component_name;

    return !strncmp(config_pdc_name, "*",      UCT_PD_COMPONENT_NAME_MAX) ||
           !strncmp(config_pdc_name, pdc_name, UCT_PD_COMPONENT_NAME_MAX);
}

static ucs_status_t ucp_mem_alloc(ucp_context_h context, size_t length,
                                  const char *name, ucp_mem_h memh)
{
    uct_allocated_memory_t mem;
    uct_alloc_method_t method;
    unsigned method_index, pd_index, num_pds;
    ucs_status_t status;
    uct_pd_h *pds;

    pds = ucs_calloc(context->num_pds, sizeof(*pds), "temp pds");
    if (pds == NULL) {
        return UCS_ERR_NO_MEMORY;
    }

    for (method_index = 0; method_index < context->config.num_alloc_methods;
                    ++method_index)
    {
        method = context->config.alloc_methods[method_index].method;

        /* If we are trying PD method, gather all PDs which match the component
         * name specified in the configuration.
         */
        num_pds = 0;
        if (method == UCT_ALLOC_METHOD_PD) {
            for (pd_index = 0; pd_index < context->num_pds; ++pd_index) {
                if (ucp_is_pd_selected_by_config(context, method_index, pd_index)) {
                    pds[num_pds++] = context->pds[pd_index];
                }
            }
        }

        status = uct_mem_alloc(length, &method, 1, pds, num_pds, name, &mem);
        if (status == UCS_OK) {
            goto allocated;
        }
    }

    status = UCS_ERR_NO_MEMORY;
    goto out;

allocated:
    ucs_debug("allocated memory at %p with method %s, now registering it",
             mem.address, uct_alloc_method_names[mem.method]);
    memh->address      = mem.address;
    memh->length       = mem.length;
    memh->alloc_method = mem.method;
    memh->alloc_pd     = mem.pd;
    status = ucp_memh_reg_pds(context, memh, mem.memh);
    if (status != UCS_OK) {
        uct_mem_free(&mem);
    }
out:
    ucs_free(pds);
    return status;
}

ucs_status_t ucp_mem_map(ucp_context_h context, void **address_p, size_t length,
                         unsigned flags, ucp_mem_h *memh_p)
{
    ucs_status_t status;
    ucp_mem_h memh;

    if (length == 0) {
        return UCS_ERR_INVALID_PARAM;
    }

    /* Allocate the memory handle */
    ucs_assert(context->num_pds > 0);
    memh = ucs_malloc(sizeof(*memh) + context->num_pds * sizeof(memh->uct[0]),
                      "ucp_memh");
    if (memh == NULL) {
        status = UCS_ERR_NO_MEMORY;
        goto err;
    }

    if (*address_p == NULL) {
        status = ucp_mem_alloc(context, length, "user allocation", memh);
        if (status != UCS_OK) {
            goto err_free_memh;
        }

        *address_p = memh->address;
    } else {
        ucs_debug("registering user memory at %p length %zu", *address_p, length);
        memh->address      = *address_p;
        memh->length       = length;
        memh->alloc_method = UCT_ALLOC_METHOD_LAST;
        memh->alloc_pd     = NULL;
        status = ucp_memh_reg_pds(context, memh, UCT_INVALID_MEM_HANDLE);
        if (status != UCS_OK) {
            goto err_free_memh;
        }
    }

    ucs_debug("%s buffer %p length %zu memh %p pd_map 0x%"PRIx64,
              (memh->alloc_method == UCT_ALLOC_METHOD_LAST) ? "mapped" : "allocated",
              memh->address, memh->length, memh, memh->pd_map);
    *memh_p = memh;
    return UCS_OK;

err_free_memh:
    ucs_free(memh);
err:
    return status;
}

ucs_status_t ucp_mem_unmap(ucp_context_h context, ucp_mem_h memh)
{
    uct_allocated_memory_t mem;
    uct_mem_h alloc_pd_memh;
    ucs_status_t status;

    ucs_debug("unmapping buffer %p memh %p", memh->address, memh);

    /* Unregister from all protection domains */
    status = ucp_memh_dereg_pds(context, memh, &alloc_pd_memh);
    if (status != UCS_OK) {
        return status;
    }

    /* If the memory was also allocated, release it */
    if (memh->alloc_method != UCT_ALLOC_METHOD_LAST) {
        mem.address = memh->address;
        mem.length  = memh->length;
        mem.method  = memh->alloc_method;
        mem.pd      = memh->alloc_pd;  /* May be NULL if method is not PD */
        mem.memh    = alloc_pd_memh;   /* May be INVALID if method is not PD */

        status = uct_mem_free(&mem);
        if (status != UCS_OK) {
            return status;
        }
    }

    ucs_free(memh);
    return UCS_OK;
}

ucs_status_t ucp_rkey_pack(ucp_context_h context, ucp_mem_h memh,
                           void **rkey_buffer_p, size_t *size_p)
{
    unsigned pd_index, uct_memh_index;
    void *rkey_buffer, *p;
    size_t size, pd_size;

    ucs_trace("packing rkeys for buffer %p memh %p pd_map 0x%"PRIx64,
              memh->address, memh, memh->pd_map);

    size = sizeof(uint64_t);
    for (pd_index = 0; pd_index < context->num_pds; ++pd_index) {
        size += sizeof(uint8_t);
        pd_size = context->pd_attrs[pd_index].rkey_packed_size;
        ucs_assert_always(pd_size < UINT8_MAX);
        size += pd_size;
    }

    rkey_buffer = ucs_malloc(size, "ucp_rkey_buffer");
    if (rkey_buffer == NULL) {
        return UCS_ERR_NO_MEMORY;
    }

    p = rkey_buffer;

    /* Write the PD map */
    *(uint64_t*)p = memh->pd_map;
    p += sizeof(uint64_t);

    /* Write both size and rkey_buffer for each UCT rkey */
    uct_memh_index = 0;
    for (pd_index = 0; pd_index < context->num_pds; ++pd_index) {
        if (!(memh->pd_map & UCS_BIT(pd_index))) {
            continue;
        }

        pd_size = context->pd_attrs[pd_index].rkey_packed_size;
        *((uint8_t*)p++) = pd_size;
        uct_pd_mkey_pack(context->pds[pd_index], memh->uct[uct_memh_index], p);
        ++uct_memh_index;
        p += pd_size;
    }

    *rkey_buffer_p = rkey_buffer;
    *size_p        = size;
    return UCS_OK;
}

void ucp_rkey_buffer_release(void *rkey_buffer)
{
    ucs_free(rkey_buffer);
}

ucs_status_t ucp_ep_rkey_unpack(ucp_ep_h ep, void *rkey_buffer, ucp_rkey_h *rkey_p)
{
    unsigned remote_pd_index, remote_pd_gap;
    unsigned rkey_index;
    unsigned pd_count;
    ucs_status_t status;
    ucp_rkey_h rkey;
    uint8_t pd_size;
    uint64_t pd_map;
    void *p;

    /* Count the number of remote PDs in the rkey buffer */
    p = rkey_buffer;

    /* Read remote PD map */
    pd_map   = *(uint64_t*)p;
    pd_count = ucs_count_one_bits(pd_map);
    p       += sizeof(uint64_t);

    /* Allocate rkey handle which holds UCT rkeys for all remote PDs.
     * We keep all of them to handle a future transport switch.
     */
    rkey = ucs_malloc(sizeof(*rkey) + (sizeof(rkey->uct[0]) * pd_count), "ucp_rkey");
    if (rkey == NULL) {
        status = UCS_ERR_NO_MEMORY;
        goto err;
    }

    rkey->pd_map    = 0;
    remote_pd_index = 0; /* Index of remote PD */
    rkey_index      = 0; /* Index of the rkey in the array */

    /* Unpack rkey of each UCT PD */
    ucs_trace("unpacking rkey with pd_map 0x%"PRIx64, pd_map);
    while (pd_map > 0) {
        pd_size = *((uint8_t*)p++);

        /* Use bit operations to iterate through the indices of the remote PDs
         * as provided in the pd_map. pd_map always holds a bitmap of PD indices
         * that remain to be used. Every time we find the "gap" until the next
         * valid PD index using ffs operation. If some rkeys cannot be unpacked,
         * we remove them from the local map.
         */
        remote_pd_gap    = ucs_ffs64(pd_map); /* Find the offset for next PD index */
        remote_pd_index += remote_pd_gap;      /* Calculate next index of remote PD*/
        pd_map >>= remote_pd_gap;                   /* Remove the gap from the map */
        ucs_assert(pd_map & 1);

        /* Unpack only reachable rkeys */
        if (ep->uct.reachable_pds & UCS_BIT(remote_pd_index)) {

            ucs_assert(rkey_index < pd_count);
            status = uct_rkey_unpack(p, &rkey->uct[rkey_index]);
            if (status != UCS_OK) {
                ucs_error("Failed to unpack remote key from remote pd[%d]: %s",
                          remote_pd_index, ucs_status_string(status));
                goto err_destroy;
            }

            ucs_trace("rkey[%d] for remote pd %d is 0x%lx", rkey_index,
                      remote_pd_index, rkey->uct[rkey_index].rkey);
            rkey->pd_map |= UCS_BIT(remote_pd_index);
            ++rkey_index;
        }

        ++remote_pd_index;
        pd_map >>= 1;
        p += pd_size;
    }

    *rkey_p = rkey;
    return UCS_OK;

err_destroy:
    ucp_rkey_destroy(rkey);
err:
    return status;
}

void ucp_rkey_destroy(ucp_rkey_h rkey)
{
    unsigned num_rkeys = ucs_count_one_bits(rkey->pd_map);
    unsigned i;

    for (i = 0; i < num_rkeys; ++i) {
        uct_rkey_release(&rkey->uct[i]);
    }
    ucs_free(rkey);
}

static inline uct_rkey_t ucp_lookup_uct_rkey(ucp_ep_h ep, ucp_rkey_h rkey)
{
    unsigned rkey_index;

    /*
     * Calculate the rkey index inside the compact array. This is actually the
     * number of PDs in the map with index less-than ours. So mask pd_map to get
     * only the less-than indices, and then count them using popcount operation.
     * TODO save the mask in ep->uct, to avoid the shift operation.
     */
    rkey_index = ucs_count_one_bits(rkey->pd_map & UCS_MASK(ep->uct.dst_pd_index));
    return rkey->uct[rkey_index].rkey;
}

ucs_status_t ucp_rma_put(ucp_ep_h ep, const void *buffer, size_t length,
                         uint64_t remote_addr, ucp_rkey_h rkey)
{
    ucs_status_t status;
    uct_rkey_t uct_rkey;
    size_t frag_length;

    if (length == 0) {
        return UCS_OK;
    }
    if (ENABLE_PARAMS_CHECK && (buffer == NULL)) {
        return UCS_ERR_INVALID_PARAM;
    }

    uct_rkey = UCP_RMA_RKEY_LOOKUP(ep, rkey);

    /* Loop until all message has been sent.
     * We re-check the configuration on every iteration, because it can be
     * changed by transport switch.
     */
    for (;;) {
        if (length <= ep->config.max_short_put) {
            status = uct_ep_put_short(ep->uct.ep, buffer, length, remote_addr,
                                      uct_rkey);
            if (ucs_likely(status != UCS_ERR_NO_RESOURCE)) {
                break;
            }
        } else {
            if (length <= ep->worker->context->config.bcopy_thresh) {
                frag_length = ucs_min(length, ep->config.max_short_put);
                status = uct_ep_put_short(ep->uct.ep, buffer, frag_length, remote_addr,
                                          uct_rkey);
            } else {
                frag_length = ucs_min(length, ep->config.max_bcopy_put);
                status = uct_ep_put_bcopy(ep->uct.ep, (uct_pack_callback_t)memcpy,
                                          (void*)buffer, frag_length, remote_addr,
                                          uct_rkey);
            }
            if (ucs_likely(status == UCS_OK)) {
                length      -= frag_length;
                if (length == 0) {
                    break;
                }

                buffer      += frag_length;
                remote_addr += frag_length;
            } else if (status != UCS_ERR_NO_RESOURCE) {
                break;
            }
        }
        ucp_worker_progress(ep->worker);
    }

    return status;
}

ucs_status_t ucp_rma_get(ucp_ep_h ep, void *buffer, size_t length,
                         uint64_t remote_addr, ucp_rkey_h rkey)
{
    uct_completion_t comp;
    ucs_status_t status;
    uct_rkey_t uct_rkey;
    size_t frag_length;

    if (length == 0) {
        return UCS_OK;
    }

    uct_rkey = UCP_RMA_RKEY_LOOKUP(ep, rkey);

    comp.count = 1;

    for (;;) {

        /* Push out all fragments, and request completion only for the last
         * fragment.
         */
        frag_length = ucs_min(ep->config.max_bcopy_get, length);
        status = uct_ep_get_bcopy(ep->uct.ep, (uct_unpack_callback_t)memcpy,
                                  (void*)buffer, frag_length, remote_addr,
                                  uct_rkey, &comp);
        if (ucs_likely(status == UCS_OK)) {
            goto posted;
        } else if (status == UCS_INPROGRESS) {
            ++comp.count;
            goto posted;
        } else if (status == UCS_ERR_NO_RESOURCE) {
            goto retry;
        } else {
            return status;
        }

posted:
        length      -= frag_length;
        if (length == 0) {
            break;
        }

        buffer      += frag_length;
        remote_addr += frag_length;
retry:
        ucp_worker_progress(ep->worker);
    }

    /* coverity[loop_condition] */
    while (comp.count > 1) {
        ucp_worker_progress(ep->worker);
    };
    return UCS_OK;
}

ucs_status_t ucp_rma_fence(ucp_worker_h worker)
{
    return UCS_ERR_UNSUPPORTED;
}

ucs_status_t ucp_rma_flush(ucp_worker_h worker)
{
    unsigned rsc_index;

    /* TODO flush in parallel */
    for (rsc_index = 0; rsc_index < worker->context->num_tls; ++rsc_index) {
        if (worker->ifaces[rsc_index] == NULL) {
            continue;
        }

        while (uct_iface_flush(worker->ifaces[rsc_index]) != UCS_OK) {
            ucp_worker_progress(worker);
        }
    }

    return UCS_OK;
}


text:
package org.infinispan.demo.online;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;

import io.fabric8.openshift.client.DefaultOpenShiftClient;
import io.fabric8.openshift.client.OpenShiftClient;
import io.fabric8.openshift.client.OpenShiftConfig;
import io.fabric8.openshift.client.OpenShiftConfigBuilder;

/**
 * DEPRECATED. Use the OpenShift quickstarts for Data Grid 7.3 instead.
 */

/**
 * This is a helper class for parsing a CRT file and creating a java truststore
 */
public class TrustStore {

   public static void createFromCmdLine(String path, char[] password) throws GeneralSecurityException, IOException {
      String oauthToken = getStringFromCommand("oc whoami -t");
      String currentContext = getStringFromCommand("oc config current-context");
      String[] contextArray = currentContext.split("/");
      String namespace = contextArray[0];
      String url = "https://" + contextArray[1].split(":")[0];

      String certificate = getCertificateSecret(url, namespace, oauthToken);
      create(certificate, path, password);
   }

   private static String getStringFromCommand(String cmd) throws IOException {
      Process process = Runtime.getRuntime().exec(cmd);
      try (BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
         return input.readLine();
      }
   }

   private static String getCertificateSecret(String url, String namespace, String oauthTok) {
      OpenShiftConfig config = new OpenShiftConfigBuilder()
            .withOpenShiftUrl(url)
            .withNamespace(namespace)
            .withOauthToken(oauthTok)
            .build();

      OpenShiftClient client = new DefaultOpenShiftClient(config);
      return client.secrets().withName("service-certs").get().getData().get("tls.crt");
   }

   /**
    * @param crtPath  the path to the crt file to be passed
    * @param tsPath   the path of the truststore to be created
    * @param password the password for accessing the created truststore
    */
   public static void createFromCrtFile(String crtPath, String tsPath, char[] password)
         throws GeneralSecurityException, IOException {
      create(parseCrtFile(crtPath), tsPath, password);
   }

   /**
    * @param cert     a certificate to be stored in the truststore
    * @param path     the path to the truststore
    * @param password the password for accessing the generated truststore
    */
   public static void create(String cert, String path, char[] password) throws GeneralSecurityException, IOException {
      create(Collections.singletonList(cert), path, password);
   }

   /**
    * @param certs    a list of certificates to be store in the truststore
    * @param path     the path to the truststore
    * @param password the password for accessing the generated truststore
    */
   public static void create(List<String> certs, String path, char[] password) throws GeneralSecurityException, IOException {
      try (FileOutputStream output = new FileOutputStream(path)) {
         KeyStore trustStore = KeyStore.getInstance("PKCS12");
         CertificateFactory cf = CertificateFactory.getInstance("X.509");
         trustStore.load(null, null);

         for (int i = 0; i < certs.size(); i++) {
            String alias = i < 10 ? "service-crt-0" : "service-crt-";
            String cert = certs.get(i);
            try (InputStream input = Base64.getDecoder().wrap(new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8)))) {
               Certificate certificate = cf.generateCertificate(input);
               trustStore.setCertificateEntry(alias + i, certificate);
            }
         }
         trustStore.store(output, password);
      }
   }

   /**
    * Parse the parsed crt file to return an array of String certificates
    *
    * @param path to the crt file to be parsed
    * @return a list of certificates in String format
    */
   private static List<String> parseCrtFile(String path) throws IOException {
      List<String> certs = new ArrayList<>();
      StringBuilder sb = new StringBuilder();
      for (String line : Files.readAllLines(Paths.get(path))) {
         if (line.isEmpty() || line.contains("BEGIN CERTIFICATE"))
            continue;

         if (line.contains("END CERTIFICATE")) {
            certs.add(sb.toString());
            sb.setLength(0);
         } else {
            sb.append(line);
         }
      }
      return certs;
   }
}


text:
$("#contactForm").validator().on("submit", function (event) {
	if (event.isDefaultPrevented()) {
		// handle the invalid form...
		formError();
		submitMSG(false, "Form working has been disabled here. It will work on a PHP enabled server!");
	} else {
		// everything looks good!
        event.preventDefault();
        submitForm();
    }
});

function submitForm(){
	// Initiate Variables With Form Content
	var name = $("#name").val();
	var email = $("#email").val();
	var events = $("#events").val();
	var number_of_people = $("#number_of_people").val();

	$.ajax({
		type: "POST",
		//Set the Path to Your PHP File here
		url: "/bless/form-process.php",
		data: "name=" + name + "&email=" + email + "&events=" + events + "&number_of_people=" + number_of_people,
        success : function(text){
			if (text == "success"){
				formSuccess();
				$("#contact_form_fields").slideUp(); //hide form after success
            } else {
                formError();
                submitMSG(false,text);
            }
		}
	});
}

function formSuccess(){
	$("#contactForm")[0].reset();
	submitMSG(true, "Thank you!")
}

function formError(){
	$(this).removeClass();
}

function submitMSG(valid, msg){
	if(valid){
		var msgClasses = "h3 text-center text-success";
    } else {
        var msgClasses = "h3 text-center text-danger";
    }
	$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}


text:
//package pratice.java.database.transaction.utils;
//
///**
// * Created by patrick on 12/17/14.
// */
//
//import com.sleepycat.je.*;
//import org.apache.log4j.Logger;
//
//import java.io.File;
//import java.io.UnsupportedEncodingException;
//import java.util.ArrayList;
//
//public class BerkeleyDBUtil {
//    static Logger log = Logger.getLogger(BerkeleyDBUtil.class.getName());
//
//    // 数据库环境
//    private Environment env = null;
//
//    // 数据库
//    private static Database frontierDatabase = null;
//
//    // 数据库名
//    private static String dbName = "frontier_database";
//
//    public BerkeleyDBUtil(String homeDirectory) {
//        try {
//            // 1、创建EnvironmentConfig
//            EnvironmentConfig envConfig = new EnvironmentConfig();
//            envConfig.setTransactional(true);
//            envConfig.setAllowCreate(true);
//
//            // 2、使用EnvironmentConfig配置Environment
//            env = new Environment(new File(homeDirectory), envConfig);
//
//            // 3、创建DatabaseConfig
//            DatabaseConfig dbConfig = new DatabaseConfig();
//            dbConfig.setTransactional(true);
//            dbConfig.setAllowCreate(true);
//
//            // 4、使用Environment与DatabaseConfig打开Database
//            frontierDatabase = env.openDatabase(null, dbName, dbConfig);
//        }catch(DatabaseException ex){
//            log.error(ex.getMessage());
//        }
//
//    }
//
//    /*
//     * 向数据库中写入记录,并判断是否可以有重复数据。 传入key和value
//     * 若可以有重复数据,则直接使用put()即可,若不能有重复数据,则使用putNoOverwrite()。
//     */
//    public boolean writeToDatabase(String key, String value, boolean isOverwrite) {
//        try {
//            // 设置key/value,注意DatabaseEntry内使用的是bytes数组
//            DatabaseEntry theKey = new DatabaseEntry(key.getBytes("UTF-8"));
//            DatabaseEntry theData = new DatabaseEntry(value.getBytes("UTF-8"));
//            OperationStatus status = null;
//            Transaction txn = null;
//            try {
//                // 1、Transaction配置
//                TransactionConfig txConfig = new TransactionConfig();
//                txConfig.setSerializableIsolation(true);
//                txn = env.beginTransaction(null, txConfig);
//                // 2、写入数据
//                if (isOverwrite) {
//                    status = frontierDatabase.put(txn, theKey, theData);
//                } else {
//                    status = frontierDatabase.putNoOverwrite(txn, theKey,
//                            theData);
//                }
//                txn.commit();
//                if (status == OperationStatus.SUCCESS) {
//                    System.out.println("向数据库" + dbName + "中写入:" + key + ","
//                            + value);
//                    return true;
//                } else if (status == OperationStatus.KEYEXIST) {
//                    System.out.println("向数据库" + dbName + "中写入:" + key + ","
//                            + value + "失败,该值已经存在");
//                    return false;
//                } else {
//                    System.out.println("向数据库" + dbName + "中写入:" + key + ","
//                            + value + "失败");
//                    return false;
//                }
//            } catch (DeadlockException lockConflict) {
//                txn.abort();
//                System.out.println("向数据库" + dbName + "中写入:" + key + "," + value
//                        + "出现lock异常");
//                return false;
//            }
//        } catch (Exception e) {
//            // 错误处理
//            System.out.println("向数据库" + dbName + "中写入:" + key + "," + value
//                    + "出现错误");
//
//            return false;
//        }
//    }
//
//    /*
//     * 从数据库中读出数据 传入key 返回value
//     */
//    public String readFromDatabase(String key) {
//        try {
//            DatabaseEntry theKey = new DatabaseEntry(key.getBytes("UTF-8"));
//            DatabaseEntry theData = new DatabaseEntry();
//            Transaction txn = null;
//            try {
//                // 1、配置 Transaction相关信息
//                TransactionConfig txConfig = new TransactionConfig();
//                txConfig.setSerializableIsolation(true);
//                txn = env.beginTransaction(null, txConfig);
//                // 2、读取数据
//                OperationStatus status = frontierDatabase.get(txn, theKey,
//                        theData, LockMode.DEFAULT);
//                txn.commit();
//                if (status == OperationStatus.SUCCESS) {
//                    // 3、将字节转换成String
//                    byte[] retData = theData.getData();
//                    String value = new String(retData, "UTF-8");
//                    System.out.println("从数据库" + dbName + "中读取:" + key + ","
//                            + value);
//                    return value;
//                } else {
//                    System.out
//                            .println("No record found for key '" + key + "'.");
//                    return "";
//                }
//            } catch (DeadlockException lockConflict) {
//                try{
//                    txn.abort();
//                    System.out.println("从数据库" + dbName + "中读取:" + key + "出现lock异常");
//                }catch(DatabaseException ex){
//                    log.error(ex.getMessage());
//                }
//
//                return "";
//            }catch (DatabaseException ex){
//                log.error(ex.getMessage());
//            }
//
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//            return "";
//
//    }
//
//    /*
//     * 遍历数据库中的所有记录,返回list
//     */
//    public ArrayList<String> getEveryItem() {
//        // TODO Auto-generated method stub
//        System.out.println("===========遍历数据库" + dbName + "中的所有数据==========");
//        Cursor myCursor = null;
//        ArrayList<String> resultList = new ArrayList<String>();
//        Transaction txn = null;
//        try {
//            txn = this.env.beginTransaction(null, null);
//            CursorConfig cc = new CursorConfig();
//            cc.setReadCommitted(true);
//            if (myCursor == null)
//                myCursor = frontierDatabase.openCursor(txn, cc);
//            DatabaseEntry foundKey = new DatabaseEntry();
//            DatabaseEntry foundData = new DatabaseEntry();
//            // 使用cursor.getPrev方法来遍历游标获取数据
//            if (myCursor.getFirst(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
//                String theKey = new String(foundKey.getData(), "UTF-8");
//                String theData = new String(foundData.getData(), "UTF-8");
//                resultList.add(theKey);
//                System.out.println("Key | Data : " + theKey + " | " + theData
//                        + "");
//                while (myCursor.getNext(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
//                    theKey = new String(foundKey.getData(), "UTF-8");
//                    theData = new String(foundData.getData(), "UTF-8");
//                    resultList.add(theKey);
//                    System.out.println("Key | Data : " + theKey + " | "
//                            + theData + "");
//                }
//            }
//            myCursor.close();
//            txn.commit();
//            return resultList;
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            return null;
//        } catch (Exception e) {
//            System.out.println("getEveryItem处理出现异常");
//            try{
//            txn.abort();
//            if (myCursor != null) {
//                myCursor.close();
//            }}catch(DatabaseException exception){
//                log.error(exception.getMessage());
//            }
//            return null;
//        }
//    }
//
//    /*
//     * 根据key值删除数据库中的一条记录
//     */
//    public boolean deleteFromDatabase(String key) {
//        boolean success = false;
//        long sleepMillis = 0;
//        for (int i = 0; i < 3; i++) {
//            if (sleepMillis != 0) {
//                try {
//                    Thread.sleep(sleepMillis);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                sleepMillis = 0;
//            }
//            Transaction txn = null;
//            try {
//                // 1、使用cursor.getPrev方法来遍历游标获取数据
//                TransactionConfig txConfig = new TransactionConfig();
//                txConfig.setSerializableIsolation(true);
//                txn = env.beginTransaction(null, txConfig);
//                DatabaseEntry theKey;
//                theKey = new DatabaseEntry(key.getBytes("UTF-8"));
//
//                //2、删除数据 并提交
//                OperationStatus res = frontierDatabase.delete(txn, theKey);
//                txn.commit();
//                if (res == OperationStatus.SUCCESS) {
//                    System.out.println("从数据库" + dbName + "中删除:" + key);
//                    success = true;
//                    return success;
//                } else if (res == OperationStatus.KEYEMPTY) {
//                    System.out.println("没有从数据库" + dbName + "中找到:" + key + "。无法删除");
//                } else {
//                    System.out.println("删除操作失败,由于" + res.toString());
//                }
//                return false;
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//                return false;
//            } catch (DeadlockException lockConflict) {
//                System.out.println("删除操作失败,出现lockConflict异常");
//                sleepMillis = 1000;
//
//                continue;
//            } catch(DatabaseException databaseEx){
//                log.error(databaseEx.getMessage());
//            }
//            finally {
//                if (!success) {
//                    if (txn != null) {
//                        try{
//                            txn.abort();
//                        }catch(DatabaseException ex){
//                            log.error(ex.getMessage());
//                        }
//                    }
//                }
//            }
//        }
//        return false;
//    }
//
//    public void closeDB() {
//        try{
//        if (frontierDatabase != null) {
//            frontierDatabase.close();
//        }
//        if (env != null) {
//            env.close();
//        }}catch(DatabaseException ex){
//            log.error(ex.getMessage());
//        }
//    }
//
//}
//


text:
@interface LGAlertViewCell ()

@property (readwrite) UIView *separatorView;

@end

@implementation LGAlertViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;

        [self clearBackgrounds];

        self.separatorView = [UIView new];
        [self addSubview:self.separatorView];

        self.enabled = YES;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat frameWidth = CGRectGetWidth(self.bounds);
    CGFloat frameHeight = CGRectGetHeight(self.bounds);

    // -----

    BOOL imageExists = (self.imageView.image != nil);
    CGSize imageSize = self.imageView.image.size;

    CGFloat textLabelMaxWidth;

    if (imageExists) {
        textLabelMaxWidth = frameWidth - (LGAlertViewPaddingWidth * 2.0) - imageSize.width - LGAlertViewButtonImageOffsetFromTitle;
    }
    else {
        textLabelMaxWidth = frameWidth - (LGAlertViewPaddingWidth * 2.0);
    }

    CGRect textLabelFrame = CGRectMake(NSNotFound,
                                       LGAlertViewPaddingHeight,
                                       textLabelMaxWidth,
                                       frameHeight - (LGAlertViewPaddingHeight * 2.0));

    if (self.textLabel.textAlignment == NSTextAlignmentLeft) {
        textLabelFrame.origin.x = LGAlertViewPaddingWidth;

        if (imageExists && self.iconPosition == LGAlertViewButtonIconPositionLeft) {
            textLabelFrame.origin.x += imageSize.width + LGAlertViewButtonImageOffsetFromTitle;
        }
    }
    else if (self.textLabel.textAlignment == NSTextAlignmentRight) {
        textLabelFrame.origin.x = frameWidth - textLabelMaxWidth - LGAlertViewPaddingWidth;

        if (imageExists && self.iconPosition == LGAlertViewButtonIconPositionRight) {
            textLabelFrame.origin.x -= imageSize.width + LGAlertViewButtonImageOffsetFromTitle;
        }
    }
    else {
        textLabelFrame.origin.x = (frameWidth / 2.0) - (textLabelMaxWidth / 2.0);

        if (imageExists) {
            if (self.iconPosition == LGAlertViewButtonIconPositionLeft) {
                textLabelFrame.origin.x += (imageSize.width / 2.0) + (LGAlertViewButtonImageOffsetFromTitle / 2.0);
            }
            else {
                textLabelFrame.origin.x -= (imageSize.width / 2.0) + (LGAlertViewButtonImageOffsetFromTitle / 2.0);
            }
        }
    }

    if (LGAlertViewHelper.isNotRetina) {
        textLabelFrame = CGRectIntegral(textLabelFrame);
    }

    self.textLabel.frame = textLabelFrame;

    // -----

    if (self.imageView.image) {
        CGSize imageSize = self.imageView.image.size;

        CGRect imageViewFrame = CGRectMake(NSNotFound,
                                           (frameHeight / 2.0) - (imageSize.height / 2.0),
                                           imageSize.width,
                                           imageSize.height);

        if (self.textLabel.textAlignment == NSTextAlignmentCenter) {
            CGSize textLabelSize = [self.textLabel sizeThatFits:CGSizeMake(textLabelMaxWidth, CGFLOAT_MAX)];
            CGFloat imageAndTextWidth = imageSize.width + textLabelSize.width + LGAlertViewButtonImageOffsetFromTitle;

            if (self.iconPosition == LGAlertViewButtonIconPositionLeft) {
                imageViewFrame.origin.x = (frameWidth / 2.0) - (imageAndTextWidth / 2.0);
            }
            else {
                imageViewFrame.origin.x = (frameWidth / 2.0) + (imageAndTextWidth / 2.0) - imageSize.width;
            }
        }
        else {
            if (self.iconPosition == LGAlertViewButtonIconPositionLeft) {
                imageViewFrame.origin.x = LGAlertViewPaddingWidth;
            }
            else {
                imageViewFrame.origin.x = frameWidth - imageSize.width - LGAlertViewPaddingWidth;
            }
        }

        if (LGAlertViewHelper.isNotRetina) {
            imageViewFrame = CGRectIntegral(imageViewFrame);
        }

        self.imageView.frame = imageViewFrame;
    }

    // -----

    if (!self.separatorView.hidden) {
        self.separatorView.frame = CGRectMake(0.0,
                                              CGRectGetHeight(self.bounds) - LGAlertViewHelper.separatorHeight,
                                              CGRectGetWidth(self.bounds),
                                              LGAlertViewHelper.separatorHeight);
    }
}

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    [super setHighlighted:highlighted animated:animated];

    if (highlighted) {
        self.textLabel.textColor = self.titleColorHighlighted;
        self.imageView.image = self.imageHighlighted;
        self.backgroundColor = self.backgroundColorHighlighted;
    }
    else {
        [self setEnabled:self.enabled];
    }

    [self clearBackgrounds];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    if (selected) {
        self.textLabel.textColor = self.titleColorHighlighted;
        self.imageView.image = self.imageHighlighted;
        self.backgroundColor = self.backgroundColorHighlighted;
    }
    else {
        [self setEnabled:self.enabled];
    }

    [self clearBackgrounds];
}

- (void)setEnabled:(BOOL)enabled {
    _enabled = enabled;

    self.userInteractionEnabled = enabled;

    if (enabled) {
        self.textLabel.textColor = self.titleColor;
        self.imageView.image = self.image;
        self.backgroundColor = self.backgroundColorNormal;
    }
    else {
        self.textLabel.textColor = self.titleColorDisabled;
        self.imageView.image = self.imageDisabled;
        self.backgroundColor = self.backgroundColorDisabled;
    }
}

- (CGSize)sizeThatFits:(CGSize)size {
    CGSize sizeForTextLabel = size;
    sizeForTextLabel.width -= LGAlertViewPaddingWidth * 2.0;

    if (self.imageView.image) {
        sizeForTextLabel.width -= self.imageView.image.size.width + LGAlertViewButtonImageOffsetFromTitle;
    }

    CGSize labelSize = [self.textLabel sizeThatFits:size];

    CGSize resultSize;

    if (self.imageView.image) {
        CGSize imageSize = self.imageView.image.size;

        CGFloat width = MAX(labelSize.width, imageSize.width);
        width = MIN(width, size.width);

        CGFloat height = MAX(labelSize.height, imageSize.height);

        resultSize = CGSizeMake(width, height);
    }
    else {
        resultSize = labelSize;
    }

    resultSize.height += LGAlertViewPaddingHeight * 2.0;

    return resultSize;
}

- (void)clearBackgrounds {
    self.textLabel.backgroundColor = UIColor.clearColor;
    self.imageView.backgroundColor = UIColor.clearColor;
}

@end


text:
package org.apache.synapse.config.xml;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.SynapseException;
import org.apache.synapse.message.processors.MessageProcessor;
import org.apache.synapse.util.xpath.SynapseXPath;

import javax.xml.namespace.QName;
import java.util.Iterator;

/**
 * Create an instance of the given Message processor, and sets properties on it.
 * <p/>
 * <messageProcessor name="string" class="classname" messageStore = "string" >
 * <parameter name="string"&gt"string" <parameter>
 * <parameter name="string"&gt"string" <parameter>
 * <parameter name="string"&gt"string" <parameter>
 * <parameter name="string" expression="string">
 * .
 * .
 * </messageProcessor>
 */
public class MessageProcessorSerializer {

    private static final Log log = LogFactory.getLog(MessageProcessorSerializer.class);

    protected static final OMFactory fac = OMAbstractFactory.getOMFactory();
    protected static final OMNamespace synNS = SynapseConstants.SYNAPSE_OMNAMESPACE;
    protected static final OMNamespace nullNS = fac.createOMNamespace(
            XMLConfigConstants.NULL_NAMESPACE, "");

    /**
     * Serialize a give Message processor instance to XML configuration
     *
     * @param parent    parent configuration
     * @param processor message processor instance
     * @return created XML configuration
     */
    public static OMElement serializeMessageProcessor(OMElement parent,
                                                      MessageProcessor processor) {
        OMElement processorElem = fac.createOMElement("messageProcessor", synNS);
        if (processor != null) {
            processorElem.addAttribute(fac.createOMAttribute("class", nullNS,
                                                             processor.getClass().getName()));
        } else {
            handleException("Invalid processor. Provider is required");
        }

        if (processor.getName() != null) {
            processorElem.addAttribute(fac.createOMAttribute("name", nullNS, processor.getName()));
        } else {
            handleException("Message store Name not specified");
        }

        if (processor.getMessageStoreName() != null) {
            processorElem.addAttribute(fac.createOMAttribute(
                    "messageStore", nullNS, processor.getMessageStoreName()));
        }

        if (processor.getParameters() != null) {
            Iterator iterator = processor.getParameters().keySet().iterator();
            while (iterator.hasNext()) {
                String name = (String) iterator.next();
                Object object = processor.getParameters().get(name);
                OMElement property = fac.createOMElement("parameter", synNS);
                property.addAttribute(fac.createOMAttribute(
                        "name", nullNS, name));

                if (object instanceof String) {
                    String value = (String) object;
                    property.setText(value.trim());

                } else if (object instanceof SynapseXPath) {
                    SynapseXPath expression = (SynapseXPath) object;
                    SynapseXPathSerializer.serializeXPath(expression,property,"expression");

                }

                processorElem.addChild(property);

            }
        }

        if (getSerializedDescription(processor) != null) {
            processorElem.addChild(getSerializedDescription(processor));
        }

        if (parent != null) {
            parent.addChild(processorElem);
        }
        return processorElem;
    }

    private static void handleException(String msg) {
        log.error(msg);
        throw new SynapseException(msg);
    }

    private static OMElement getSerializedDescription(MessageProcessor processor) {
        OMElement descriptionElem = fac.createOMElement(
                new QName(SynapseConstants.SYNAPSE_NAMESPACE, "description"));

        if (processor.getDescription() != null) {
            descriptionElem.setText(processor.getDescription());
            return descriptionElem;
        } else {
            return null;
        }
    }

}