text:
var cheerio = require('cheerio'),
	fs = require('fs'),
	path = require('path'),
	marked = require('marked');

marked.setOptions({

});

var idRegex = /[^\w]/g;

var setExtHeader1Regex = /^(.+)[ \t]*\r?\n=+[ \t]*(?:\r?\n)+/gm;
var setExtHeader2Regex = /^(.+)[ \t]*\r?\n-+[ \t]*(?:\r?\n)+/gm;

/*    /
	^(\#{1,6})      // $1 = string of #'s
		[ \t]*
	(.+?)           // $2 = Header text
	[ \t]*
	\#*             // optional closing #'s (not counted)
	\n+
	/gm */
var atxHeaderRegex = /^(\#{1,6})[ \t]*(.+?)[ \t]*\#*(?:\r?\n)+/gm;
var markdownHeaders = [
	'',
	"#",
	"##",
	"###",
	"####",
	"#####",
	"######"
];

var allHtmlHeaders = 'h1, h2, h3, h4, h5, h6';

var buildHeader = function(name, depth) {
	if (depth < 1) {
		return '
' + name + '
';
	} else {
		return '<h' + (depth) + '>' + name + '</h' + depth + '>';
	}
};

var appendTocElement = function(toc, link) {
	var element = cheerio.load('

');
	element('li')
		.addClass('docmd-toc-item')
		.append(link);
	toc.root().append(element.html());
};

var buildSimpleTocLink = function(name, anchorId) {
	return cheerio.load('')('a')
		.attr('href', '#' + anchorId)
		.addClass("docmd-toc-link")
		.text(name);
};

var adjustMarkdownHeaders = function(markdown, depth) {
	markdown = markdown.replace(atxHeaderRegex, function (wholeMatch, m1, m2) {
		var currentLevel = m1.length;
		var newLevel = depth + currentLevel - 1;
		if (newLevel > 6) {
			newLevel = 6;
		}
		return '\n' + markdownHeaders[newLevel] + ' ' + m2 + '\n\n';
		}
	);

	markdown = markdown.replace(setExtHeader1Regex, function(wholeMatch, m1) {
		return '\n' + markdownHeaders[depth] + ' ' + m1 + '\n\n';
	});

	markdown = markdown.replace(setExtHeader2Regex, function(wholeMatch, m1) {
		var newLevel = depth + 1;
		if (newLevel > 6) {
			newLevel = 6;
		}
		return '\n' + markdownHeaders[newLevel] + ' ' + m1 + '\n\n';
	});
	return markdown;
};

var buildAndLinkHtml = function(options, properties, depth) {
	if (depth > 4) {
		//TODO determine if this is the correct threshold
		depth = 4;
	}
	var tocSections = cheerio.load('');
	var name,
		header,
		$,
		markdown;
	if (properties["name"]) {
		name = properties["name"];
		$ = cheerio.load(buildHeader(name, depth));
		markdown = depth > 0 ? markdownHeaders[depth] + name + '\n\n' : "" ;
		header = $(allHtmlHeaders).first();
	} else if (properties["file"]) {
		var sectionFile = path.join(options['docDir'], properties["file"]);
		markdown = fs.readFileSync(sectionFile, {"encoding": "utf-8"});
		if (options['normalizeHeaders']) {
			markdown = adjustMarkdownHeaders(markdown, depth);
		}
		var markdownHtml = marked(markdown);
		$ = cheerio.load('');
		$.root().append(markdownHtml);
		$(allHtmlHeaders).each(function() {
			var header = $(this);
			header.attr('id', header.text().replace(idRegex, ''));
		});
		$('a').each((i, el) => $(el).attr('target') && $(el).attr('rel', 'noopener noreferrer'))
		header = $(allHtmlHeaders).first();
		name = header.text();
	} else  {
		grunt.fail.warn("A toc list contains an element that is neither a name nor a file");
	}
	var anchorId = properties["referenceId"];
	if (!anchorId) {
		anchorId = buildId(name);
	}
	header.attr('id', anchorId);
	appendTocElement(tocSections, buildSimpleTocLink(name, anchorId));

	if (properties["toc"]) {
		properties["toc"].forEach(function(section) {
			var sectionContent = buildAndLinkHtml(options, section, depth + 1);

			appendTocElement(tocSections, sectionContent["toc"]);
			$.root().append(sectionContent['main']);
			markdown = markdown + '\n\n' + sectionContent['markdown'];
		});
	}

	var toc = cheerio.load('');
	var tocContents = cheerio.load('
');
	tocContents('ul').addClass('docmd-toc-list')
		.append(tocSections.html());
	toc.root().append(tocContents.html());

	return {
		"main": $.root().html(),
		"toc": toc.html(),
		"markdown": markdown
	};
};

var buildGuideLinks = function(guides) {
	var $ = cheerio.load('
');
	guides.forEach(function(guide) {
		var element = cheerio.load('');
		var icon;
		var fileName = guide.overrideGuideFile || guide.link
		element('a')
			.addClass("all-guides-list-item list-group-item")
			.attr('href', fileName + '.html');
		element('span')
			.addClass('docmd-guide-name')
			.text(guide.text);

		if (guide.propertiesFile.guideIcon) {
			icon = cheerio.load('');
			icon('img')
				.addClass('docmd-guide-icon')
				.attr('src', guide.propertiesFile.guideIcon);

		} else {
			icon = cheerio.load('');
			icon('span')
				.addClass('glyphicon glyphicon-book')
		}
		element('a')
			.prepend(icon.root().html());
		$('div').append(element.root().html())
	});
	return $.root().html();
};

var highlightCurrentGuide = function(guideLinksHtml, guideLink) {
	var $ = cheerio.load(guideLinksHtml);
	$('a').each(function() {
		var link = $(this);
		if (link.attr('href') === guideLink) {
			link.addClass('docmd-selected-guide');
		}
	});
	return $.root().html();
};

var buildId = function(name) {
	return name.replace(idRegex, '');
};

module.exports = {
	buildAndLinkHtml: buildAndLinkHtml,
	buildGuideLinks: buildGuideLinks,
	highlightCurrentGuide: highlightCurrentGuide,
	buildId: buildId
};


text:
<?php

/**
 * Manage locks using a lock daemon server.
 *
 * Version of LockManager based on using lock daemon servers.
 * This is meant for multi-wiki systems that may share files.
 * All locks are non-blocking, which avoids deadlocks.
 *
 * All lock requests for a resource, identified by a hash string, will map
 * to one bucket. Each bucket maps to one or several peer servers, each
 * running LockServerDaemon.php, listening on a designated TCP port.
 * A majority of peers must agree for a lock to be acquired.
 *
 * @ingroup LockManager
 * @since 1.19
 */
class LSLockManager extends LockManager {
	/** @var Array Mapping of lock types to the type actually used */
	protected $lockTypeMap = array(
		self::LOCK_SH => self::LOCK_SH,
		self::LOCK_UW => self::LOCK_SH,
		self::LOCK_EX => self::LOCK_EX
	);

	/** @var Array Map of server names to server config */
	protected $lockServers; // (server name => server config array)
	/** @var Array Map of bucket indexes to peer server lists */
	protected $srvsByBucket; // (bucket index => (lsrv1, lsrv2, ...))

	/** @var Array Map Server connections (server name => resource) */
	protected $conns = array();

	protected $connTimeout; // float number of seconds
	protected $session = ''; // random SHA-1 string

	/**
	 * Construct a new instance from configuration.
	 *
	 * $config paramaters include:
	 *     'lockServers'  : Associative array of server names to configuration.
	 *                      Configuration is an associative array that includes:
	 *                      'host'    - IP address/hostname
	 *                      'port'    - TCP port
	 *                      'authKey' - Secret string the lock server uses
	 *     'srvsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
	 *                      each having an odd-numbered list of server names (peers) as values.
	 *     'connTimeout'  : Lock server connection attempt timeout. [optional]
	 *
	 * @param Array $config
	 */
	public function __construct( array $config ) {
		$this->lockServers = $config['lockServers'];
		// Sanitize srvsByBucket config to prevent PHP errors
		$this->srvsByBucket = array_filter( $config['srvsByBucket'], 'is_array' );
		$this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive

		if ( isset( $config['connTimeout'] ) ) {
			$this->connTimeout = $config['connTimeout'];
		} else {
			$this->connTimeout = 3; // use some sane amount
		}

		$this->session = '';
		for ( $i = 0; $i < 5; $i++ ) {
			$this->session .= mt_rand( 0, 2147483647 );
		}
		$this->session = wfBaseConvert( sha1( $this->session ), 16, 36, 31 );
	}

	protected function doLock( array $paths, $type ) {
		$status = Status::newGood();

		$pathsToLock = array();
		// Get locks that need to be acquired (buckets => locks)...
		foreach ( $paths as $path ) {
			if ( isset( $this->locksHeld[$path][$type] ) ) {
				++$this->locksHeld[$path][$type];
			} elseif ( isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
				$this->locksHeld[$path][$type] = 1;
			} else {
				$bucket = $this->getBucketFromKey( $path );
				$pathsToLock[$bucket][] = $path;
			}
		}

		$lockedPaths = array(); // files locked in this attempt
		// Attempt to acquire these locks...
		foreach ( $pathsToLock as $bucket => $paths ) {
			// Try to acquire the locks for this bucket
			$res = $this->doLockingRequestAll( $bucket, $paths, $type );
			if ( $res === 'cantacquire' ) {
				// Resources already locked by another process.
				// Abort and unlock everything we just locked.
				foreach ( $paths as $path ) {
					$status->fatal( 'lockmanager-fail-acquirelock', $path );
				}
				$status->merge( $this->doUnlock( $lockedPaths, $type ) );
				return $status;
			} elseif ( $res !== true ) {
				// Couldn't contact any servers for this bucket.
				// Abort and unlock everything we just locked.
				foreach ( $paths as $path ) {
					$status->fatal( 'lockmanager-fail-acquirelock', $path );
				}
				$status->merge( $this->doUnlock( $lockedPaths, $type ) );
				return $status;
			}
			// Record these locks as active
			foreach ( $paths as $path ) {
				$this->locksHeld[$path][$type] = 1; // locked
			}
			// Keep track of what locks were made in this attempt
			$lockedPaths = array_merge( $lockedPaths, $paths );
		}

		return $status;
	}

	protected function doUnlock( array $paths, $type ) {
		$status = Status::newGood();

		foreach ( $paths as $path ) {
			if ( !isset( $this->locksHeld[$path] ) ) {
				$status->warning( 'lockmanager-notlocked', $path );
			} elseif ( !isset( $this->locksHeld[$path][$type] ) ) {
				$status->warning( 'lockmanager-notlocked', $path );
			} else {
				--$this->locksHeld[$path][$type];
				if ( $this->locksHeld[$path][$type] <= 0 ) {
					unset( $this->locksHeld[$path][$type] );
				}
				if ( !count( $this->locksHeld[$path] ) ) {
					unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
				}
			}
		}

		// Reference count the locks held and release locks when zero
		if ( !count( $this->locksHeld ) ) {
			$status->merge( $this->releaseLocks() );
		}

		return $status;
	}

	/**
	 * Get a connection to a lock server and acquire locks on $paths
	 *
	 * @param $lockSrv string
	 * @param $paths Array
	 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
	 * @return bool Resources able to be locked
	 */
	protected function doLockingRequest( $lockSrv, array $paths, $type ) {
		if ( $type == self::LOCK_SH ) { // reader locks
			$type = 'SH';
		} elseif ( $type == self::LOCK_EX ) { // writer locks
			$type = 'EX';
		} else {
			return true; // ok...
		}

		// Send out the command and get the response...
		$keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
		$response = $this->sendCommand( $lockSrv, 'ACQUIRE', $type, $keys );

		return ( $response === 'ACQUIRED' );
	}

	/**
	 * Send a command and get back the response
	 *
	 * @param $lockSrv string
	 * @param $action string
	 * @param $type string
	 * @param $values Array
	 * @return string|false
	 */
	protected function sendCommand( $lockSrv, $action, $type, $values ) {
		$conn = $this->getConnection( $lockSrv );
		if ( !$conn ) {
			return false; // no connection
		}
		$authKey = $this->lockServers[$lockSrv]['authKey'];
		// Build of the command as a flat string...
		$values = implode( '|', $values );
		$key = sha1( $this->session . $action . $type . $values . $authKey );
		// Send out the command...
		if ( fwrite( $conn, "{$this->session}:$key:$action:$type:$values\n" ) === false ) {
			return false;
		}
		// Get the response...
		$response = fgets( $conn );
		if ( $response === false ) {
			return false;
		}
		return trim( $response );
	}

	/**
	 * Attempt to acquire locks with the peers for a bucket
	 *
	 * @param $bucket integer
	 * @param $paths Array List of resource keys to lock
	 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
	 * @return bool|string One of (true, 'cantacquire', 'srverrors')
	 */
	protected function doLockingRequestAll( $bucket, array $paths, $type ) {
		$yesVotes = 0; // locks made on trustable servers
		$votesLeft = count( $this->srvsByBucket[$bucket] ); // remaining peers
		$quorum = floor( $votesLeft/2 + 1 ); // simple majority
		// Get votes for each peer, in order, until we have enough...
		foreach ( $this->srvsByBucket[$bucket] as $lockSrv ) {
			// Attempt to acquire the lock on this peer
			if ( !$this->doLockingRequest( $lockSrv, $paths, $type ) ) {
				return 'cantacquire'; // vetoed; resource locked
			}
			++$yesVotes; // success for this peer
			if ( $yesVotes >= $quorum ) {
				return true; // lock obtained
			}
			--$votesLeft;
			$votesNeeded = $quorum - $yesVotes;
			if ( $votesNeeded > $votesLeft ) {
				// In "trust cache" mode we don't have to meet the quorum
				break; // short-circuit
			}
		}
		// At this point, we must not have meet the quorum
		return 'srverrors'; // not enough votes to ensure correctness
	}

	/**
	 * Get (or reuse) a connection to a lock server
	 *
	 * @param $lockSrv string
	 * @return resource
	 */
	protected function getConnection( $lockSrv ) {
		if ( !isset( $this->conns[$lockSrv] ) ) {
			$cfg = $this->lockServers[$lockSrv];
			wfSuppressWarnings();
			$errno = $errstr = '';
			$conn = fsockopen( $cfg['host'], $cfg['port'], $errno, $errstr, $this->connTimeout );
			wfRestoreWarnings();
			if ( $conn === false ) {
				return null;
			}
			$sec = floor( $this->connTimeout );
			$usec = floor( ( $this->connTimeout - floor( $this->connTimeout ) ) * 1e6 );
			stream_set_timeout( $conn, $sec, $usec );
			$this->conns[$lockSrv] = $conn;
		}
		return $this->conns[$lockSrv];
	}

	/**
	 * Release all locks that this session is holding
	 *
	 * @return Status
	 */
	protected function releaseLocks() {
		$status = Status::newGood();
		foreach ( $this->conns as $lockSrv => $conn ) {
			$response = $this->sendCommand( $lockSrv, 'RELEASE_ALL', '', array() );
			if ( $response !== 'RELEASED_ALL' ) {
				$status->fatal( 'lockmanager-fail-svr-release', $lockSrv );
			}
		}
		return $status;
	}

	/**
	 * Get the bucket for resource path.
	 * This should avoid throwing any exceptions.
	 *
	 * @param $path string
	 * @return integer
	 */
	protected function getBucketFromKey( $path ) {
		$prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
		return intval( base_convert( $prefix, 16, 10 ) ) % count( $this->srvsByBucket );
	}

	/**
	 * Make sure remaining locks get cleared for sanity
	 */
	function __destruct() {
		$this->releaseLocks();
		foreach ( $this->conns as $conn ) {
			fclose( $conn );
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package uk.gov.hmrc.ct.version.calculations

import org.joda.time.LocalDate
import org.scalatest.prop.TableDrivenPropertyChecks._
import org.scalatest.{Matchers, WordSpec}
import uk.gov.hmrc.ct._
import uk.gov.hmrc.ct.accounts._
import uk.gov.hmrc.ct.accounts.retriever.AccountsBoxRetriever
import uk.gov.hmrc.ct.accounts.stubs.StubbedAccountsBoxRetriever
import uk.gov.hmrc.ct.box.CtValue
import uk.gov.hmrc.ct.box.retriever.FilingAttributesBoxValueRetriever
import uk.gov.hmrc.ct.box.stubs.StubbedFilingAttributesBoxValueRetriever
import uk.gov.hmrc.ct.computations._
import uk.gov.hmrc.ct.computations.retriever.ComputationsBoxRetriever
import uk.gov.hmrc.ct.computations.stubs.StubbedComputationsBoxRetriever
import uk.gov.hmrc.ct.version.CoHoAccounts.{CoHoMicroEntityAbridgedAccounts, CoHoMicroEntityAccounts, CoHoStatutoryAbbreviatedAccounts, CoHoStatutoryAccounts}
import uk.gov.hmrc.ct.version.CoHoVersions.AccountsVersion1
import uk.gov.hmrc.ct.version.HmrcReturns._
import uk.gov.hmrc.ct.version.HmrcVersions._
import uk.gov.hmrc.ct.version.{Return, Version}

class ReturnVersionsCalculatorSpec extends WordSpec with Matchers {

  "Return Versions Calculator" should {
    "for CoHo only filing" when {
      "return accounts version for full Micro entity accounts" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(CoHoMicroEntityAccounts, AccountsVersion1))
        calculateReturnVersions(coHoFiling = CompaniesHouseFiling(true),
                                microEntityFiling = MicroEntityFiling(true)) shouldBe expectedResult
      }

      "return accounts version for abridged Micro entity accounts" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(CoHoMicroEntityAbridgedAccounts, AccountsVersion1))
        calculateReturnVersions(coHoFiling = CompaniesHouseFiling(true),
                                microEntityFiling = MicroEntityFiling(true),
                                abridgedFiling = AbridgedFiling(true)) shouldBe expectedResult
      }

      "return accounts version for full statutory accounts" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(CoHoStatutoryAccounts, AccountsVersion1))
        calculateReturnVersions(coHoFiling = CompaniesHouseFiling(true),
                                statutoryAccountsFiling = StatutoryAccountsFiling(true)) shouldBe expectedResult
      }

      "return accounts version for abbreviated statutory accounts" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(CoHoStatutoryAbbreviatedAccounts, AccountsVersion1))
        calculateReturnVersions(coHoFiling = CompaniesHouseFiling(true),
                                statutoryAccountsFiling = StatutoryAccountsFiling(true),
                                abbreviatedAccountsFiling = AbbreviatedAccountsFiling(true)) shouldBe expectedResult
      }

      "match successfully for AccountsBoxRetriever" in {
        val expectedResult = Set(Return(CoHoMicroEntityAccounts, AccountsVersion1))

        val accountsBoxRetriever = new StubbedAccountsBoxRetriever with StubbedFilingAttributesBoxValueRetriever {

          override def retrieveAbbreviatedAccountsFiling(): AbbreviatedAccountsFiling = AbbreviatedAccountsFiling(false)
          override def retrieveStatutoryAccountsFiling(): StatutoryAccountsFiling = StatutoryAccountsFiling(false)
          override def retrieveMicroEntityFiling(): MicroEntityFiling = MicroEntityFiling(true)
          override def retrieveAbridgedFiling(): AbridgedFiling = AbridgedFiling(false)
          override def retrieveCompaniesHouseFiling(): CompaniesHouseFiling = CompaniesHouseFiling(true)
          override def retrieveHMRCFiling(): HMRCFiling = HMRCFiling(false)
        }

        ReturnVersionsCalculator.doCalculation(accountsBoxRetriever) shouldBe expectedResult
      }

      "match successfully for ComputationsBoxRetriever" in {
        val expectedResult = Set(Return(CT600j, CT600Version2),
                                 Return(HmrcMicroEntityAccounts, AccountsVersion1),
                                 Return(CT600a, CT600Version2),
                                 Return(CoHoMicroEntityAccounts, AccountsVersion1),
                                 Return(Computations, ComputationsCT20141001),
                                 Return(CT600, CT600Version2))

        ReturnVersionsCalculator.doCalculation(new ComputationsBoxRetrieverForTest with StubbedAccountsBoxRetriever {

        }) shouldBe expectedResult
      }
    }

    "for HMRC only filing" when {
      "return HMRC version for full Micro entity accounts for AP starting before 2015-04-01" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcMicroEntityAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version2),
                                 Return(CT600a, CT600Version2),
                                 Return(CT600j, CT600Version2),
                                 Return(Computations, ComputationsCT20141001))

        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-03-31"))),
                                cp2 = Some(CP2(LocalDate.parse("2015-12-31"))),
                                hmrcFiling = HMRCFiling(true),
                                microEntityFiling = MicroEntityFiling(true)) shouldBe expectedResult
      }
      "return HMRC version for full Micro entity accounts for AP starting after 2015-03-31" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcMicroEntityAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version3),
                                 Return(CT600a, CT600Version3),
                                 Return(CT600j, CT600Version3),
                                 Return(Computations, ComputationsCT20150201))

        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-04-01"))),
                                cp2 = Some(CP2(LocalDate.parse("2016-03-31"))),
                                hmrcFiling = HMRCFiling(true),
                                microEntityFiling = MicroEntityFiling(true)) shouldBe expectedResult
      }

      "return HMRC version for abridged Micro entity accounts for AP starting before 2015-04-01" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcMicroEntityAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version2),
                                 Return(CT600a, CT600Version2),
                                 Return(CT600j, CT600Version2),
                                 Return(Computations, ComputationsCT20141001))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-03-31"))),
                                cp2 = Some(CP2(LocalDate.parse("2015-12-31"))),
                                hmrcFiling = HMRCFiling(true),
                                microEntityFiling = MicroEntityFiling(true),
                                abridgedFiling = AbridgedFiling(true)) shouldBe expectedResult
      }

      "return HMRC version for abridged Micro entity accounts for AP starting after 2015-03-31" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcMicroEntityAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version3),
                                 Return(CT600a, CT600Version3),
                                 Return(CT600j, CT600Version3),
                                 Return(Computations, ComputationsCT20150201))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-04-01"))),
                                cp2 = Some(CP2(LocalDate.parse("2016-03-31"))),
                                hmrcFiling = HMRCFiling(true),
                                microEntityFiling = MicroEntityFiling(true),
                                abridgedFiling = AbridgedFiling(true)) shouldBe expectedResult
      }

      "return HMRC version for full statutory accounts for AP starting before 2015-04-01" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcStatutoryAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version2),
                                 Return(CT600a, CT600Version2),
                                 Return(CT600j, CT600Version2),
                                 Return(Computations, ComputationsCT20141001))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-03-31"))),
                                cp2 = Some(CP2(LocalDate.parse("2015-12-31"))),
                                hmrcFiling = HMRCFiling(true),
                                statutoryAccountsFiling = StatutoryAccountsFiling(true)) shouldBe expectedResult
      }

      "return HMRC version for full statutory accounts for AP starting after 2015-03-31" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcStatutoryAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version3),
                                 Return(CT600a, CT600Version3),
                                 Return(CT600j, CT600Version3),
                                 Return(Computations, ComputationsCT20150201))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-04-01"))),
                                cp2 = Some(CP2(LocalDate.parse("2016-03-31"))),
                                hmrcFiling = HMRCFiling(true),
                                statutoryAccountsFiling = StatutoryAccountsFiling(true)) shouldBe expectedResult
      }

      "return HMRC versions for abbreviated statutory accounts for AP starting before 2015-04-01" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcStatutoryAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version2),
                                 Return(CT600a, CT600Version2),
                                 Return(CT600j, CT600Version2),
                                 Return(Computations, ComputationsCT20141001))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-03-31"))),
                                cp2 = Some(CP2(LocalDate.parse("2015-12-31"))),
                                hmrcFiling = HMRCFiling(true),
                                statutoryAccountsFiling = StatutoryAccountsFiling(true),
                                abbreviatedAccountsFiling = AbbreviatedAccountsFiling(true)) shouldBe expectedResult
      }

      "return HMRC versions for abbreviated statutory accounts for AP starting after 2015-03-31" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcStatutoryAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version3),
                                 Return(CT600a, CT600Version3),
                                 Return(CT600j, CT600Version3),
                                 Return(Computations, ComputationsCT20150201))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-04-01"))),
                                cp2 = Some(CP2(LocalDate.parse("2016-03-31"))),
                                hmrcFiling = HMRCFiling(true),
                                statutoryAccountsFiling = StatutoryAccountsFiling(true),
                                abbreviatedAccountsFiling = AbbreviatedAccountsFiling(true)) shouldBe expectedResult
      }

      "return HMRC versions for uploaded accounts for AP starting before 2015-04-01" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcUploadedAccounts, UploadedAccounts),
                                 Return(CT600, CT600Version2),
                                 Return(CT600a, CT600Version2),
                                 Return(CT600j, CT600Version2),
                                 Return(Computations, ComputationsCT20141001))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-03-31"))),
                                cp2 = Some(CP2(LocalDate.parse("2015-12-31"))),
                                hmrcFiling = HMRCFiling(true),
                                microEntityFiling = MicroEntityFiling(false),
                                abridgedFiling = AbridgedFiling(false),
                                statutoryAccountsFiling = StatutoryAccountsFiling(false),
                                abbreviatedAccountsFiling = AbbreviatedAccountsFiling(false)) shouldBe expectedResult
      }

      "return HMRC versions for uploaded accounts for AP starting after 2015-03-31" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcUploadedAccounts, UploadedAccounts),
                                 Return(CT600, CT600Version3),
                                 Return(CT600a, CT600Version3),
                                 Return(CT600j, CT600Version3),
                                 Return(Computations, ComputationsCT20150201))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-04-01"))),
                                cp2 = Some(CP2(LocalDate.parse("2016-03-31"))),
                                hmrcFiling = HMRCFiling(true),
                                microEntityFiling = MicroEntityFiling(false),
                                abridgedFiling = AbridgedFiling(false),
                                statutoryAccountsFiling = StatutoryAccountsFiling(false),
                                abbreviatedAccountsFiling = AbbreviatedAccountsFiling(false)) shouldBe expectedResult
      }
    }

    val computationsVersions = org.scalatest.prop.Tables.Table (

      ("startDate", "endDate", "compsVersion"),
      ("2012-04-02", "2013-03-31", ComputationsCT20130721),
      ("2012-04-01", "2013-03-31", ComputationsCT20130721),
      ("2012-04-01", "2012-04-01", ComputationsCT20130721),
      ("2010-04-01", "2011-03-31", ComputationsCT20130721),
      ("2008-04-01", "2008-04-01", ComputationsCT20130721),

      ("2015-03-31", "2016-03-30", ComputationsCT20141001),
      ("2015-01-01", "2015-12-31", ComputationsCT20141001),
      ("2012-04-02", "2013-04-01", ComputationsCT20141001),

      ("2016-01-01", "2016-12-31", ComputationsCT20150201),
      ("2015-04-01", "2016-03-31", ComputationsCT20150201)
    )

    "for any HMRC filing" when {
      "return Computations version" in new ReturnVersionsCalculator {
        forAll(computationsVersions) {
          (start: String, end: String, version: Version) => {
            val versions = calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse(start))),
                                               cp2 = Some(CP2(LocalDate.parse(end))),
                                               hmrcFiling = HMRCFiling(true))
            versions.find( v => v.submission == Computations).get.version shouldBe version
          }
        }
      }
    }

    "for Joint filing" when {
      "return versions for full Micro entity accounts for AP starting before 2015-04-01" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcMicroEntityAccounts, AccountsVersion1),
                                 Return(CoHoMicroEntityAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version2),
                                 Return(CT600a, CT600Version2),
                                 Return(CT600j, CT600Version2),
                                 Return(Computations, ComputationsCT20141001))

        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-03-31"))),
                                cp2 = Some(CP2(LocalDate.parse("2015-12-31"))),
                                hmrcFiling = HMRCFiling(true),
                                coHoFiling = CompaniesHouseFiling(true),
                                microEntityFiling = MicroEntityFiling(true)) shouldBe expectedResult
      }
      "return versions for full Micro entity accounts for AP starting after 2015-03-31" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcMicroEntityAccounts, AccountsVersion1),
                                 Return(CoHoMicroEntityAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version3),
                                 Return(CT600a, CT600Version3),
                                 Return(CT600j, CT600Version3),
                                 Return(Computations, ComputationsCT20150201))

        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-04-01"))),
                                cp2 = Some(CP2(LocalDate.parse("2016-03-31"))),
                                hmrcFiling = HMRCFiling(true),
                                coHoFiling = CompaniesHouseFiling(true),
                                microEntityFiling = MicroEntityFiling(true)) shouldBe expectedResult
      }

      "return versions for abridged Micro entity accounts for AP starting before 2015-04-01" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcMicroEntityAccounts, AccountsVersion1),
                                 Return(CoHoMicroEntityAbridgedAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version2),
                                 Return(CT600a, CT600Version2),
                                 Return(CT600j, CT600Version2),
                                 Return(Computations, ComputationsCT20141001))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-03-31"))),
                                cp2 = Some(CP2(LocalDate.parse("2015-12-31"))),
                                hmrcFiling = HMRCFiling(true),
                                coHoFiling = CompaniesHouseFiling(true),
                                microEntityFiling = MicroEntityFiling(true),
                                abridgedFiling = AbridgedFiling(true)) shouldBe expectedResult
      }

      "return HMRC version for abridged Micro entity accounts for AP starting after 2015-03-31" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcMicroEntityAccounts, AccountsVersion1),
                                 Return(CoHoMicroEntityAbridgedAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version3),
                                 Return(CT600a, CT600Version3),
                                 Return(CT600j, CT600Version3),
                                 Return(Computations, ComputationsCT20150201))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-04-01"))),
                                cp2 = Some(CP2(LocalDate.parse("2016-03-31"))),
                                hmrcFiling = HMRCFiling(true),
                                coHoFiling = CompaniesHouseFiling(true),
                                microEntityFiling = MicroEntityFiling(true),
                                abridgedFiling = AbridgedFiling(true)) shouldBe expectedResult
      }

      "return HMRC version for full statutory accounts for AP starting before 2015-04-01" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcStatutoryAccounts, AccountsVersion1),
                                 Return(CoHoStatutoryAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version2),
                                 Return(CT600a, CT600Version2),
                                 Return(CT600j, CT600Version2),
                                 Return(Computations, ComputationsCT20141001))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-03-31"))),
                                cp2 = Some(CP2(LocalDate.parse("2015-12-31"))),
                                hmrcFiling = HMRCFiling(true),
                                coHoFiling = CompaniesHouseFiling(true),
                                statutoryAccountsFiling = StatutoryAccountsFiling(true)) shouldBe expectedResult
      }

      "return HMRC version for full statutory accounts for AP starting after 2015-03-31" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcStatutoryAccounts, AccountsVersion1),
                                 Return(CoHoStatutoryAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version3),
                                 Return(CT600a, CT600Version3),
                                 Return(CT600j, CT600Version3),
                                 Return(Computations, ComputationsCT20150201))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-04-01"))),
                                cp2 = Some(CP2(LocalDate.parse("2016-03-31"))),
                                hmrcFiling = HMRCFiling(true),
                                coHoFiling = CompaniesHouseFiling(true),
                                statutoryAccountsFiling = StatutoryAccountsFiling(true)) shouldBe expectedResult
      }

      "return HMRC version for abbreviated statutory accounts for AP starting before 2015-04-01" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcStatutoryAccounts, AccountsVersion1),
                                 Return(CoHoStatutoryAbbreviatedAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version2),
                                 Return(CT600a, CT600Version2),
                                 Return(CT600j, CT600Version2),
                                 Return(Computations, ComputationsCT20141001))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-03-31"))),
                                cp2 = Some(CP2(LocalDate.parse("2015-12-31"))),
                                hmrcFiling = HMRCFiling(true),
                                coHoFiling = CompaniesHouseFiling(true),
                                statutoryAccountsFiling = StatutoryAccountsFiling(true),
                                abbreviatedAccountsFiling = AbbreviatedAccountsFiling(true)) shouldBe expectedResult
      }

      "return HMRC version for abbreviated statutory accounts for AP starting after 2015-03-31" in new ReturnVersionsCalculator {
        val expectedResult = Set(Return(HmrcStatutoryAccounts, AccountsVersion1),
                                 Return(CoHoStatutoryAbbreviatedAccounts, AccountsVersion1),
                                 Return(CT600, CT600Version3),
                                 Return(CT600a, CT600Version3),
                                 Return(CT600j, CT600Version3),
                                 Return(Computations, ComputationsCT20150201))
        calculateReturnVersions(cp1 = Some(CP1(LocalDate.parse("2015-04-01"))),
                                cp2 = Some(CP2(LocalDate.parse("2016-03-31"))),
                                hmrcFiling = HMRCFiling(true),
                                coHoFiling = CompaniesHouseFiling(true),
                                statutoryAccountsFiling = StatutoryAccountsFiling(true),
                                abbreviatedAccountsFiling = AbbreviatedAccountsFiling(true)) shouldBe expectedResult
      }
    }
  }
}

class ComputationsBoxRetrieverForTest extends StubbedComputationsBoxRetriever with StubbedFilingAttributesBoxValueRetriever {

  self: AccountsBoxRetriever =>

  override def retrieveCP1(): CP1 = CP1(LocalDate.parse("2015-03-31"))

  override def retrieveCP2(): CP2 = CP2(LocalDate.parse("2015-12-31"))

  override def retrieveAbbreviatedAccountsFiling(): AbbreviatedAccountsFiling = AbbreviatedAccountsFiling(false)

  override def retrieveStatutoryAccountsFiling(): StatutoryAccountsFiling = StatutoryAccountsFiling(false)

  override def retrieveMicroEntityFiling(): MicroEntityFiling = MicroEntityFiling(true)

  override def retrieveAbridgedFiling(): AbridgedFiling = AbridgedFiling(false)

  override def retrieveCompaniesHouseFiling(): CompaniesHouseFiling = CompaniesHouseFiling(true)

  override def retrieveHMRCFiling(): HMRCFiling = HMRCFiling(true)
}


text:
package org.olat.core.servlets;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.LogFactory;
import org.apache.log4j.LogManager;
import org.olat.core.logging.OLog;
import org.olat.core.logging.Tracing;

/**
 *
 * Initial date: 04.01.2013<br>
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 *
 */
public class OLATContextListener implements ServletContextListener {

	private static final OLog log = Tracing.createLoggerFor(OLATContextListener.class);

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    LogFactory.release(contextClassLoader);

    log.info("*** Destroying OLAT servlet.");
		log.info("*** Shutting down the logging system - do not use logger after this point!");
		LogManager.shutdown();
  }
}


text:
import { Component, OnInit } from '@angular/core';
import { AccType } from './accomodation-type.model';
import { Http, Response } from '@angular/http';
import { HttpAccTypeService } from '../services/http.accType.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-accomodation-type',
  templateUrl: './accomodation-type.component.html',
  styleUrls: ['./accomodation-type.component.css'],
  providers: [HttpAccTypeService]
})
export class AccomodationTypeComponent implements OnInit {

  errorMsg: string;
  accTypeName: string;   //za edit i delete
  accType: AccType;
  accTypes: Object[]; //iz get metode - iz baze
  id: number;

  constructor(private httpAccTypeService: HttpAccTypeService) { }

  getAll() {
    this.httpAccTypeService.getAccTypes().subscribe(
      (at: any) => { this.accTypes = at; console.log(this.accTypes) },
      error => { alert("Unsuccessful fetch operation!"); console.log(error); }
    );
  }

  ngOnInit() {
    this.getAll();
  }

  addAccType(newAccType: any, form: NgForm): void {

    if (!form.valid) {
      return;
    }
    this.httpAccTypeService.postAccType(newAccType).subscribe(
      (at: any) => { this.getAll() },

      (error: any) => {
        this.errorMsg = error.json().Message;
        console.log(error);
      }
    );
    form.reset();
  }

  deleteAccType(): void {
    this.httpAccTypeService.deleteAccType(this.id).subscribe(
      (at: any) => { this.getAll() },
      error => { alert("Unsuccessful delete!"); console.log(error); }
    );
  }

  editAccType(): void {
    this.httpAccTypeService.updateAccType(this.accType).subscribe(
      (at: any) => { this.getAll() },
      (error: any) => {
        this.errorMsg = error.json().Message;
        console.log(error);
      }
    );
  }

  setId(id: number) {
    this.id = id;
  }

  setAccType(accType: AccType) {
    this.accType = accType;
  }

  getById() {
    this.httpAccTypeService.getById(this.id).subscribe(x => this.accType = x[0] as AccType);
  }

}


text:
@implementation PFLogMessage

+(void)logMsg:(NSString *)message {
    NSLog(@"[Log]Message:%@",message);
}
@end


text:
package com.sun.xml.ws.message.stream;

import com.oracle.webservices.api.message.ContentType;
import com.oracle.webservices.api.message.MessageContext;
import com.oracle.webservices.api.message.MessageContextFactory;
import com.sun.xml.ws.api.SOAPVersion;
import com.sun.xml.ws.api.message.Message;
import com.sun.xml.ws.api.message.Packet;
import com.sun.xml.ws.api.message.Packet.State;
import com.sun.xml.ws.api.pipe.Codec;
import com.sun.xml.ws.api.pipe.Codecs;
import com.sun.xml.ws.encoding.MtomCodec;
import com.sun.xml.ws.fault.SOAPFaultBuilder;
import com.sun.xml.ws.util.ByteArrayBuffer;
import junit.framework.TestCase;

import javax.xml.namespace.QName;
import jakarta.xml.soap.AttachmentPart;
import jakarta.xml.soap.MessageFactory;
import jakarta.xml.soap.MimeHeaders;
import jakarta.xml.soap.SOAPMessage;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import jakarta.xml.ws.soap.MTOMFeature;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * StreamMessage test
 *
 * @author Jitendra Kotamraju
 */
public class StreamMessageTest extends TestCase {
    String FAULT_MESSAGE  = "<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'>"+
            "<S:Header>" +
            "<wsa:Action xmlns:wsa='http://www.w3.org/2005/08/addressing'>http://example.com/addNumbers</wsa:Action>" +
            "</S:Header>" +
            "<S:Body><S:Fault>" +
            "<faultCode>S:client</faultCode>" +
            "<faultString>Fault Test</faultString>" +
            "<detail xmlns:ns1='urn:fault'><ns1:entry></ns1:entry></detail>" +
            "</S:Fault></S:Body></S:Envelope>";

    // tests Message#getFirstDetailEntryName()
    public void testFirstDetailEntryName() throws Exception {
        Message msg = useStreamCodec(FAULT_MESSAGE);
        QName exp = new QName("urn:fault", "entry");
        assertEquals(exp, msg.getFirstDetailEntryName());
    }

    private StreamMessage useStreamCodec(String msg) throws IOException {
        Codec codec = Codecs.createSOAPEnvelopeXmlCodec(SOAPVersion.SOAP_11);
        Packet packet = new Packet();
        ByteArrayInputStream in = new ByteArrayInputStream(msg.getBytes());
        codec.decode(in, "text/xml", packet);
        return (StreamMessage) packet.getInternalMessage();
    }

    public void testCopyStreamMessage1() throws IOException {
        String soap11Msg =
"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><Header xmlns='http://schemas.xmlsoap.org/soap/envelope/'> <SubscriptionInfo xmlns='http://ws.strikeiron.com'> <LicenseStatusCode>0</LicenseStatusCode> </SubscriptionInfo> </Header> <soap:Body> <GetCountryCodesResponse xmlns='http://www.strikeiron.com'> <GetCountryCodesResult/></GetCountryCodesResponse></soap:Body></soap:Envelope>";
        Message message = useStreamCodec(soap11Msg);
        message.copy();
    }

    public void testCopyWithSpaces() throws IOException {
        String soap12Msg = "<?xml version='1.0'?><S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'> <S:Header> <m:ut xmlns:m='a'> <u xmlns='' id='a'>user</u> </m:ut> <b> hello </b> </S:Header> <S:Body> <ns2:c xmlns:ns2='local'> <clientName>Test</clientName> <ns2:year>2007</ns2:year> </ns2:c> </S:Body> </S:Envelope>";
        Message message = useStreamCodec(soap12Msg);
        message.copy();
    }

    public void testCopy13() throws IOException {
        String soap13Msg = "<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'><S:Body/></S:Envelope>";
        Message message = useStreamCodec(soap13Msg);
        message.copy();
    }

    public void testCopy14() throws IOException {
        String soap14Msg = "<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'><S:Body> </S:Body></S:Envelope>";
        Message message = useStreamCodec(soap14Msg);
        message.copy();
    }

    public void testCopy15() throws IOException {
        String soap15Msg = "<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'> <S:Body> </S:Body> </S:Envelope>";
        Message message = useStreamCodec(soap15Msg);
        message.copy();
    }

    public void testCopy16() throws IOException {
        String soap16Msg = "<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'> <S:Body> <a> </a><b> </b> <c/> </S:Body> </S:Envelope>";
        Message message = useStreamCodec(soap16Msg);
        message.copy();
    }

    public void testCopy17() throws IOException {
        String soap17Msg = "<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'> <S:Header> <a> </a> <b> </b> </S:Header> <S:Body> <a> </a><b> </b> <c/> </S:Body> </S:Envelope>";
        Message message = useStreamCodec(soap17Msg);
        message.copy();
    }

    /*
     * Test for the following exception. Bug in StreamMessage.copy() code
     * java.lang.IllegalArgumentException: faultCode argument for createFault was passed NULL
     *   at com.sun.xml.messaging.saaj.soap.ver1_1.SOAPFactory1_1Impl.createFault(SOAPFactory1_1Impl.java:87)
     */
    public void testCopy18() throws Exception {
        String soap18Msg =
"<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'>" +
  "<S:Body>" +
    "<S:Fault xmlns:ns4='http://www.w3.org/2003/05/soap-envelope'>" +
      "<faultcode>S:Server</faultcode>" +
      "<faultstring>com.sun.istack.XMLStreamException2</faultstring>" +
    "</S:Fault>" +
  "</S:Body>" +
"</S:Envelope>";
        Message message = useStreamCodec(soap18Msg);
        message.copy();
        SOAPFaultBuilder.create(message).createException(null);
    }

    /*
     * ns4 is declared on Envelope and is used in faultcode. So making sure
     * it is picked up after copy()
     */
    public void testCopy19() throws Exception {
        String soap18Msg =
"<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns4='http://schemas.xmlsoap.org/soap/envelope/'>" +
  "<S:Body>" +
    "<S:Fault>" +
      "<faultcode>ns4:Server</faultcode>" +
      "<faultstring>com.sun.istack.XMLStreamException2</faultstring>" +
    "</S:Fault>" +
  "</S:Body>" +
"</S:Envelope>";
        Message message = useStreamCodec(soap18Msg);
        message.copy();
        SOAPFaultBuilder.create(message).createException(null);
    }

    /*
     * ns4 is declared on Body and is used in faultcode. So making sure
     * it is picked up after copy()
     */
    public void testCopy20() throws Exception {
        String soap18Msg =
"<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/'>" +
  "<S:Body xmlns:ns4='http://schemas.xmlsoap.org/soap/envelope/'>" +
    "<S:Fault>" +
      "<faultcode>ns4:Server</faultcode>" +
      "<faultstring>com.sun.istack.XMLStreamException2</faultstring>" +
    "</S:Fault>" +
  "</S:Body>" +
"</S:Envelope>";
        Message message = useStreamCodec(soap18Msg);
        message.copy();
        SOAPFaultBuilder.create(message).createException(null);
    }

    /*
     * ns4 is declared on Envelope and is used in faultcode. So making sure
     * it is picked up for payload source
     */
    public void testPayloadSource() throws Exception {
        String soap18Msg =
"<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns4='http://schemas.xmlsoap.org/soap/envelope/'>" +
  "<S:Body>" +
    "<S:Fault>" +
      "<faultcode>ns4:Server</faultcode>" +
      "<faultstring>com.sun.istack.XMLStreamException2</faultstring>" +
    "</S:Fault>" +
  "</S:Body>" +
"</S:Envelope>";
        Message message = useStreamCodec(soap18Msg);
        Source source = message.readPayloadAsSource();
        InputStream is = getInputStream(source);
        XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(is);
        xsr.next();
        xsr.next();
        assertEquals("http://schemas.xmlsoap.org/soap/envelope/", xsr.getNamespaceURI("ns4"));
    }

    /*
     * ns4 is declared on Envelope and Body and is used in faultcode.
     * So making sure the correct ns4 is picked up for payload source
     */
    public void testPayloadSource1() throws Exception {
        String soap18Msg =
"<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns4='A'>" +
  "<S:Body xmlns:ns4='http://schemas.xmlsoap.org/soap/envelope/'>" +
    "<S:Fault>" +
      "<faultcode>ns4:Server</faultcode>" +
      "<faultstring>com.sun.istack.XMLStreamException2</faultstring>" +
    "</S:Fault>" +
  "</S:Body>" +
"</S:Envelope>";
        Message message = useStreamCodec(soap18Msg);
        Source source = message.readPayloadAsSource();
        InputStream is = getInputStream(source);
        XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(is);
        xsr.next();
        xsr.next();
        assertEquals("http://schemas.xmlsoap.org/soap/envelope/", xsr.getNamespaceURI("ns4"));
    }

    public void testCData() throws Exception {
        String soap18Msg = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soapenv:Body>" +
    "<echoRequest xmlns=\"http://test.oracle.com/xsd\">" +
      "<arg0>outside cdata <![CDATA[<data>inside cdata</data>]]></arg0>" +
    "</echoRequest>" +
  "</soapenv:Body>" +
"</soapenv:Envelope>";
		Message message = useStreamCodec(soap18Msg);
        Source source = message.readPayloadAsSource();
        InputStream is = getInputStream(source);
        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(is);
        reader.next();
        while (reader.getEventType() == XMLStreamReader.START_ELEMENT) reader.next();
        String text = "";
        //Depending on parser settings, multiple characters events may be reported
        //in small chunks, instead of one event for an entire text node
        while (reader.getEventType() == XMLStreamReader.CHARACTERS) {
            String textTmp = new String(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength());
            reader.next();
            text += textTmp;
        }
        assertEquals("outside cdata <data>inside cdata</data>", text);
    }

/*
    private DOMSource toDOMSource(Source source) throws Exception {
        if (source instanceof DOMSource) {
            return (DOMSource)source;
        }
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        DOMResult result = new DOMResult();
        trans.transform(source, result);
        return new DOMSource(result.getNode());
    }
    */

    private InputStream getInputStream(Source source) throws Exception {
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        ByteArrayBuffer bab = new ByteArrayBuffer();
        StreamResult result = new StreamResult(bab);
        trans.transform(source, result);
        return bab.newInputStream();
    }

    public void testEmptySoapHeader() throws Exception {
		String soap =
				"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>" +
		           "<soap:Header xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'></soap:Header>" +
		  "<soapenv:Body>"+
		  "  <tes:fooOwsmMsgProtection xmlns:tes='http://testOwsm'>"+
		  "   <!--Optional:-->"+
		  "    <arg0>string</arg0>"+
		  "  </tes:fooOwsmMsgProtection>"+
		  "</soapenv:Body>"+
		"</soapenv:Envelope>";
		MessageContextFactory mcf = MessageContextFactory.createFactory();
		MessageContext mc = mcf.createContext(new ByteArrayInputStream(soap.getBytes()), "text/xml");
		String string1 = mc.toString();

		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		mc.writeTo(bo);
		String string2 = new String(bo.toByteArray());
		assertTrue(string1.indexOf("Header") != -1);
		assertTrue(string2.indexOf("Header") != -1);
    }

    public void testWriteMtomToStream() throws Exception {
        // Ensure writing StreamMessage to OutputputStream preserves CID and
        // does not create duplicate attachment.  We check this by re-parsing
        // as a SOAP message and verifying the contents.

        InputStream is = null;
        ByteArrayOutputStream baos = null;
        ByteArrayInputStream bais = null;
        try {
            String ctype = "multipart/related;type=\"application/xop+xml\";"
                    + "boundary=\"----=_Part_0_1145105632.1353005695468\";"
                    + "start=\"<cbe648b3-2055-413e-b8ed-877cdf0f2477>\";start-info=\"text/xml\"";

            MessageContextFactory mcf = MessageContextFactory
                    .createFactory(new MTOMFeature(true));
            is = getClass().getClassLoader().getResourceAsStream(
                    "etc/testMtomMessageReload_01.msg");
            MessageContext mc = mcf.createContext(is, ctype);
            Packet packet = (Packet) mc;
            Message message = packet.getInternalMessage();
            assertTrue("StreamMessage not found, got : " + message.getClass(),
                    StreamMessage.class.isAssignableFrom(message.getClass()));
            baos = new ByteArrayOutputStream();
            mc.writeTo(baos);
            bais = new ByteArrayInputStream(baos.toByteArray());
            MessageFactory mf = MessageFactory.newInstance();
            MimeHeaders mh = new MimeHeaders();
            mh.addHeader("Content-Type", ctype);
            SOAPMessage sm = mf.createMessage(mh, bais);
            assertEquals("wrong attachment count", 1, sm.countAttachments());
            AttachmentPart ap = sm.getAttachments().next();
            assertEquals("wrong attachemnt Content-Id",
                    "<534475ae-bdab-4594-9f97-c09908bacfbd>", ap.getContentId());
            NodeList nl = sm.getSOAPBody().getElementsByTagNameNS(
                    MtomCodec.XOP_NAMESPACEURI, MtomCodec.XOP_LOCALNAME);
            assertEquals(MtomCodec.XOP_NAMESPACEURI + ":"
                    + MtomCodec.XOP_LOCALNAME + " not found", 1, nl.getLength());
            Element elt = (Element) nl.item(0);
            assertEquals("wrong href value",
                    "cid:534475ae-bdab-4594-9f97-c09908bacfbd",
                    elt.getAttribute("href"));
        } finally {
            Exception e = null;
            try {
                if (is != null)
                    is.close();
            } catch (IOException e1) {
                e = e1;
            }
            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e2) {
                e = e2;
            }
            try {
                if (bais != null)
                    bais.close();
            } catch (Exception e3) {
                e = e3;
            }
            if (e != null)
                throw e;
        }
    }

    public void testWriteMtomToStreamClientRequest() throws Exception {
        // DISI may set the packet.state to State.ClientRequest
        // ((Packet)mc).setState(State.ClientRequest)
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        ByteArrayInputStream bais = null;
        try {
            String ctype = "multipart/related; boundary=MIME_Boundary; "+
            "start=\"<ff2b0fb4-9bcf-4ff5-ba16-d3436c78c3fd>\"; " +
            "type=\"application/xop+xml\"; start-info=\"text/xml\"";
            MessageContextFactory mcf = MessageContextFactory.createFactory(new MTOMFeature(true));
            is = getClass().getClassLoader().getResourceAsStream("etc/testMtomMessage_osb_disi.msg");
            MessageContext mc = mcf.createContext(is, ctype);
            Packet packet = (Packet) mc;
            Message message = packet.getInternalMessage();
            assertTrue("StreamMessage not found, got : " + message.getClass(),
                    StreamMessage.class.isAssignableFrom(message.getClass()));
            baos = new ByteArrayOutputStream();

            ((Packet)mc).setState(State.ClientRequest);
            mc.writeTo(baos);

            bais = new ByteArrayInputStream(baos.toByteArray());
            MessageFactory mf = MessageFactory.newInstance();
            MimeHeaders mh = new MimeHeaders();
            mh.addHeader("Content-Type", ctype);
            SOAPMessage sm = mf.createMessage(mh, bais);
            assertEquals("wrong attachment count", 1, sm.countAttachments());
            AttachmentPart ap = sm.getAttachments().next();
            assertEquals("wrong attachemnt Content-Id", "<testAttachmentContentId>", ap.getContentId());
            NodeList nl = sm.getSOAPBody().getElementsByTagNameNS(MtomCodec.XOP_NAMESPACEURI, MtomCodec.XOP_LOCALNAME);
            assertEquals(MtomCodec.XOP_NAMESPACEURI + ":" + MtomCodec.XOP_LOCALNAME + " not found", 1, nl.getLength());
            Element elt = (Element) nl.item(0);
            assertEquals("wrong href value", "cid:testAttachmentContentId", elt.getAttribute("href"));
        } finally {
            Exception e = null;
            try {
                if (is != null) is.close();
            } catch (IOException e1) {
                e = e1;
            }
            try {
                if (baos != null) baos.close();
            } catch (IOException e2) {
                e = e2;
            }
            try {
                if (bais != null) bais.close();
            } catch (Exception e3) {
                e = e3;
            }
            if (e != null) throw e;
        }
    }

    //Bug 17367334
    public void testWriteSwaToStreamClientRequest() throws Exception {
        String ctype = "multipart/related; boundary=MIME_Boundary; "+
        "start=\"<6232425701115978772--54bee05.140acdf4f8a.-7f3f>\"; " +
        "type=\"text/xml\"; start-info=\"text/xml\"";
        MessageContextFactory mcf = MessageContextFactory.createFactory(new MTOMFeature(true));
        InputStream is = getClass().getClassLoader().getResourceAsStream("etc/bug17367334InputMsg.txt");
        Packet packet = (Packet) mcf.createContext(is, ctype);
        Message message = packet.getInternalMessage();
        assertTrue("StreamMessage not found, got : " + message.getClass(),
                    StreamMessage.class.isAssignableFrom(message.getClass()));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        packet.setState(State.ClientRequest);
//System.out.println("SWA packet.getContentType(): " + packet.getContentType().getContentType() );

        ContentType contentType = packet.writeTo(baos);
//System.out.println("etc/bug17367334InputMsg.txt\r\n" + contentType.getContentType() + "\r\n" + new String(baos.toByteArray()));

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        MessageFactory mf = MessageFactory.newInstance();
        MimeHeaders mh = new MimeHeaders();
        mh.addHeader("Content-Type", ctype);
        SOAPMessage sm = mf.createMessage(mh, bais);
        assertEquals("wrong attachment count", 1, sm.countAttachments());
        AttachmentPart ap = sm.getAttachments().next();
        assertEquals("wrong attachemnt Content-Id", "<testAttachmentContentId>", ap.getContentId());
//        NodeList nl = sm.getSOAPBody().getElementsByTagNameNS(MtomCodec.XOP_NAMESPACEURI, MtomCodec.XOP_LOCALNAME);
    }
}