text:
#import "NSFNanoObjectProtocol.h"
#import "NSFNanoObject.h"
#import "NSFNanoGlobals.h"
#import "NSFNanoStore.h"
#import "NSFNanoPredicate.h"
#import "NSFNanoExpression.h"
#import "NSFNanoSearch.h"
#import "NSFNanoSortDescriptor.h"
#import "NSFNanoResult.h"
#import "NSFNanoBag.h"
#import "NSFNanoEngine.h"
#import "NSFNanoGlobals.h"

/**
 @mainpage Welcome To NanoStore

 @section whatis_sec What is NanoStore?

 NanoStore is an open source, lightweight schema-less local key-value document store written in Objective-C for Mac OS X and iOS.

 Relational databases tend to have a rich understanding of the structure of your data, but requires some planing beforehand and some level of
 maintenance as well. NanoStore provides the flexibility that comes with key-value document stores, but still understands something about your data.
 Because the data is key-value based, it can be accessed quickly and can grow as much as needed... all without ever worrying about the schema.

 @section mainadv_sec Main advantages

 - No SQL knowledge required
 - Schema-less
 - Key-value based storage
 - Store your own custom objects
 - Bags, a free-form relational system
 - Fast, direct object manipulation
 - Dynamic queries
 - Full index support, inner-objects, embedded arrays and dictionaries
 - Convenience methods to access, manipulate and maintain SQLite databases
 - Full SQLite access available
 - Mac OS X Lion 10.7 and iOS 5 ready
 - iOS library runs on the device and simulator
 - ARC compliant

 @section installation_sec Installation

 Building NanoStore is very easy. Just follow these steps:

 - 1) Download NanoStore
 - 2) Open the NanoStore.xcodeproj file
 - 3) Select Universal > My Mac 64-bit or 32-bit from the Scheme popup
 - 4) Build (Command-B)

 Now you should have a new Distribution directory within the NanoStore project directory which contains the Universal static library (armv6/armv7/i386)
 as well as the header files. To add it in your project, do the following:

 - 1) Drag the Distribution directory to the Project Navigator panel
 - 2) Include #import "NanoStore.h" in your code

 @details Example:
 @code
 #import "NanoStore.h"

 @implementation MyDemoAppDelegate

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
     // Override point for customization after application launch.
     // Instantiate a NanoStore and open it

     NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];
     ...
 @endcode

 @note
 If you want to add a dependency between your project and NanoStore so that it gets automatically rebuilt when
 you update NanoStore, do the following (we'll assume your app is called "MyDemoApp"):

 - 1) Select the MyDemoApp project in the Project Navigator
 - 2) Select the MyDemoApp target
 - 3) Expand the Target Dependencies box
 - 4) Click "+" and add NanoStore

 @section howitworks_sec How does NanoStore work?

 The basic unit of data in NanoStore is called NanoObject. A NanoObject is any object which conforms to the NSFNanoObjectProtocol protocol.

 At its core, a NanoObject is nothing more than a wrapper around two properties:

 - A dictionary which contains the metadata (provided by the developer)
 - A key (UUID) that identifies the object (provided by NanoStore)

 The dictionary must be serializable, which means that only the following data types are allowed:

 - NSArray
 - NSDictionary
 - NSString
 - NSData (*)
 - NSDate
 - NSNumber

 (*) The data type NSData is allowed, but it will be excluded from the indexing process.

 To save and retrieve objects from the document store, NanoStore moves the data around by encapsulating it in NanoObjects. In order to store the objects in
 NanoStore the developer has three options:

 - Use the NSFNanoObject class directly
 - Expand your custom classes by inheriting from NSFNanoObject
 - Expand your custom classes by implementing the NSFNanoObjectProtocol protocol

 Regardless of the route you decide to take, NanoStore will be able to store and retrieve objects from the document store seamlessly. The beauty of this system is that
 NanoStore returns the object as it was stored, that is, instantiating an object of the class that was originally stored.

 @note
 If the document store is opened by another application that doesn't implement the object that was stored, NanoStore will instantiate a
 NSFNanoObject instead, thus allowing the app to retrieve the data seamlessly. If the object is then updated by this application, the original
 class name will be honored.

 Example:

 - App A stores an object of class Car.
 - App B retrieves the object, but since it doesn't know anything about the class Car, NanoStore returns a NSFNanoObject.
 - App B updates the object, perhaps adding a timestamp or additional information. NanoStore saves it as a Car, not as a NSFNanoObject.
 - App A retrieves the updated object as a Car object, in exactly the same format as it was originally stored.

 @section typesofdocumentstores Types of Document Stores

 There are three types of document stores available in NanoStore: in-memory, temporary and file-based. These document stores are defined by the \link NSFGlobals::NSFNanoStoreType NSFNanoStoreType \endlink type:

 - NSFMemoryStoreType: create the transient backing store in RAM. Its contents are lost when the process exits. Fastest, uses more RAM (*).
 - NSFTemporaryStoreType: create a transient temporary backing store on disk. Its contents are lost when the process exits. Slower, uses less RAM than NSFMemoryStoreType.
 - NSFPersistentStoreType:create a persistant backing store on disk. Slower, uses less RAM than NSFMemoryStoreType (*).

 @note
 Until the limit set by NSFNanoEngine's \link NSFNanoEngine::cacheSize - (NSUInteger)cacheSize \endlink has been reached, memory usage would be the same for in-memory store and on-disk store. When the size
 of the store grows beyond \link NSFNanoEngine::cacheSize - (NSUInteger)cacheSize \endlink in-memory stores start to consume more memory than on-disk ones, because it has nowhere to push pages out of the cache.

 Typically, most developers may want to create and open the document store. To do that, use NSFNanoStore's \link createAndOpenStoreWithType:path:error: + (NSFNanoStore *)createAndOpenStoreWithType:(NSFNanoStoreType)theType path:(NSString *)thePath error:(out NSError **)outError \endlink method.

 @details Example:
 @code
 // Instantiate an in-memory document store and open it. The path parameter is unused.
 NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];

 // Instantiate a temporary document store and open it. The path parameter is unused.
 NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFTemporaryStoreType path:nil error:nil];

 // Instantiate a file-based document store and open it. The path parameter must be specified.
 NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFPersistentStoreType path:@"~/Desktop/myDatabase.database" error:nil];
 @endcode

 @note
 In the case of file-based document stores, the file gets created automatically if it doesn't exist and then opened. If it already exists, it gets opened and made available for use right away.

 There are instances where you may want to fine-tune the engine. Tunning the engine has to be performed before the document store is opened. Another method is available In NSFNanoStore for this
 purpose: \link createStoreWithType:path: + (NSFNanoStore *)createStoreWithType:(NSFNanoStoreType)theType path:(NSString *)thePath \endlink.

 @details Example:
 @code
 // Instantiate a file-based document store but don't open it right away. The path parameter must be specified.
 NSFNanoStore *nanoStore = [NSFNanoStore createStoreWithType:NSFPersistentStoreType path:@"~/Desktop/myDatabase.database" error:nil];

 // Obtain the engine
 NSFNanoEngine *nanoStoreEngine = [nanoStore nanoStoreEngine];

 // Set the synchronous mode setting
 [nanoStoreEngine setSynchronousMode:SynchronousModeOff];
 [nanoStoreEngine setEncodingType:NSFEncodingUTF16];

 // Open the document store
 [nanoStore openWithError:nil];
 @endcode

 @note
 Check the section Performance Tips below for important information about how to get the most out of NanoStore.

 @section workingwithnanoobject_sec Working with a NanoObject

 There are three basic operations that NanoStore can perform with a NanoObject:

 - Add it to the document store
 - Update an existing object in the document store
 - Remove it from the document store

 To add an object, instantiate a \link NSFNanoObject::nanoObject NanoObject, \endlink populate it and add it to the document store.

 @details Example:
 @code
 // Instantiate a NanoStore and open it
 NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];

 // Generate an empty NanoObject
 NSFNanoObject *object = [NSFNanoObject nanoObject];

 // Add some data
 [object setObject:@"Doe" forKey:@"kLastName"];
 [object setObject:@"John" forKey:@"kFirstName"];
 [object setObject:[NSArray arrayWithObjects:@"jdoe@foo.com", @"jdoe@bar.com", nil] forKey:@"kEmails"];

 // Add it to the document store
 [nanoStore addObject:object error:nil];

 // Close the document store
 [nanoStore closeWithError:nil];
 @endcode

 Alternatively, you can instantiate a \link NSFNanoObject::nanoObject NanoObject \endlink providing a dictionary via \link NSFNanoObject::nanoObjectWithDictionary: + (NSFNanoObject*)nanoObjectWithDictionary:(NSDictionary *)theDictionary. \endlink
 NanoStore will assign a UUID automatically when the \link NSFNanoObject::nanoObjectWithDictionary: NanoObject \endlink
 is instantiated. This means that requesting the key from the \link NSFNanoObject::nanoObjectWithDictionary: NanoObject \endlink will return a valid UUID.
 The same holds true for objects that inherit from NSFNanoObject. However, classes that implement the NSFNanoObjectProtocol protocol should
 make sure they return a valid key via \link NSFNanoObjectProtocol::nanoObjectKey - (NSString *)nanoObjectKey \endlink

 @warning
 If an attempt is made to add or remove an object without a valid key, an exception of type \ref NSFGlobals::NSFNanoObjectBehaviorException
 "NSFNanoObjectBehaviorException" will be raised.

 To update an object, simply modify the object and add it to the document store. NanoStore will replace the existing object with the one being added.

 @details Example:
 @code
 // Instantiate and open a NanoStore
 NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];

 // Assuming the dictionary exists, instantiate a NanoObject
 NSDictionary *info = ...;
 NSFNanoObject *object = [NSFNanoObject nanoObjectWithDictionary:info];

 // Add the NanoObject to the document store
 [nanoStore addObject:object error:nil];

 // Update the NanoObject with new data
 [object setObject:@"foo" forKey:@"SomeKey"];

 // Update the NanoObject in the document store
 [nanoStore addObject:object error:nil];
 @endcode

 To remove an object, there are several options available. The most common methods are found in NSFNanoStore:

 - \link NSFNanoStore::removeObject:error: - (BOOL)removeObject:(id <NSFNanoObjectProtocol>)theObject error:(out NSError **)outError \endlink
 - \link NSFNanoStore::removeObjectsWithKeysInArray:error: - (BOOL)removeObjectsWithKeysInArray:(NSArray *)theKeys error:(out NSError **)outError \endlink
 - \link NSFNanoStore::removeObjectsInArray:error: - (BOOL)removeObjectsInArray:(NSArray *)theObjects error:(out NSError **)outError \endlink

 @details Example:
 @code
 // Instantiate and open a NanoStore
 NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];

 // Assuming the dictionary exists, instantiate a NanoObject
 NSDictionary *info = ...;
 NSFNanoObject *object = [NSFNanoObject nanoObjectWithDictionary:info];

 // Add the NanoObject to the document store
 [nanoStore addObject:object error:nil];

 // Remove the object
 [nanoStore removeObject:object error:nil];

 // ... or you could pass the key instead
 [nanoStore removeObjectsWithKeysInArray:[NSArray arrayWithObject:[object nanoObjectKey]] error:nil];
 @endcode

 @section notaflatworld_sec It's not a flat World

 Most database solutions force the developer to think in a two-dimensional space (rows and columns), forcing the developer to plan the schema ahead of
 time. This situation is not ideal because in most cases schema refinements could be required, oftentimes impacting the code as well.

 NanoStore goes beyond that allowing the developer to store objects in their natural form. These objects must conform to the NSFNanoObjectProtocol
 protocol, providing NanoStore with the NSDictionary that will be stored. By using a dictionary data can be inspected very quickly, and it also allows the
 structure to be defined in a hierarchical fashion as well, due to the fact that it includes support for nested collections (of type NSDictionary and NSArray.)
 Each inner-object is indexed automatically, thus allowing to quickly find objects which contain a specific key and/or value.

 By default, NanoStore allows objects to be stored without any sense of relationship to other objects. This simple format, while powerful, is limited because
 the developer has to keep track of the relationships among objects. Some applications may need to relate objects, some of them perhaps of different nature or class
 type. This is exactly what NanoBag (represented by the NSFNanoBag class) does: it allows any object conforming to the NSFNanoObjectProtocol protocol to be
 added to the bag. By saving the bag with one single call, the new and/or modified are taken care of seamlessly.

 The NSFNanoBag API is rich, allowing the developer to add, remove, reload and undo its changes, deflate it (thus saving memory) and inflate it whenever it's
 required. In addition, it provides methods to obtain all bags, specific bags matching some keys, and bags containing a specific object
 (see NSFNanoStore for more information).

 @section wherearetheobjects_sec Where are my objects?

 While NSFNanoStore provides some convenience methods to obtain standard objects such as bags, the bulk of the search mechanism is handled by NSFNanoSearch.
 The steps involved to perform a search are quite simple:

 - 1) Instantiate a search object
 - 2) Configure the search via its accessors
 - 3) Obtain the results specifying whether objects or keys should be returned (*)

 (*) If introspecting the data is needed, request objects. You should request keys if you need to feed the result to another method, such as NSFNanoStore
 \link NSFNanoStore::removeObjectsWithKeysInArray:error: -(BOOL)removeObjectsWithKeysInArray:(NSArray *)theKeys error:(out NSError **)outError \endlink method.

 @details Example: finding all objects with the attribute 'LastName' and value 'Doe'.
 @code
 NSFNanoSearch *search = [NSFNanoSearch searchWithStore:nanoStore];

 search.attribute = @"LastName";
 search.match = NSFEqualTo;
 search.value = @"Doe";

 // Returns a dictionary with the UUID of the object (key) and the NanoObject (value).
 NSDictionary *searchResults = [search searchObjectsWithReturnType:NSFReturnObjects error:nil];
 @endcode

 @details Example: removing all objects with the attribute 'LastName' and value 'Doe'.
 @code
 NSFNanoSearch *search = [NSFNanoSearch searchWithStore:nanoStore];

 search.attribute = @"LastName";
 search.match = NSFEqualTo;
 search.value = @"Doe";

 // Returns an array of matching UUIDs
 NSArray *matchingKeys = [search searchObjectsWithReturnType:NSFReturnKeys error:nil];

 // Remove the NanoObjects matching the selected UUIDs
 NSError *outError = nil;
 if (YES == [nanoStore removeObjectsWithKeysInArray:matchingKeys error:&outError]) {
    NSLog(@"The matching objects have been removed.");
 } else {
    NSLog(@"An error has occurred while removing the matching objects. Reason: %@", [outError localizedDescription]);
 }
 @endcode

 Another cool feature is the possibility to invoke aggregated functions (count, avg, min, max and total) on the search results. Using the search snippet above,
 calculating the average salary of all people with last name equal to 'Doe' is very easy.

 @details Example: calculating the average salary of all objects with the attribute 'LastName' and value 'Doe'.
 @code
 NSFNanoSearch *search = [NSFNanoSearch searchWithStore:nanoStore];

 search.attribute = @"LastName";
 search.match = NSFEqualTo;
 search.value = @"Doe";

 float averageSalary = [[search aggregateOperation:NSFAverage onAttribute:@"Salary"]floatValue];
 @endcode

 @section sorting_sec Sorting

 Combining search and sort is an extremely easy operation. There are two simple parts:

 - 1) Preparing your classes for sorting
 - 2) Setup a search operation and set its sort descriptors

 @section preparesorting_sec Preparing your classes for sorting

 Since NanoStore relies on KVC to perform the sorts, a hint of the location where the data lives within the object is required. Since KVC uses a key path to reach the element being sorted, we need a way to "point" to it. Most custom classes will return self, as is the case for NSFNanoBag:

 @code
 - (id)rootObject
 {
     return self;
 }
 @endcode

 Self in this case represents the top level, the location where the variables name, key and hasUnsavedChanges are located:

 @code
 @interface NSFNanoBag : NSObject <NSFNanoObjectProtocol, NSCopying>
 {
      NSFNanoStore     *store;
      NSString         *name;
      NSString         *key;
      BOOL             hasUnsavedChanges;
 }
 @endcode

 Assume we have an object that represents a person and its root object is set to self, just as demonstrated above:

 @code
 @interface Person : NSFNanoObject
 {
       NSString        *firstName;
       NSString        *lastName;
       NSString        *email;
 }
 @endcode

 If we wanted to retrieve all the existing people with firstName equal to John sorted by lastName we would do the following:

 @code
 // Assume NanoStore has been opened elsewhere
 NSFNanoStore *nanoStore = ...;

 // Prepare the search
 NSFNanoSearch *search = [NSFNanoSearch searchWithStore:nanoStore];
 search.attribute = @"firstName";
 search.match = NSFEqualTo;
 search.value = @"John";

 // Prepare and set the sort descriptor
 NSFNanoSortDescriptor *sortByLastName = [[NSFNanoSortDescriptor alloc]initWithAttribute:@"lastName" ascending:YES];
 search.sort = [NSArray arrayWithObject:sortByLastName];

 // Perform the search
 NSArray *searchResults = [search searchObjectsWithReturnType:NSFReturnObjects error:nil];

 // Cleanup
 [sortByLastName release];
 @endcode

 @section performancetips_sec Performance Tips

 NanoStore by defaults saves every object to disk one by one. To speed up inserts and edited objects, increase NSFNanoStore's \link NSFNanoStore::saveInterval saveInterval \endlink property.

 @details Example:
 @code
 // Instantiate and open a NanoStore
 NSFNanoStore *nanoStore = [NSFNanoStore createAndOpenStoreWithType:NSFMemoryStoreType path:nil error:nil];

 // Increase the save interval
 [nanoStore setSaveInterval:1000];

 // Do a bunch of inserts and/or edits

 // Don't forget that some objects could be lingering in memory. Force a save.
 [nanoStore saveStoreAndReturnError:nil];
 @endcode

 @note If you set the saveInterval value to anything other one, keep in mind that some objects may still be left unsaved after being added or modified. To make sure they're saved properly, call \link NSFNanoStore::saveStoreAndReturnError: - (BOOL)saveStoreAndReturnError:(out NSError **)outError \endlink.

 Choosing a good saveInterval value is more art than science. While testing NanoStore using a medium-sized dictionary (iTunes' MP3 dictionary) setting saveInterval to 1000 resulted in the best performance. You may want to test with different numbers and fine-tune it for your data set.

 @warning Setting saveInterval to a large number could result in decreased performance because SQLite's would have to spend more time reading the journal file and writing the changes to the database.

 @section needhelp_sec Need more help?
 There are two quick ways to find answers: reading the documentation and browsing the Unit tests.

 While several attempts have been made to make the documentation easy to read and understand, it's far from perfect. If you find that the documentation is
 incomplete, incorrect or needs some clarification, please file a bug. I'll appreciate it and correct it as soon as possible:

 - NanoStore Documentation: http://dl.dropbox.com/u/2601212/NanoStore%202.0/html/index.html
 - NanoStore Bug Tracker: https://github.com/tciuro/NanoStore/issues
 - Twitter: http://twitter.com/nanostoredev

 @section officialsourcerepo_sec Official Source Repository
 The official repository for NanoStore is hosted on GitHub: https://github.com/tciuro/NanoStore
 	*/


text:
package org.olat.restapi.repository.course;

import static org.olat.restapi.security.RestSecurityHelper.getIdentity;
import static org.olat.restapi.security.RestSecurityHelper.getUserRequest;
import static org.olat.restapi.security.RestSecurityHelper.isAuthor;
import static org.olat.restapi.security.RestSecurityHelper.isAuthorEditor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.olat.admin.securitygroup.gui.IdentitiesAddEvent;
import org.olat.basesecurity.BaseSecurity;
import org.olat.basesecurity.BaseSecurityManager;
import org.olat.basesecurity.Constants;
import org.olat.basesecurity.SecurityGroup;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.tree.TreeNode;
import org.olat.core.helpers.Settings;
import org.olat.core.id.Identity;
import org.olat.core.id.OLATResourceable;
import org.olat.core.logging.OLog;
import org.olat.core.logging.Tracing;
import org.olat.core.util.nodes.INode;
import org.olat.core.util.resource.OresHelper;
import org.olat.core.util.vfs.VFSItem;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.course.CourseFactory;
import org.olat.course.CourseModule;
import org.olat.course.ICourse;
import org.olat.course.editor.PublishProcess;
import org.olat.course.editor.StatusDescription;
import org.olat.course.tree.CourseEditorTreeModel;
import org.olat.course.tree.PublishTreeModel;
import org.olat.repository.RepositoryEntry;
import org.olat.repository.RepositoryManager;
import org.olat.resource.OLATResource;
import org.olat.resource.OLATResourceManager;
import org.olat.restapi.support.ObjectFactory;
import org.olat.restapi.support.vo.CourseConfigVO;
import org.olat.restapi.support.vo.CourseVO;
import org.olat.user.restapi.UserVO;
import org.olat.user.restapi.UserVOFactory;

import com.thoughtworks.xstream.XStream;

/**
 * Description:

 * This web service will handle the functionality related to Course and its contents.
 *

 * Initial Date: 27 apr. 2010

 *
 * @author srosse, stephane.rosse@frentix.com
 */
@Path("repo/courses/{courseId}")
public class CourseWebService {

	private static final OLog log = Tracing.createLoggerFor(CourseWebService.class);
	private static final XStream myXStream = XStreamHelper.createXStreamInstance();

	private static final String VERSION = "1.0";

	/**
	 * The version of the Course Web Service
	 *
	 * @response.representation.200.mediaType text/plain
	 * @response.representation.200.doc The version of this specific Web Service
	 * @response.representation.200.example 1.0
	 * @return
	 */
	@GET
	@Path("version")
	@Produces(MediaType.TEXT_PLAIN)
	public Response getVersion() {
		return Response.ok(VERSION).build();
	}

	@Path("groups")
	public CourseGroupWebService getCourseGroupWebService(@PathParam("courseId") final Long courseId) {
		final OLATResource ores = getCourseOLATResource(courseId);
		return new CourseGroupWebService(ores);
	}

	/**
	 * Publish the course.
	 *
	 * @response.representation.200.qname {http://www.example.com}courseVO
	 * @response.representation.200.mediaType application/xml, application/json
	 * @response.representation.200.doc The metadatas of the created course
	 * @response.representation.200.example {@link org.olat.restapi.support.vo.Examples#SAMPLE_COURSEVO}
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The course not found
	 * @param courseId The course resourceable's id
	 * @param locale The course locale
	 * @param request The HTTP request
	 * @return It returns the metadatas of the published course.
	 */
	@POST
	@Path("publish")
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Response publishCourse(@PathParam("courseId") final Long courseId, @QueryParam("locale") final Locale locale, @Context final HttpServletRequest request) {
		if (!isAuthor(request)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final UserRequest ureq = getUserRequest(request);
		final ICourse course = loadCourse(courseId);
		if (course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if (!isAuthorEditor(course, request)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }
		publishCourse(course, ureq.getIdentity(), locale);
		final CourseVO vo = ObjectFactory.get(course);
		return Response.ok(vo).build();
	}

	/**
	 * Publish a course
	 *
	 * @param course
	 * @param identity
	 * @param locale
	 */
	private void publishCourse(ICourse course, final Identity identity, final Locale locale) {
		try {
			final CourseEditorTreeModel cetm = course.getEditorTreeModel();
			final PublishProcess publishProcess = PublishProcess.getInstance(course, cetm, locale);
			final PublishTreeModel publishTreeModel = publishProcess.getPublishTreeModel();

			final int newAccess = RepositoryEntry.ACC_USERS;
			// access rule -> all users can the see course
			// RepositoryEntry.ACC_OWNERS
			// only owners can the see course
			// RepositoryEntry.ACC_OWNERS_AUTHORS //only owners and authors can the see course
			// RepositoryEntry.ACC_USERS_GUESTS // users and guests can see the course
			publishProcess.changeGeneralAccess(null, newAccess);

			if (publishTreeModel.hasPublishableChanges()) {
				final List<String> nodeToPublish = new ArrayList<String>();
				visitPublishModel(publishTreeModel.getRootNode(), publishTreeModel, nodeToPublish);

				publishProcess.createPublishSetFor(nodeToPublish);
				final StatusDescription[] status = publishProcess.testPublishSet(locale);
				// publish not possible when there are errors
				for (int i = 0; i < status.length; i++) {
					if (status[i].isError()) { return; }
				}
			}

			course = CourseFactory.openCourseEditSession(course.getResourceableId());
			publishProcess.applyPublishSet(identity, locale);
			CourseFactory.closeCourseEditSession(course.getResourceableId(), true);
		} catch (final Throwable e) {
			throw new WebApplicationException(e);
		}
	}

	private void visitPublishModel(final TreeNode node, final PublishTreeModel publishTreeModel, final Collection<String> nodeToPublish) {
		final int numOfChildren = node.getChildCount();
		for (int i = 0; i < numOfChildren; i++) {
			final INode child = node.getChildAt(i);
			if (child instanceof TreeNode) {
				nodeToPublish.add(child.getIdent());
				visitPublishModel((TreeNode) child, publishTreeModel, nodeToPublish);
			}
		}
	}

	/**
	 * Get the metadatas of the course by id
	 *
	 * @response.representation.200.qname {http://www.example.com}courseVO
	 * @response.representation.200.mediaType application/xml, application/json
	 * @response.representation.200.doc The metadatas of the created course
	 * @response.representation.200.example {@link org.olat.restapi.support.vo.Examples#SAMPLE_COURSEVO}
	 * @response.representation.404.doc The course not found
	 * @param courseId The course resourceable's id
	 * @return It returns the CourseVO object representing the course.
	 */
	@GET
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Response findById(@PathParam("courseId") final Long courseId) {
		final ICourse course = loadCourse(courseId);
		if (course == null) { return Response.serverError().status(Status.NOT_FOUND).build(); }
		final CourseVO vo = ObjectFactory.get(course);
		return Response.ok(vo).build();
	}

	/**
	 * Delete a course by id
	 *
	 * @response.representation.200.doc The metadatas of the created course
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The course not found
	 * @param courseId The course resourceable's id
	 * @param request The HTTP request
	 * @return It returns the XML representation of the Structure object representing the course.
	 */
	@DELETE
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Response deleteCourse(@PathParam("courseId") final Long courseId, @Context final HttpServletRequest request) {
		if (!isAuthor(request)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final ICourse course = loadCourse(courseId);
		if (course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if (!isAuthorEditor(course, request)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }
		// FIXME: this does not remove all data from the database, see repositoryManger
		CourseFactory.deleteCourse(course);
		return Response.ok().build();
	}

	/**
	 * Get the configuration of the course
	 *
	 * @response.representation.200.qname {http://www.example.com}courseConfigVO
	 * @response.representation.200.mediaType application/xml, application/json
	 * @response.representation.200.doc The configuration of the course
	 * @response.representation.200.example {@link org.olat.restapi.support.vo.Examples#SAMPLE_COURSECONFIGVO}
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The course not found
	 * @param courseId The course resourceable's id
	 * @param request The HTTP request
	 * @return It returns the XML representation of the Structure object representing the course.
	 */
	@GET
	@Path("configuration")
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Response getConfiguration(@PathParam("courseId") final Long courseId, @Context final HttpServletRequest request) {
		if (!isAuthor(request)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final ICourse course = loadCourse(courseId);
		if (course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if (!isAuthorEditor(course, request)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }
		final CourseConfigVO vo = ObjectFactory.getConfig(course);
		return Response.ok(vo).build();
	}

	/**
	 * Get the runstructure of the course by id
	 *
	 * @response.representation.200.mediaType application/xml
	 * @response.representation.200.doc The run structure of the course
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The course not found
	 * @param courseId The course resourceable's id
	 * @param httpRequest The HTTP request
	 * @param request The REST request
	 * @return It returns the XML representation of the Structure object representing the course.
	 */
	@GET
	@Path("runstructure")
	@Produces(MediaType.APPLICATION_XML)
	public Response findRunStructureById(@PathParam("courseId") final Long courseId, @Context final HttpServletRequest httpRequest, @Context final Request request) {
		if (!isAuthor(httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final ICourse course = loadCourse(courseId);
		if (course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if (!isAuthorEditor(course, httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }
		final VFSItem runStructureItem = course.getCourseBaseContainer().resolve("runstructure.xml");
		final Date lastModified = new Date(runStructureItem.getLastModified());

		final Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
		if (response == null) { return Response.ok(myXStream.toXML(course.getRunStructure())).build(); }
		return response.build();
	}

	/**
	 * Get the editor tree model of the course by id
	 *
	 * @response.representation.200.mediaType application/xml
	 * @response.representation.200.doc The editor tree model of the course
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The course not found
	 * @param courseId The course resourceable's id
	 * @param httpRequest The HTTP request
	 * @param request The REST request
	 * @return It returns the XML representation of the Editor model object representing the course.
	 */
	@GET
	@Path("editortreemodel")
	@Produces(MediaType.APPLICATION_XML)
	public Response findEditorTreeModelById(@PathParam("courseId") final Long courseId, @Context final HttpServletRequest httpRequest, @Context final Request request) {
		if (!isAuthor(httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final ICourse course = loadCourse(courseId);
		if (course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if (!isAuthorEditor(course, httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }
		final VFSItem editorModelItem = course.getCourseBaseContainer().resolve("editortreemodel.xml");
		final Date lastModified = new Date(editorModelItem.getLastModified());

		final Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
		if (response == null) { return Response.ok(myXStream.toXML(course.getEditorTreeModel())).build(); }
		return response.build();
	}

	/**
	 * Get all owners and authors of the course
	 *
	 * @response.representation.200.qname {http://www.example.com}userVO
	 * @response.representation.200.mediaType application/xml, application/json
	 * @response.representation.200.doc The array of authors
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The course not found
	 * @param courseId The course resourceable's id
	 * @param httpRequest The HTTP request
	 * @return It returns an array of UserVO
	 */
	@GET
	@Path("authors")
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Response getAuthors(@PathParam("courseId") final Long courseId, @Context final HttpServletRequest httpRequest) {
		if (!isAuthor(httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final OLATResourceable course = getCourseOLATResource(courseId);
		if (course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if (!isAuthorEditor(course, httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final RepositoryManager rm = RepositoryManager.getInstance();
		final RepositoryEntry repositoryEntry = rm.lookupRepositoryEntry(course, true);
		final SecurityGroup sg = repositoryEntry.getOwnerGroup();

		final BaseSecurity securityManager = BaseSecurityManager.getInstance();
		final List<Object[]> owners = securityManager.getIdentitiesAndDateOfSecurityGroup(sg);

		int count = 0;
		final UserVO[] authors = new UserVO[owners.size()];
		for (int i = 0; i < owners.size(); i++) {
			final Identity identity = (Identity) owners.get(i)[0];
			authors[count++] = UserVOFactory.get(identity);
		}
		return Response.ok(authors).build();
	}

	/**
	 * Get this specific author and owner of the course
	 *
	 * @response.representation.200.qname {http://www.example.com}userVO
	 * @response.representation.200.mediaType application/xml, application/json
	 * @response.representation.200.doc The author
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The course not found or the user is not an onwer or author of the course
	 * @param courseId The course resourceable's id
	 * @param identityKey The user identifier
	 * @param httpRequest The HTTP request
	 * @return It returns an UserVO
	 */
	@GET
	@Path("authors/{identityKey}")
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Response getAuthor(@PathParam("courseId") final Long courseId, @PathParam("identityKey") final Long identityKey, @Context final HttpServletRequest httpRequest) {
		if (!isAuthor(httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final OLATResourceable course = getCourseOLATResource(courseId);
		if (course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if (!isAuthorEditor(course, httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final RepositoryManager rm = RepositoryManager.getInstance();
		final RepositoryEntry repositoryEntry = rm.lookupRepositoryEntry(course, true);
		final SecurityGroup sg = repositoryEntry.getOwnerGroup();

		final BaseSecurity securityManager = BaseSecurityManager.getInstance();
		final SecurityGroup authorGroup = securityManager.findSecurityGroupByName(Constants.GROUP_AUTHORS);

		final Identity author = securityManager.loadIdentityByKey(identityKey, false);
		if (securityManager.isIdentityInSecurityGroup(author, sg) && securityManager.isIdentityInSecurityGroup(author, authorGroup)) {
			final UserVO vo = UserVOFactory.get(author);
			return Response.ok(vo).build();
		}
		return Response.ok(author).build();
	}

	/**
	 * Add an owner and author to the course
	 *
	 * @response.representation.200.doc The user is an author and owner of the course
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The course or the user not found
	 * @param courseId The course resourceable's id
	 * @param identityKey The user identifier
	 * @param httpRequest The HTTP request
	 * @return It returns 200 if the user is added as owner and author of the course
	 */
	@PUT
	@Path("authors/{identityKey}")
	public Response addAuthor(@PathParam("courseId") final Long courseId, @PathParam("identityKey") final Long identityKey, @Context final HttpServletRequest httpRequest) {
		if (!isAuthor(httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final OLATResourceable course = getCourseOLATResource(courseId);
		if (course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if (!isAuthorEditor(course, httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final BaseSecurity securityManager = BaseSecurityManager.getInstance();
		final Identity author = securityManager.loadIdentityByKey(identityKey, false);
		if (author == null) { return Response.serverError().status(Status.NOT_FOUND).build(); }

		final Identity identity = getIdentity(httpRequest);

		final SecurityGroup authorGroup = securityManager.findSecurityGroupByName(Constants.GROUP_AUTHORS);
		final boolean hasBeenAuthor = securityManager.isIdentityInSecurityGroup(author, authorGroup);
		if (!hasBeenAuthor) {
			// not an author already, add this identity to the security group "authors"
			securityManager.addIdentityToSecurityGroup(author, authorGroup);
		}

		// add the author as owner of the course
		final RepositoryManager rm = RepositoryManager.getInstance();
		final RepositoryEntry repositoryEntry = rm.lookupRepositoryEntry(course, true);
		final List<Identity> authors = Collections.singletonList(author);
		final IdentitiesAddEvent identitiesAddedEvent = new IdentitiesAddEvent(authors);
		rm.addOwners(identity, identitiesAddedEvent, repositoryEntry);

		return Response.ok().build();
	}

	/**
	 * Remove an owner and author to the course
	 *
	 * @response.representation.200.doc The user was successfully removed as owner of the course
	 * @response.representation.401.doc The roles of the authenticated user are not sufficient
	 * @response.representation.404.doc The course or the user not found
	 * @param courseId The course resourceable's id
	 * @param identityKey The user identifier
	 * @param httpRequest The HTTP request
	 * @return It returns 200 if the user is removed as owner of the course
	 */
	@DELETE
	@Path("authors/{identityKey}")
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Response removeAuthor(@PathParam("courseId") final Long courseId, @PathParam("identityKey") final Long identityKey,
			@Context final HttpServletRequest httpRequest) {
		if (!isAuthor(httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final OLATResourceable course = getCourseOLATResource(courseId);
		if (course == null) {
			return Response.serverError().status(Status.NOT_FOUND).build();
		} else if (!isAuthorEditor(course, httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); }

		final BaseSecurity securityManager = BaseSecurityManager.getInstance();
		final Identity author = securityManager.loadIdentityByKey(identityKey, false);
		if (author == null) { return Response.serverError().status(Status.NOT_FOUND).build(); }

		final Identity identity = getIdentity(httpRequest);

		// remove the author as owner of the course
		final RepositoryManager rm = RepositoryManager.getInstance();
		final RepositoryEntry repositoryEntry = rm.lookupRepositoryEntry(course, true);
		final List<Identity> authors = Collections.singletonList(author);
		rm.removeOwners(identity, authors, repositoryEntry);

		return Response.ok().build();
	}

	private OLATResource getCourseOLATResource(final Long courseId) {
		final String typeName = OresHelper.calculateTypeName(CourseModule.class);
		OLATResource ores = OLATResourceManager.getInstance().findResourceable(courseId, typeName);
		if (ores == null && Settings.isJUnitTest()) {
			// hack for the BGContextManagerImpl which load the course
			ores = OLATResourceManager.getInstance().findResourceable(courseId, "junitcourse");
		}
		return ores;
	}

	private ICourse loadCourse(final Long courseId) {
		try {
			final ICourse course = CourseFactory.loadCourse(courseId);
			return course;
		} catch (final Exception ex) {
			log.error("cannot load course with id: " + courseId, ex);
			return null;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _ASM_GENERIC_SIGINFO_H
#define _ASM_GENERIC_SIGINFO_H

#include <linux/types.h>

typedef union sigval {
	int sival_int;
	void *sival_ptr;
} sigval_t;

/*
 * This is the size (including padding) of the part of the
 * struct siginfo that is before the union.
 */
#ifndef __ARCH_SI_PREAMBLE_SIZE
#define __ARCH_SI_PREAMBLE_SIZE	(3 * sizeof(int))
#endif

#define SI_MAX_SIZE	128
#ifndef SI_PAD_SIZE
#define SI_PAD_SIZE	((SI_MAX_SIZE - __ARCH_SI_PREAMBLE_SIZE) / sizeof(int))
#endif

/*
 * The default "si_band" type is "long", as specified by POSIX.
 * However, some architectures want to override this to "int"
 * for historical compatibility reasons, so we allow that.
 */
#ifndef __ARCH_SI_BAND_T
#define __ARCH_SI_BAND_T long
#endif

#ifndef __ARCH_SI_CLOCK_T
#define __ARCH_SI_CLOCK_T __kernel_clock_t
#endif

#ifndef __ARCH_SI_ATTRIBUTES
#define __ARCH_SI_ATTRIBUTES
#endif

typedef struct siginfo {
	int si_signo;
#ifndef __ARCH_HAS_SWAPPED_SIGINFO
	int si_errno;
	int si_code;
#else
	int si_code;
	int si_errno;
#endif

	union {
		int _pad[SI_PAD_SIZE];

		/* kill() */
		struct {
			__kernel_pid_t _pid;	/* sender's pid */
			__kernel_uid32_t _uid;	/* sender's uid */
		} _kill;

		/* POSIX.1b timers */
		struct {
			__kernel_timer_t _tid;	/* timer id */
			int _overrun;		/* overrun count */
			sigval_t _sigval;	/* same as below */
			int _sys_private;       /* not to be passed to user */
		} _timer;

		/* POSIX.1b signals */
		struct {
			__kernel_pid_t _pid;	/* sender's pid */
			__kernel_uid32_t _uid;	/* sender's uid */
			sigval_t _sigval;
		} _rt;

		/* SIGCHLD */
		struct {
			__kernel_pid_t _pid;	/* which child */
			__kernel_uid32_t _uid;	/* sender's uid */
			int _status;		/* exit code */
			__ARCH_SI_CLOCK_T _utime;
			__ARCH_SI_CLOCK_T _stime;
		} _sigchld;

		/* SIGILL, SIGFPE, SIGSEGV, SIGBUS, SIGTRAP, SIGEMT */
		struct {
			void *_addr; /* faulting insn/memory ref. */
#ifdef __ARCH_SI_TRAPNO
			int _trapno;	/* TRAP # which caused the signal */
#endif
#ifdef __ia64__
			int _imm;		/* immediate value for "break" */
			unsigned int _flags;	/* see ia64 si_flags */
			unsigned long _isr;	/* isr */
#endif

#define __ADDR_BND_PKEY_PAD  (__alignof__(void *) < sizeof(short) ? \
			      sizeof(short) : __alignof__(void *))
			union {
				/*
				 * used when si_code=BUS_MCEERR_AR or
				 * used when si_code=BUS_MCEERR_AO
				 */
				short _addr_lsb; /* LSB of the reported address */
				/* used when si_code=SEGV_BNDERR */
				struct {
					char _dummy_bnd[__ADDR_BND_PKEY_PAD];
					void *_lower;
					void *_upper;
				} _addr_bnd;
				/* used when si_code=SEGV_PKUERR */
				struct {
					char _dummy_pkey[__ADDR_BND_PKEY_PAD];
					__u32 _pkey;
				} _addr_pkey;
			};
		} _sigfault;

		/* SIGPOLL */
		struct {
			__ARCH_SI_BAND_T _band;	/* POLL_IN, POLL_OUT, POLL_MSG */
			int _fd;
		} _sigpoll;

		/* SIGSYS */
		struct {
			void *_call_addr; /* calling user insn */
			int _syscall;	/* triggering system call number */
			unsigned int _arch;	/* AUDIT_ARCH_* of syscall */
		} _sigsys;
	} _sifields;
} __ARCH_SI_ATTRIBUTES siginfo_t;

/*
 * How these fields are to be accessed.
 */
#define si_pid		_sifields._kill._pid
#define si_uid		_sifields._kill._uid
#define si_tid		_sifields._timer._tid
#define si_overrun	_sifields._timer._overrun
#define si_sys_private  _sifields._timer._sys_private
#define si_status	_sifields._sigchld._status
#define si_utime	_sifields._sigchld._utime
#define si_stime	_sifields._sigchld._stime
#define si_value	_sifields._rt._sigval
#define si_int		_sifields._rt._sigval.sival_int
#define si_ptr		_sifields._rt._sigval.sival_ptr
#define si_addr		_sifields._sigfault._addr
#ifdef __ARCH_SI_TRAPNO
#define si_trapno	_sifields._sigfault._trapno
#endif
#define si_addr_lsb	_sifields._sigfault._addr_lsb
#define si_lower	_sifields._sigfault._addr_bnd._lower
#define si_upper	_sifields._sigfault._addr_bnd._upper
#define si_pkey		_sifields._sigfault._addr_pkey._pkey
#define si_band		_sifields._sigpoll._band
#define si_fd		_sifields._sigpoll._fd
#define si_call_addr	_sifields._sigsys._call_addr
#define si_syscall	_sifields._sigsys._syscall
#define si_arch		_sifields._sigsys._arch

/*
 * si_code values
 * Digital reserves positive values for kernel-generated signals.
 */
#define SI_USER		0		/* sent by kill, sigsend, raise */
#define SI_KERNEL	0x80		/* sent by the kernel from somewhere */
#define SI_QUEUE	-1		/* sent by sigqueue */
#define SI_TIMER	-2		/* sent by timer expiration */
#define SI_MESGQ	-3		/* sent by real time mesq state change */
#define SI_ASYNCIO	-4		/* sent by AIO completion */
#define SI_SIGIO	-5		/* sent by queued SIGIO */
#define SI_TKILL	-6		/* sent by tkill system call */
#define SI_DETHREAD	-7		/* sent by execve() killing subsidiary threads */
#define SI_ASYNCNL	-60		/* sent by glibc async name lookup completion */

#define SI_FROMUSER(siptr)	((siptr)->si_code <= 0)
#define SI_FROMKERNEL(siptr)	((siptr)->si_code > 0)

/*
 * SIGILL si_codes
 */
#define ILL_ILLOPC	1	/* illegal opcode */
#define ILL_ILLOPN	2	/* illegal operand */
#define ILL_ILLADR	3	/* illegal addressing mode */
#define ILL_ILLTRP	4	/* illegal trap */
#define ILL_PRVOPC	5	/* privileged opcode */
#define ILL_PRVREG	6	/* privileged register */
#define ILL_COPROC	7	/* coprocessor error */
#define ILL_BADSTK	8	/* internal stack error */
#define ILL_BADIADDR	9	/* unimplemented instruction address */
#define __ILL_BREAK	10	/* illegal break */
#define __ILL_BNDMOD	11	/* bundle-update (modification) in progress */
#define NSIGILL		11

/*
 * SIGFPE si_codes
 */
#define FPE_INTDIV	1	/* integer divide by zero */
#define FPE_INTOVF	2	/* integer overflow */
#define FPE_FLTDIV	3	/* floating point divide by zero */
#define FPE_FLTOVF	4	/* floating point overflow */
#define FPE_FLTUND	5	/* floating point underflow */
#define FPE_FLTRES	6	/* floating point inexact result */
#define FPE_FLTINV	7	/* floating point invalid operation */
#define FPE_FLTSUB	8	/* subscript out of range */
#define __FPE_DECOVF	9	/* decimal overflow */
#define __FPE_DECDIV	10	/* decimal division by zero */
#define __FPE_DECERR	11	/* packed decimal error */
#define __FPE_INVASC	12	/* invalid ASCII digit */
#define __FPE_INVDEC	13	/* invalid decimal digit */
#define FPE_FLTUNK	14	/* undiagnosed floating-point exception */
#define FPE_CONDTRAP	15	/* trap on condition */
#define NSIGFPE		15

/*
 * SIGSEGV si_codes
 */
#define SEGV_MAPERR	1	/* address not mapped to object */
#define SEGV_ACCERR	2	/* invalid permissions for mapped object */
#define SEGV_BNDERR	3	/* failed address bound checks */
#ifdef __ia64__
# define __SEGV_PSTKOVF	4	/* paragraph stack overflow */
#else
# define SEGV_PKUERR	4	/* failed protection key checks */
#endif
#define SEGV_ACCADI	5	/* ADI not enabled for mapped object */
#define SEGV_ADIDERR	6	/* Disrupting MCD error */
#define SEGV_ADIPERR	7	/* Precise MCD exception */
#define NSIGSEGV	7

/*
 * SIGBUS si_codes
 */
#define BUS_ADRALN	1	/* invalid address alignment */
#define BUS_ADRERR	2	/* non-existent physical address */
#define BUS_OBJERR	3	/* object specific hardware error */
/* hardware memory error consumed on a machine check: action required */
#define BUS_MCEERR_AR	4
/* hardware memory error detected in process but not consumed: action optional*/
#define BUS_MCEERR_AO	5
#define NSIGBUS		5

/*
 * SIGTRAP si_codes
 */
#define TRAP_BRKPT	1	/* process breakpoint */
#define TRAP_TRACE	2	/* process trace trap */
#define TRAP_BRANCH     3	/* process taken branch trap */
#define TRAP_HWBKPT     4	/* hardware breakpoint/watchpoint */
#define TRAP_UNK	5	/* undiagnosed trap */
#define NSIGTRAP	5

/*
 * There is an additional set of SIGTRAP si_codes used by ptrace
 * that are of the form: ((PTRACE_EVENT_XXX << 8) | SIGTRAP)
 */

/*
 * SIGCHLD si_codes
 */
#define CLD_EXITED	1	/* child has exited */
#define CLD_KILLED	2	/* child was killed */
#define CLD_DUMPED	3	/* child terminated abnormally */
#define CLD_TRAPPED	4	/* traced child has trapped */
#define CLD_STOPPED	5	/* child has stopped */
#define CLD_CONTINUED	6	/* stopped child has continued */
#define NSIGCHLD	6

/*
 * SIGPOLL (or any other signal without signal specific si_codes) si_codes
 */
#define POLL_IN		1	/* data input available */
#define POLL_OUT	2	/* output buffers available */
#define POLL_MSG	3	/* input message available */
#define POLL_ERR	4	/* i/o error */
#define POLL_PRI	5	/* high priority input available */
#define POLL_HUP	6	/* device disconnected */
#define NSIGPOLL	6

/*
 * SIGSYS si_codes
 */
#define SYS_SECCOMP	1	/* seccomp triggered */
#define NSIGSYS		1

/*
 * sigevent definitions
 *
 * It seems likely that SIGEV_THREAD will have to be handled from
 * userspace, libpthread transmuting it to SIGEV_SIGNAL, which the
 * thread manager then catches and does the appropriate nonsense.
 * However, everything is written out here so as to not get lost.
 */
#define SIGEV_SIGNAL	0	/* notify via signal */
#define SIGEV_NONE	1	/* other notification: meaningless */
#define SIGEV_THREAD	2	/* deliver via thread creation */
#define SIGEV_THREAD_ID 4	/* deliver to thread */

/*
 * This works because the alignment is ok on all current architectures
 * but we leave open this being overridden in the future
 */
#ifndef __ARCH_SIGEV_PREAMBLE_SIZE
#define __ARCH_SIGEV_PREAMBLE_SIZE	(sizeof(int) * 2 + sizeof(sigval_t))
#endif

#define SIGEV_MAX_SIZE	64
#define SIGEV_PAD_SIZE	((SIGEV_MAX_SIZE - __ARCH_SIGEV_PREAMBLE_SIZE) \
		/ sizeof(int))

typedef struct sigevent {
	sigval_t sigev_value;
	int sigev_signo;
	int sigev_notify;
	union {
		int _pad[SIGEV_PAD_SIZE];
		 int _tid;

		struct {
			void (*_function)(sigval_t);
			void *_attribute;	/* really pthread_attr_t */
		} _sigev_thread;
	} _sigev_un;
} sigevent_t;

#define sigev_notify_function	_sigev_un._sigev_thread._function
#define sigev_notify_attributes	_sigev_un._sigev_thread._attribute
#define sigev_notify_thread_id	 _sigev_un._tid

#endif /* _ASM_GENERIC_SIGINFO_H */


text:
/*jshint ignore:start*/
require({
    config: {
        'scalejs.statechart-scion': {
            logStatesEnteredAndExited: true
        }
    },
    baseUrl: 'src',
    scalejs: {
        extensions: [
            'scalejs.mvvm',
            'scalejs.statechart-scion',
            'scalejs.functional',
            'scalejs.linq-linqjs',
            'scalejs.ratchet',
            'scalejs.facebook'
        ]
    },
    map: {
        '*': {
            sandbox: 'scalejs.sandbox',
            bindings: 'scalejs.mvvm.bindings',
            views: 'scalejs.mvvm.views'
        }
    },
    paths: {
        almond: '../lib/almond/almond',
        requirejs: '../lib/requirejs/require',
        scalejs: '../lib/scalejs/dist/scalejs.min',
        ratchet: '../lib/ratchet/dist/js/ratchet',
        knockout: '../lib/knockout/dist/knockout',
        'knockout.mapping': '../lib/knockout.mapping/knockout.mapping',
        'scalejs.functional': '../lib/scalejs.functional/dist/scalejs.functional.min',
        text: '../lib/text/text',
        'scalejs.statechart-scion': '../lib/scalejs.statechart-scion/dist/scalejs.statechart-scion.min',
        'scalejs.linq-linqjs': '../lib/scalejs.linq-linqjs/dist/scalejs.linq-linqjs.min',
        linqjs: '../lib/linqjs/linq',
        'scion-ng': '../lib/scion-ng/lib/scion',
        'scalejs.mvvm': '../lib/scalejs.mvvm/dist/scalejs.mvvm',
        'scalejs.mvvm.bindings': '../lib/scalejs.mvvm/dist/scalejs.mvvm',
        'scalejs.mvvm.views': '../lib/scalejs.mvvm/dist/scalejs.mvvm',
        'scalejs.ratchet': 'ext/scalejs.ratchet',
        'font-awesome': '../lib/font-awesome/fonts/*',
        jquery: '../lib/jquery/dist/jquery',
        facebook: '//connect.facebook.net/en_US/sdk/debug',
        'scalejs.facebook': 'ext/scalejs.facebook',
        moment: '../lib/moment/moment',
        package: '../lib/package/dist/scalejs.mvvm.min',
        hello: '../lib/hello/dist/hello.all',
        'scalejs.routing-historyjs': '../lib/scalejs.routing-historyjs/dist/scalejs.routing-historyjs.min'
    },
    shim: {
        facebook: {
            exports: 'FB'
        }
    },
    packages: [

    ]
});
/*jshint ignore:end*/


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://sse.uni-hildesheim.de/instrumentation" exclusive="true">
  <namespace name="test">
    <module name="InstanceIdentifierTest">
      <monitor/>
      <behavior signature="execute()">
        <monitor id="exec" instanceIdentifierKind="IDENTITY_HASHCODE"/>
      </behavior>
      <behavior signature="main(java.lang.String[])">
        <startSystem/>
        <endSystem invoke="asserts"/>
      </behavior>
    </module>
  </namespace>
</configuration>


text:
package de.etecture.opensource.dynamicresources.core.executors;

import de.etecture.opensource.dynamicresources.api.ExecutionContext;
import de.etecture.opensource.dynamicresources.api.ResourceException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.spi.AnnotatedParameter;
import javax.inject.Inject;

/**
 * executes an {@link ExecutionMethod}
 *
 * @author rhk
 * @version
 * @since
 */
public class ExecutionMethodResourceMethodExecutor<T> extends AbstractResourceMethodExecutor {

    private final ExecutionMethod<T> method;
    private T bean;
    @Inject
    Instance<Object> instances;

    ExecutionMethodResourceMethodExecutor() {
        throw new IllegalStateException("do not create directly!");
    }

    public ExecutionMethodResourceMethodExecutor(ExecutionMethod<T> method) {
        this.method = method;
    }

    @PostConstruct
    public void setupBean() {
        // get the type of the bean
        Class<T> beanType = method.getDeclaringType().getJavaClass();
        // select the bean
        bean = instances.select(beanType).get();
    }

    @Override
    protected <R, B> R getEntity(
            ExecutionContext<R, B> context) throws Exception {
        // assemble the arguments...
        Object[] arguments = new Object[method.getParameters().size()];
        if (method.getExecutionContextArgument() != null) {
            arguments[method.getExecutionContextArgument().getPosition()] =
                    context;
        }
        if (method.getBodyArgument() != null) {
            arguments[method.getBodyArgument().getPosition()] = context
                    .getBody();
        }
        for (Map.Entry<AnnotatedParameter<T>, String> e : method
                .getParameterArguments().entrySet()) {
            arguments[e.getKey().getPosition()] = context.getParameterValue(e
                    .getValue());
        }
        // invoke the method now.
        if (!method.getJavaMember().isAccessible()) {
            method.getJavaMember().setAccessible(true);
        }
        try {
            Object result = method.getJavaMember().invoke(bean, arguments);
            return (R) result;
        } catch (IllegalAccessException | IllegalArgumentException |
                InvocationTargetException ex) {
            throw new ResourceException("cannot call the execution method!", ex);
        }
    }
}


text:
ACE_RCSID(SOCK_SAP, CPP_inserver, "$Id: CPP-memserver.cpp 80826 2008-03-04 14:51:23Z wotte $")

static int
run_event_loop (u_short port)
{
  // Create the acceptors.
  ACE_MEM_Acceptor acceptor;

  ACE_MEM_Addr server_addr (port);

  // Create acceptors, reuse the address.
  if (acceptor.open (server_addr, 1) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "%p\n",
                       "open"),
                      1);
  else if (acceptor.get_local_addr (server_addr) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "%p\n",
                       "get_local_addr"),
                      1);

  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t) starting server at port %d\n",
              server_addr.get_port_number ()));

  // Keep these objects out here to prevent excessive constructor
  // calls within the loop.
  ACE_MEM_Stream new_stream;

  // blocking wait on accept.
  if (acceptor.accept (new_stream) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "%p\n",
                       "accept"),
                      -1);

  char buf[MAXPATHLEN];
  int len = 0;
  while ((len = new_stream.recv (buf, MAXPATHLEN)) != -1)
    {
      ACE_DEBUG ((LM_DEBUG, "%s\n", buf));
      new_stream.send (buf, len);
    }

  return new_stream.fini ();
}

int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  u_short port = ACE_DEFAULT_SERVER_PORT;

  if (argc > 1)
    port = ACE_OS::atoi (argv[1]);

  return run_event_loop (port);
}