text:
from datetime import date, datetime

from typing import List, Dict, Type

from openapi_server.models.base_model_ import Model
from openapi_server.models.cause_action import CauseAction
from openapi_server.models.empty_change_log_set import EmptyChangeLogSet
from openapi_server import util

class FreeStyleBuild(Model):
    """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).

    Do not edit the class manually.
    """

    def __init__(self, _class: str=None, number: int=None, url: str=None, actions: List[CauseAction]=None, building: bool=None, description: str=None, display_name: str=None, duration: int=None, estimated_duration: int=None, executor: str=None, full_display_name: str=None, id: str=None, keep_log: bool=None, queue_id: int=None, result: str=None, timestamp: int=None, built_on: str=None, change_set: EmptyChangeLogSet=None):
        """FreeStyleBuild - a model defined in OpenAPI

        :param _class: The _class of this FreeStyleBuild.
        :param number: The number of this FreeStyleBuild.
        :param url: The url of this FreeStyleBuild.
        :param actions: The actions of this FreeStyleBuild.
        :param building: The building of this FreeStyleBuild.
        :param description: The description of this FreeStyleBuild.
        :param display_name: The display_name of this FreeStyleBuild.
        :param duration: The duration of this FreeStyleBuild.
        :param estimated_duration: The estimated_duration of this FreeStyleBuild.
        :param executor: The executor of this FreeStyleBuild.
        :param full_display_name: The full_display_name of this FreeStyleBuild.
        :param id: The id of this FreeStyleBuild.
        :param keep_log: The keep_log of this FreeStyleBuild.
        :param queue_id: The queue_id of this FreeStyleBuild.
        :param result: The result of this FreeStyleBuild.
        :param timestamp: The timestamp of this FreeStyleBuild.
        :param built_on: The built_on of this FreeStyleBuild.
        :param change_set: The change_set of this FreeStyleBuild.
        """
        self.openapi_types = {
            '_class': str,
            'number': int,
            'url': str,
            'actions': List[CauseAction],
            'building': bool,
            'description': str,
            'display_name': str,
            'duration': int,
            'estimated_duration': int,
            'executor': str,
            'full_display_name': str,
            'id': str,
            'keep_log': bool,
            'queue_id': int,
            'result': str,
            'timestamp': int,
            'built_on': str,
            'change_set': EmptyChangeLogSet
        }

        self.attribute_map = {
            '_class': '_class',
            'number': 'number',
            'url': 'url',
            'actions': 'actions',
            'building': 'building',
            'description': 'description',
            'display_name': 'displayName',
            'duration': 'duration',
            'estimated_duration': 'estimatedDuration',
            'executor': 'executor',
            'full_display_name': 'fullDisplayName',
            'id': 'id',
            'keep_log': 'keepLog',
            'queue_id': 'queueId',
            'result': 'result',
            'timestamp': 'timestamp',
            'built_on': 'builtOn',
            'change_set': 'changeSet'
        }

        self.__class = _class
        self._number = number
        self._url = url
        self._actions = actions
        self._building = building
        self._description = description
        self._display_name = display_name
        self._duration = duration
        self._estimated_duration = estimated_duration
        self._executor = executor
        self._full_display_name = full_display_name
        self._id = id
        self._keep_log = keep_log
        self._queue_id = queue_id
        self._result = result
        self._timestamp = timestamp
        self._built_on = built_on
        self._change_set = change_set

    @classmethod
    def from_dict(cls, dikt: dict) -> 'FreeStyleBuild':
        """Returns the dict as a model

        :param dikt: A dict.
        :return: The FreeStyleBuild of this FreeStyleBuild.
        """
        return util.deserialize_model(dikt, cls)

    @property
    def _class(self):
        """Gets the _class of this FreeStyleBuild.

        :return: The _class of this FreeStyleBuild.
        :rtype: str
        """
        return self.__class

    @_class.setter
    def _class(self, _class):
        """Sets the _class of this FreeStyleBuild.

        :param _class: The _class of this FreeStyleBuild.
        :type _class: str
        """

        self.__class = _class

    @property
    def number(self):
        """Gets the number of this FreeStyleBuild.

        :return: The number of this FreeStyleBuild.
        :rtype: int
        """
        return self._number

    @number.setter
    def number(self, number):
        """Sets the number of this FreeStyleBuild.

        :param number: The number of this FreeStyleBuild.
        :type number: int
        """

        self._number = number

    @property
    def url(self):
        """Gets the url of this FreeStyleBuild.

        :return: The url of this FreeStyleBuild.
        :rtype: str
        """
        return self._url

    @url.setter
    def url(self, url):
        """Sets the url of this FreeStyleBuild.

        :param url: The url of this FreeStyleBuild.
        :type url: str
        """

        self._url = url

    @property
    def actions(self):
        """Gets the actions of this FreeStyleBuild.

        :return: The actions of this FreeStyleBuild.
        :rtype: List[CauseAction]
        """
        return self._actions

    @actions.setter
    def actions(self, actions):
        """Sets the actions of this FreeStyleBuild.

        :param actions: The actions of this FreeStyleBuild.
        :type actions: List[CauseAction]
        """

        self._actions = actions

    @property
    def building(self):
        """Gets the building of this FreeStyleBuild.

        :return: The building of this FreeStyleBuild.
        :rtype: bool
        """
        return self._building

    @building.setter
    def building(self, building):
        """Sets the building of this FreeStyleBuild.

        :param building: The building of this FreeStyleBuild.
        :type building: bool
        """

        self._building = building

    @property
    def description(self):
        """Gets the description of this FreeStyleBuild.

        :return: The description of this FreeStyleBuild.
        :rtype: str
        """
        return self._description

    @description.setter
    def description(self, description):
        """Sets the description of this FreeStyleBuild.

        :param description: The description of this FreeStyleBuild.
        :type description: str
        """

        self._description = description

    @property
    def display_name(self):
        """Gets the display_name of this FreeStyleBuild.

        :return: The display_name of this FreeStyleBuild.
        :rtype: str
        """
        return self._display_name

    @display_name.setter
    def display_name(self, display_name):
        """Sets the display_name of this FreeStyleBuild.

        :param display_name: The display_name of this FreeStyleBuild.
        :type display_name: str
        """

        self._display_name = display_name

    @property
    def duration(self):
        """Gets the duration of this FreeStyleBuild.

        :return: The duration of this FreeStyleBuild.
        :rtype: int
        """
        return self._duration

    @duration.setter
    def duration(self, duration):
        """Sets the duration of this FreeStyleBuild.

        :param duration: The duration of this FreeStyleBuild.
        :type duration: int
        """

        self._duration = duration

    @property
    def estimated_duration(self):
        """Gets the estimated_duration of this FreeStyleBuild.

        :return: The estimated_duration of this FreeStyleBuild.
        :rtype: int
        """
        return self._estimated_duration

    @estimated_duration.setter
    def estimated_duration(self, estimated_duration):
        """Sets the estimated_duration of this FreeStyleBuild.

        :param estimated_duration: The estimated_duration of this FreeStyleBuild.
        :type estimated_duration: int
        """

        self._estimated_duration = estimated_duration

    @property
    def executor(self):
        """Gets the executor of this FreeStyleBuild.

        :return: The executor of this FreeStyleBuild.
        :rtype: str
        """
        return self._executor

    @executor.setter
    def executor(self, executor):
        """Sets the executor of this FreeStyleBuild.

        :param executor: The executor of this FreeStyleBuild.
        :type executor: str
        """

        self._executor = executor

    @property
    def full_display_name(self):
        """Gets the full_display_name of this FreeStyleBuild.

        :return: The full_display_name of this FreeStyleBuild.
        :rtype: str
        """
        return self._full_display_name

    @full_display_name.setter
    def full_display_name(self, full_display_name):
        """Sets the full_display_name of this FreeStyleBuild.

        :param full_display_name: The full_display_name of this FreeStyleBuild.
        :type full_display_name: str
        """

        self._full_display_name = full_display_name

    @property
    def id(self):
        """Gets the id of this FreeStyleBuild.

        :return: The id of this FreeStyleBuild.
        :rtype: str
        """
        return self._id

    @id.setter
    def id(self, id):
        """Sets the id of this FreeStyleBuild.

        :param id: The id of this FreeStyleBuild.
        :type id: str
        """

        self._id = id

    @property
    def keep_log(self):
        """Gets the keep_log of this FreeStyleBuild.

        :return: The keep_log of this FreeStyleBuild.
        :rtype: bool
        """
        return self._keep_log

    @keep_log.setter
    def keep_log(self, keep_log):
        """Sets the keep_log of this FreeStyleBuild.

        :param keep_log: The keep_log of this FreeStyleBuild.
        :type keep_log: bool
        """

        self._keep_log = keep_log

    @property
    def queue_id(self):
        """Gets the queue_id of this FreeStyleBuild.

        :return: The queue_id of this FreeStyleBuild.
        :rtype: int
        """
        return self._queue_id

    @queue_id.setter
    def queue_id(self, queue_id):
        """Sets the queue_id of this FreeStyleBuild.

        :param queue_id: The queue_id of this FreeStyleBuild.
        :type queue_id: int
        """

        self._queue_id = queue_id

    @property
    def result(self):
        """Gets the result of this FreeStyleBuild.

        :return: The result of this FreeStyleBuild.
        :rtype: str
        """
        return self._result

    @result.setter
    def result(self, result):
        """Sets the result of this FreeStyleBuild.

        :param result: The result of this FreeStyleBuild.
        :type result: str
        """

        self._result = result

    @property
    def timestamp(self):
        """Gets the timestamp of this FreeStyleBuild.

        :return: The timestamp of this FreeStyleBuild.
        :rtype: int
        """
        return self._timestamp

    @timestamp.setter
    def timestamp(self, timestamp):
        """Sets the timestamp of this FreeStyleBuild.

        :param timestamp: The timestamp of this FreeStyleBuild.
        :type timestamp: int
        """

        self._timestamp = timestamp

    @property
    def built_on(self):
        """Gets the built_on of this FreeStyleBuild.

        :return: The built_on of this FreeStyleBuild.
        :rtype: str
        """
        return self._built_on

    @built_on.setter
    def built_on(self, built_on):
        """Sets the built_on of this FreeStyleBuild.

        :param built_on: The built_on of this FreeStyleBuild.
        :type built_on: str
        """

        self._built_on = built_on

    @property
    def change_set(self):
        """Gets the change_set of this FreeStyleBuild.

        :return: The change_set of this FreeStyleBuild.
        :rtype: EmptyChangeLogSet
        """
        return self._change_set

    @change_set.setter
    def change_set(self, change_set):
        """Sets the change_set of this FreeStyleBuild.

        :param change_set: The change_set of this FreeStyleBuild.
        :type change_set: EmptyChangeLogSet
        """

        self._change_set = change_set


text:
<?php

namespace Oro\Bundle\EmailBundle\Provider;

use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\User\UserInterface;

use Oro\Bundle\EntityConfigBundle\Config\ConfigInterface;
use Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider;

class VariablesProvider
{
    /** @var ConfigProvider  */
    protected $configProvider;

    /** @var SecurityContextInterface  */
    protected $securityContext;

    public function __construct(SecurityContextInterface $securityContext, ConfigProvider $provider)
    {
        $this->securityContext = $securityContext;
        $this->configProvider = $provider;
    }

    /**
     * Return available in template variables
     *
     * @param string $entityName
     * @return array
     */
    public function getTemplateVariables($entityName)
    {
        $userClassName = $this->getUser() ? get_class($this->getUser()) : false;
        $allowedData = [];

        $ids = $this->configProvider->getIds();
        foreach ($ids as $entityConfigId) {
            // export variables of asked entity and current user entity class
            $className = $entityConfigId->getClassName();
            if ($className == $entityName || $className == $userClassName) {
                $fields = $this->configProvider->filter(
                    function (ConfigInterface $config) {
                        return $config->is('available_in_template');
                    },
                    $className
                );

                $fields = array_values(
                    array_map(
                        function (ConfigInterface $field) {
                            return $field->getId()->getFieldName();
                        },
                        $fields
                    )
                );

                switch ($className) {
                    case $entityName:
                        $allowedData['entity'] = $fields;
                        break;
                    case $userClassName:
                        $allowedData['user'] = $fields;
                        break;
                }

                if ($entityName == $userClassName) {
                    $allowedData['user'] = $allowedData['entity'];
                }
            }
        }

        return $allowedData;
    }

    /**
     * Return current user
     *
     * @return UserInterface|bool
     */
    private function getUser()
    {
        return $this->securityContext->getToken() && !is_string($this->securityContext->getToken()->getUser())
            ? $this->securityContext->getToken()->getUser() : false;
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: front_page
---

          Home

About

What we do

Products

Research

Contact

 Neurodevelopmental disorders

      <button  id="button" onclick="location.href='about.html';" href="about.html" style="margin: 20px;">ADHD</button>

About Us

Inspired by a shared vision and mission to treat neurodevelopmental disorders, we are a company that is not afraid of creating a new path and providing a guiding light for those who would travel the same path.

Our Vision

              We want to give hope to children with ADHD through relieving their stress and pain, including their families'.
We aim to make South Korea the number one medical healthcare-providing country.

Disorders

              Attention Deficit Hyperactivity Disorder (ADHD) is a neurodevelopmental disorder which has three core symptoms: inattention, hyperactivity and impulsivity. According to adhd-institute.com there are between 5.29% - 7.1% of children and adolescents suffer from ADHD and there is a higher prevalence in males than females.

Our Service

              Our company develops varied neurodevelopmental disease models, performs drug efficacy tests through drug screening and conducts two-way consultation on experiments and drugs.

Research

Specific research focusing on ADHD

              Our company has received various research assignments on neurodevelopmental disorders from national grants, helping us hone our skills in this particular field of research. Recently we got S grade from the Research Foundation in South Korea.We develop effective and personalized drug for patients aiming to reduce unwanted drug side effects through pharmacologically-based research procedures.

OUR FOCUS

Through developing the drug which has various discriminative choices, we modulate multiple targets flexibly and minimize adverse effects to improve efficacy, guarantee stability and expand usage on other various diseases

ADHD

            Trineurotec

ASD

            Neuroventi

FXS

            Ineuro

Drug development

We provide a personalized solution matching patient's developmental period to enhance development of brain function and prevent brain disorders from infancy to adulthood.

Product 1

            Product 1 description

Product 2

            Product 2 description

Product 3

            Product 3 description

Research

Specific research focusing on nuerodevelopmental disorders.

              In vitro drug screening: research by using primary nerve cell such as neural progenitor cells, neurons, and glia cells

High sucrose consumption during pregnancy induced ADHD-like behavioral phenotypes in mice offspring

              Read More

              In vivo disease model development and pharmacological effect research: use drug-induced and transgenic animal models

Effects of ethanol exposure during early pregnancy in hyperactive, inattentive and impulsive behaviors and MeCP2 expression in rodent offspring.

              Read More

              Research based on multiomics intending to find new biomarkers and targets for neurodevelopmental disorders

Chronic exposure to ethanol of male mice before mating produces attention deficit hyperactivity disorder-like phenotype along with epigenetic dysregulation of dopamine transporter expression in mouse offspring

              Read More

    <form action="#">

Our Address

Konkuk University Hwayang Dong, Kwangjin-Gu Seoul 143-701, Korea

82-2-2030-7834

trineurotec@gmail.com

www.trineurotec.github.io

    </form>


text:
using GagyiBankMVC.Models;
using GagyiBankMVC.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GagyiBankMVC.Controllers
{
    [Authorize]
    public class TransactionController : Controller
    {
        private IApplicationDbContext db;

        public TransactionController()
        {
            db = new ApplicationDbContext();
        }

        public TransactionController(IApplicationDbContext dbContext)
        {
            db = dbContext;
        }

        public ActionResult Deposit(int checkingAccountId)
        {
            return View();
        }

        [HttpPost]
        public ActionResult Deposit(TransactionModel transaction)
        {
            if (ModelState.IsValid)
            {
                db.Transactions.Add(transaction);
                db.SaveChanges();

                var service = new CheckingAccountService(db);
                service.UpdateBalance(transaction.CheckingAccountId);
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        public ActionResult QuickCash(int checkingAccountId, decimal amount)
        {
            var sourceCheckingAccount = db.CheckingAccounts.Find(checkingAccountId);
            var balance = sourceCheckingAccount.Balance;
            if (balance < amount)
            {
                return View("QuickCashInsufficientFunds");
            }
            db.Transactions.Add(new TransactionModel { CheckingAccountId = checkingAccountId, Amount = -amount });
            db.SaveChanges();

            var service = new CheckingAccountService(db);
            service.UpdateBalance(checkingAccountId);

            return RedirectToAction("Index", "Home");
        }

        public ActionResult Withdrawal(int checkingAccountId)
        {
            return View();
        }

        [HttpPost]
        public ActionResult Withdrawal(TransactionModel transaction)
        {
            var checkingAccount = db.CheckingAccounts.Find(transaction.CheckingAccountId);
            if (checkingAccount.Balance < transaction.Amount)
            {
                ModelState.AddModelError("Amount", "You have insufficient funds!");
            }

            if (ModelState.IsValid)
            {
                transaction.Amount = -transaction.Amount;
                db.Transactions.Add(transaction);
                db.SaveChanges();

                var service = new CheckingAccountService(db);
                service.UpdateBalance(transaction.CheckingAccountId);
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        public ActionResult Transfer(int checkingAccountId)
        {
            return View();
        }

        [HttpPost]
        public ActionResult Transfer(TransferViewModel transfer)
        {
            // check for available funds
            var sourceCheckingAccount = db.CheckingAccounts.Find(transfer.CheckingAccountId);
            if (sourceCheckingAccount.Balance < transfer.Amount)
            {
                ModelState.AddModelError("Amount", "You have insufficient funds!");
            }

            // check for a valid destination account
            var destinationCheckingAccount = db.CheckingAccounts.Where(c => c.AccountNumber == transfer.DestinationCheckingAccountNumber).FirstOrDefault();
            if (destinationCheckingAccount == null)
            {
                ModelState.AddModelError("DestinationCheckingAccountNumber", "Invalid destination account number.");
            }

            // add debit/credit transactions and update account balances
            if (ModelState.IsValid)
            {
                db.Transactions.Add(new TransactionModel { CheckingAccountId = transfer.CheckingAccountId, Amount = -transfer.Amount });
                db.Transactions.Add(new TransactionModel { CheckingAccountId = destinationCheckingAccount.Id, Amount = transfer.Amount });
                db.SaveChanges();

                var service = new CheckingAccountService(db);
                service.UpdateBalance(transfer.CheckingAccountId);
                service.UpdateBalance(destinationCheckingAccount.Id);

                return PartialView("_TransferSuccess", transfer);
            }
            return PartialView("_TransferForm");
        }
    }
}


text:
define(function(require) {
  'use strict';

  var AdminMenuAreaView = require('foreground/view/appBar/adminMenuAreaView');
  var viewTestUtility = require('test/foreground/view/viewTestUtility');

  describe('AdminMenuAreaView', function() {
    beforeEach(function() {
      this.documentFragment = document.createDocumentFragment();
      this.view = new AdminMenuAreaView();
    });

    afterEach(function() {
      this.view.destroy();
    });

    viewTestUtility.ensureBasicAssumptions.call(this);
  });
});


text:
package org.apache.camel.component.netty4.http;

import io.netty.handler.codec.http.FullHttpRequest;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.http4.HttpMethods;
import org.junit.Test;

public class NettyHttpBindingUseRelativePathTest extends BaseNettyTest {

    @Test
    public void testSendToNettyWithPath() throws Exception {
        Exchange exchange = template.request("netty4-http:http://localhost:{{port}}/mypath", new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(Exchange.HTTP_METHOD, HttpMethods.POST);
            }
        });

        // convert the response to a String
        String body = exchange.getOut().getBody(String.class);
        assertEquals("Request message is OK", body);
    }

    @Test
    public void testSendToNettyWithoutPath() throws Exception {
        Exchange exchange = template.request("netty4-http:http://localhost:{{port}}", new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(Exchange.HTTP_METHOD, HttpMethods.POST);
            }
        });

        // convert the response to a String
        String body = exchange.getOut().getBody(String.class);
        assertEquals("Request message is OK", body);
    }

    @Test
    public void testSendToNettyWithoutPath2() throws Exception {
        Exchange exchange = template.request("netty4-http:http://localhost:{{port}}/", new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(Exchange.HTTP_METHOD, HttpMethods.POST);
            }
        });

        // convert the response to a String
        String body = exchange.getOut().getBody(String.class);
        assertEquals("Request message is OK", body);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from("netty4-http:http://localhost:{{port}}/mypath").process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        assertEquals("Get a wrong form parameter from the message header", "localhost:" + getPort(), exchange.getIn().getHeader("host"));

                        NettyHttpMessage in = (NettyHttpMessage) exchange.getIn();
                        FullHttpRequest request = in.getHttpRequest();
                        assertEquals("Relative path not used in POST", "/mypath", request.uri());

                        // send a response
                        exchange.getOut().getHeaders().clear();
                        exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "text/plain");
                        exchange.getOut().setBody("Request message is OK");
                    }
                });

                from("netty4-http:http://localhost:{{port}}").process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        assertEquals("Get a wrong form parameter from the message header", "localhost:" + getPort(), exchange.getIn().getHeader("host"));

                        NettyHttpMessage in = (NettyHttpMessage) exchange.getIn();
                        FullHttpRequest request = in.getHttpRequest();
                        assertEquals("Relative path not used in POST", "/", request.uri());

                        // send a response
                        exchange.getOut().getHeaders().clear();
                        exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "text/plain");
                        exchange.getOut().setBody("Request message is OK");
                    }
                });
            }
        };
    }

}


text:
<?php require 'include/prehtml.php'; ?>
<?php require_active_firm(); ?>
<?php
$bldg_slot = filter_var($_GET['slot'], FILTER_SANITIZE_NUMBER_INT);
if(!$bldg_slot || $bldg_slot < 1){
	fbox_breakout('buildings.php');
}

// Check if there is already a building on the given slot
$query = $db->prepare("SELECT COUNT(*) AS cnt, building_type FROM queue_build WHERE fid = ? AND building_slot = ?");
$query->execute(array($eos_firm_id, $bldg_slot));
$result = $query->fetch(PDO::FETCH_ASSOC);
if($result['cnt']){
	fbox_redirect('bldg-expand-status.php?type='.$result['building_type'].'&slot='.$bldg_slot);
}
$sql = "(SELECT id, 'fact' AS bldg_type FROM firm_fact WHERE fid = :eos_firm_id AND slot = :slot) UNION (SELECT id, 'store' AS bldg_type FROM firm_store WHERE fid = :eos_firm_id AND slot = :slot) UNION (SELECT id, 'rnd' AS bldg_type FROM firm_rnd WHERE fid = :eos_firm_id AND slot = :slot)";
$query_get_bldg_id = $db->prepare($sql);
$query_get_bldg_id->execute(array(':eos_firm_id' => $eos_firm_id, ':slot' => $bldg_slot));
$firm_bldg = $query_get_bldg_id->fetch(PDO::FETCH_ASSOC);
if(!empty($firm_bldg)){
	$bldg_id = $firm_bldg['id'];
	$bldg_type = $firm_bldg['bldg_type'];
	if($bldg_type == 'fact'){
		$bldg_activity_url = 'factories-production.php?ffid=';
	}else if($bldg_type == 'store'){
		$bldg_activity_url = 'stores-sell.php?fsid=';
	}else if($bldg_type == 'rnd'){
		$bldg_activity_url = 'rnd-res.php?frid=';
	}else{
		fbox_breakout('buildings.php');
	}
	fbox_redirect($bldg_activity_url.$bldg_id);
}

// Find out the player's max buildings
$query = $db->prepare("SELECT max_bldg FROM firms WHERE id = ?");
$query->execute(array($eos_firm_id));
$max_bldg = $query->fetchColumn();
if($max_bldg < $bldg_slot){
	fbox_breakout('buildings.php');
}
?>
<?php require 'include/functions.php'; ?>

<?php require 'include/stats_fbox.php'; ?>
<?php
	// Initialize player level
	$sql = "SELECT player_level FROM players WHERE id = '$eos_player_id'";
	$player_level = $db->query($sql)->fetchColumn();
	if($player_level < 5){
?>

		Did you know?

		You can hover your mouse cursor over each building to see what it can produce, sell, or research.

		Once construction has started, you may click on the building to see its construction status, or to hire RJ Construction to instantly finish your project.
		Since you are a new entrepreneur, RJ Construction will automatically finish your construction project, and on expansions for buildings up to 500 m² using government subsidy.

<?php
	}

	function get_bldg_functions($db, $bldg_type, $bldg_id){
		// Populate building function list
		if($bldg_type == 'fact'){
			$sql = "SELECT opid1 FROM list_fact_choices LEFT JOIN list_prod ON list_fact_choices.opid1 = list_prod.id WHERE list_fact_choices.fact_id = '$bldg_id' GROUP BY list_prod.name ORDER BY list_prod.name ASC";
			$produceables = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
			$list_bldg_functions = "Produces: ";
			if(count($produceables)){
				foreach($produceables as $produceable){
					$sql = "SELECT name FROM list_prod WHERE id = ".$produceable['opid1'];
					$list_bldg_functions .= "
".$db->query($sql)->fetchColumn();
				}
			}else{
				$list_bldg_functions .= "
Nothing";
			}
			return $list_bldg_functions;
		}
		if($bldg_type == 'store'){
			$sql = "SELECT list_store_choices.cat_id FROM list_store_choices LEFT JOIN list_cat ON list_store_choices.cat_id = list_cat.id WHERE list_store_choices.store_id = '$bldg_id' ORDER BY list_cat.name ASC";
			$sellables = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
			$list_bldg_functions = "Sells: ";
			if(count($sellables)){
				foreach($sellables as $sellable){
					$sql = "SELECT name FROM list_cat WHERE id = ".$sellable['cat_id'];
					$list_bldg_functions .= "
".$db->query($sql)->fetchColumn()." (";

					$sql = "SELECT name FROM list_prod WHERE cat_id = ".$sellable['cat_id']." ORDER BY name ASC";
					$sell_prods = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
					if(count($sell_prods)){
						foreach($sell_prods as $sell_prod){
							$list_bldg_functions .= $sell_prod['name'].", ";
						}
						$list_bldg_functions = substr($list_bldg_functions, 0, -2);
					}else{
						$list_bldg_functions .= "Nothing";
					}
					$list_bldg_functions .= ")";
				}
			}else{
				$list_bldg_functions .= "
Nothing";
			}
			return $list_bldg_functions;
		}
		if($bldg_type == 'rnd'){
			$sql = "SELECT cat_id FROM list_rnd_choices WHERE rnd_id = '$bldg_id'";
			$researchables = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
			$list_bldg_functions = "Researches: ";
			if(count($researchables)){
				foreach($researchables as $researchable){
					$sql = "SELECT name FROM list_cat WHERE id = ".$researchable['cat_id'];
					$list_bldg_functions .= "
".$db->query($sql)->fetchColumn()." (";

					$sql = "SELECT name FROM list_prod WHERE cat_id = ".$researchable['cat_id']." ORDER BY name ASC";
					$res_prods = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
					if(count($res_prods)){
						foreach($res_prods as $res_prod){
							$list_bldg_functions .= $res_prod['name'].", ";
						}
						$list_bldg_functions = substr($list_bldg_functions, 0, -2);
					}else{
						$list_bldg_functions .= "Nothing";
					}
					$list_bldg_functions .= ")";
				}
			}else{
				$list_bldg_functions .= "
Nothing";
			}
			return $list_bldg_functions;
		}
	}
	function do_output($db, $bldg_type, $ctrl_build, $player_level, $ctrl_leftover_allowance){
		if($bldg_type == 'fact'){
			$query_get_bldg_list_info_all = $db->prepare("SELECT id, name, firstcost, firsttimecost, has_image FROM list_fact ORDER BY name ASC");
		}else if($bldg_type == 'store'){
			$query_get_bldg_list_info_all = $db->prepare("SELECT id, name, firstcost, firsttimecost, has_image FROM list_store ORDER BY name ASC");
		}else if($bldg_type == 'rnd'){
			$query_get_bldg_list_info_all = $db->prepare("SELECT id, name, firstcost, firsttimecost, has_image FROM list_rnd ORDER BY name ASC");
		}else{
			echo 'Unknown building type.
';
			return false;
		}
		if(!$ctrl_build){
			if($bldg_type == 'fact') $bldg_type_display = 'factories';
			if($bldg_type == 'store') $bldg_type_display = 'stores';
			if($bldg_type == 'rnd') $bldg_type_display = 'research facilities';
			echo 'You are not authorized to construct new '.$bldg_type_display.'.
';
			return false;
		}

		// Initialize buildings list
		$query_get_bldg_list_info_all->execute();
		$bldg_list = $query_get_bldg_list_info_all->fetchAll(PDO::FETCH_ASSOC);

		foreach($bldg_list as $bldg_list_item){
			$list_bldg_id = $bldg_list_item["id"];
			$build_cost = $bldg_list_item["firstcost"];
			$generic_name = $bldg_list_item["name"];
			if($bldg_list_item["has_image"]){
				$filename = preg_replace(array("/[\s\&\']/","/_{2,}/"), '_', strtolower($generic_name));
			}else{
				$filename = "no-image";
			}

			$list_bldg_functions = get_bldg_functions($db, $bldg_type, $list_bldg_id);
			echo '
';
			echo '',$generic_name,' ',$list_bldg_functions,'
';
			echo '
';
			echo ' $',number_format($build_cost/100, 2, '.', ','),'
';
			if($player_level < 5){
				echo ' INSTANT
';
			}else{
				// echo ' ',number_format($bldg_list_item["firsttimecost"]/60, 2, '.', ''),' min.
';
				echo ' 10 sec.
';
			}
			if($_SESSION['firm_cash'] < $build_cost){
				echo 'Not Enough Money';
			}else if($ctrl_leftover_allowance < $build_cost){
				echo 'Cost exceeds your daily spending limit.';
			}else{
				echo 'Click to Start Building

There will be no confirmation';
			}
			echo '
';
		}
	}
?>

		<?php do_output($db, 'fact', $ctrl_fact_build, $player_level, $ctrl_leftover_allowance); ?>

		<?php do_output($db, 'store', $ctrl_store_build, $player_level, $ctrl_leftover_allowance); ?>

		<?php do_output($db, 'rnd', $ctrl_rnd_build, $player_level, $ctrl_leftover_allowance); ?>

	<input type="button" class="bigger_input jqDialog-close-btn" value="Close" />
<?php require 'include/foot_fbox.php'; ?>


text:
package org.wso2.developerstudio.eclipse.integration.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;

public class IntegrationUtils {

    private static final String ADDITIONAL_FOLDERS = "default";

    private static String getLocalTagName(IntegrationEntryType type) {
        switch (type) {
            case INTEGRATION_TEMPLATE:
                return "integration-template";
            case CONNECTION:
                return "connection";
            case ALL:
                return "";
            default:
                return "";
        }
    }

    public static List<OMElement> integrationConfigFolderContentProcessing(String integrationConfigFolderPath) throws XMLStreamException,
                                                                                IOException,
                                                                                OMException,
                                                                                Exception {

        List<OMElement> editorList = new ArrayList<OMElement>();
        File rootDir = new File(integrationConfigFolderPath + "/" + ADDITIONAL_FOLDERS);

        if (!rootDir.exists()) {
            rootDir = new File(integrationConfigFolderPath);
        }
        File[] dirs = rootDir.listFiles();
        int dirCount = dirs.length;
        for (int i = 0; i < dirCount; ++i) {
            String name = dirs[i].getName();
            if (name.equals("integration-templates")) {
                processFiles(editorList, rootDir + "/integration-template",
                             IntegrationEntryType.INTEGRATION_TEMPLATE);
            } else if (name.equals("connections")) {
                processFiles(editorList, rootDir + "/endpoints", IntegrationEntryType.CONNECTION);
            }
        }
        return editorList;
    }

    private static void processFiles(List<OMElement> editorList, String dirPath,
                                     IntegrationEntryType type) throws XMLStreamException,
                                                                IOException, OMException,
                                                                Exception {
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        int fileCount = files.length;
        for (int j = 0; j < fileCount; ++j) {
            OMElement documentElement =
                                      new StAXOMBuilder(new FileInputStream(files[j])).getDocumentElement();

            String localTagName = getLocalTagName(type);

            String localName = documentElement.getLocalName();
            if (localName.equals(localTagName)) {
                if (!editorList.contains(documentElement)) {
                    editorList.add(documentElement);
                }
            }
        }
    }
}


text:
// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using ClearCase;

using Microsoft.TeamFoundation.Migration.Toolkit;
using Microsoft.TeamFoundation.Migration.Toolkit.Services;

namespace Microsoft.TeamFoundation.Migration.ClearCaseDetailedHistoryAdapter
{
    /// <summary>
    /// This class wraps calls to the clearcase server.
    /// </summary>
    public class ClearCaseServer
    {
        private static Dictionary<string, ClearCaseServer> instanceTable = new Dictionary<string, ClearCaseServer>();

        ClearToolClass m_clearCaseTool;
        CCView m_clearCaseView;

        // For a branch test, branch name is 'test', BranchVersionString is 'main\test';
        public string BranchVersionString { get; private set; }
        public string BranchName { get; private set; }
        public string ViewName { get; set; }
        public string StorageLocation { get; private set;}
        public string StorageLocationLocalPath { get; private set; }
        public ApplicationClass ApplicationClass { get; private set; }
        public string ViewRootPath { get; private set; }
        public string ViewRootLocalPath { get; private set; }
        public List<string> VobList { get; private set; }
        public bool UsePrecreatedView { get; private set; }
        public bool UseDynamicView { get; private set; }

        #region clearfsimport variables - Properties to record the state of clearfsimport command execution.
        private static Dictionary<string, ClearfsimportResult> s_clearfsimportOutput = new Dictionary<string, ClearfsimportResult>();
        private static List<string> s_clearfsimportErrorOutput = new List<string>();
        private static string  s_elementPath = string.Empty;
        private static ClearfsimportResult s_previousState = ClearfsimportResult.Initialize;
        #endregion

        public CCView ClearCaseView
        {
            get
            {
                if (m_clearCaseView == null)
                {
                    m_clearCaseView = ApplicationClass.get_View(ViewName);
                }
                return m_clearCaseView;
            }
        }

        /// <summary>
        /// Get an instance of the ClearCaseServer object
        /// </summary>
        /// <param name="storageLocation"></param>
        /// <param name="viewName"></param>
        /// <returns></returns>
        public static ClearCaseServer GetInstance(
            string storageLocation,
            string storageLocationLocalPath,
            string viewName,
            List<string> vobList,
            string branchName)
        {
            if (!instanceTable.ContainsKey(viewName))
            {
                instanceTable.Add(viewName, new ClearCaseServer(storageLocation, storageLocationLocalPath, viewName, vobList, branchName));
            }
            return instanceTable[viewName];
        }

        /// <summary>
        /// Get an instance of the ClearCaseServer object
        /// </summary>
        /// <param name="storageLocation"></param>
        /// <param name="viewName"></param>
        /// <returns></returns>
        public static ClearCaseServer GetInstance(CCConfiguration configuration, string viewName)
        {
            if (!instanceTable.ContainsKey(viewName))
            {
                instanceTable.Add(viewName, new ClearCaseServer(configuration, viewName));
            }
            return instanceTable[viewName];
        }

        /// <summary>
        /// Get an instance of the ClearCaseServer object
        /// </summary>
        /// <param name="storageLocation"></param>
        /// <param name="viewName"></param>
        /// <returns></returns>
        public static ClearCaseServer GetInstance(string viewName)
        {
            if ((instanceTable == null) || (!instanceTable.ContainsKey(viewName)))
            {
                throw new MigrationException(String.Format(CCResources.ClearCaseServerNotFound, viewName));
            }
            return instanceTable[viewName];
        }

        /// <summary>
        /// 1. Call all ClearCaseServer object in instanceTable to release COM object
        /// 2. Clear the instanceTable
        /// </summary>
        public static void CleanUp()
        {
            if (instanceTable == null)
            {
                return;
            }
            foreach (KeyValuePair<string, ClearCaseServer> instanceTableEntry in instanceTable)
            {
                instanceTableEntry.Value.cleanUp();
            }
            instanceTable.Clear();
        }

        /// <summary>
        /// Get the vob absolute path from a relative path.
        /// </summary>
        /// <param name="relativePath"></param>
        public string GetVobAbsolutePathFromRelativePath(string relativePath)
        {
            if (string.IsNullOrEmpty(relativePath))
            {
                return relativePath;
            }
            else
            {
                return ClearCasePath.Combine(ViewRootPath, relativePath);
            }
        }

        /// <summary>
        /// Get the vob absolute path from a relative path.
        /// </summary>
        /// <param name="relativePath"></param>
        public string GetRelativePathFromVobAbsolutePath(string vobAbsolutePath)
        {
            if (string.IsNullOrEmpty(vobAbsolutePath) || !vobAbsolutePath.StartsWith(ViewRootPath))
            {
                return vobAbsolutePath;
            }
            else
            {
                return vobAbsolutePath.Substring(ViewRootPath.Length);
            }
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        private ClearCaseServer(CCConfiguration configuration, string viewName)
        {
            ApplicationClass = new ApplicationClass();
            m_clearCaseTool = new ClearToolClass();
            StorageLocation = configuration.StorageLocation;
            StorageLocationLocalPath = configuration.StorageLocationLocalPath;
            ViewName = viewName;
            ViewRootPath = configuration.UseDynamicView ? configuration.DynamicViewRoot : ClearCasePath.Combine(StorageLocation, ViewName);
            ViewRootLocalPath = configuration.UseDynamicView ? configuration.DynamicViewRoot
                                                             : ClearCasePath.Combine(StorageLocationLocalPath, ViewName);
            BranchName = configuration.BranchName;

            if (configuration.UsePrecreatedView)
            {
                BranchVersionString = string.Empty;
            }
            else if (string.Equals(BranchName, CCResources.DefaultBranchName, StringComparison.OrdinalIgnoreCase))
            {
                BranchVersionString = BranchName;
            }
            else
            {
                BranchVersionString = string.Format(CCResources.BranchVersionString, BranchName);
            }
            VobList = configuration.VobList;
            UsePrecreatedView = configuration.UsePrecreatedView;
            UseDynamicView = configuration.UseDynamicView;
            verifyVobAndBranchType();
        }

        /// <summary>
        /// Create an ClearCaseServer that uses a snapshot view that will be created in runtime.
        /// </summary>
        private ClearCaseServer(string storageLocation, string storageLocationLocalPath, string viewName, List<string> vobList, string branchName)
        {
            ApplicationClass = new ApplicationClass();
            m_clearCaseTool = new ClearToolClass();
            StorageLocation = storageLocation;
            StorageLocationLocalPath = storageLocationLocalPath;
            ViewName = viewName;
            ViewRootPath = ClearCasePath.Combine(StorageLocation, ViewName);
            ViewRootLocalPath = ClearCasePath.Combine(StorageLocationLocalPath, ViewName);
            BranchName = branchName;

            if (string.Equals(branchName, CCResources.DefaultBranchName, StringComparison.OrdinalIgnoreCase))
            {
                BranchVersionString = BranchName;
            }
            else
            {
                BranchVersionString = string.Format(CCResources.BranchVersionString, branchName);
            }
            VobList = vobList;
            UsePrecreatedView = false;
            UseDynamicView = false;
            verifyVobAndBranchType();
        }

        private void verifyVobAndBranchType()
        {
            CCVOB ccVob;
            foreach (string vob in VobList)
            {
                try
                {
                    ccVob = ApplicationClass.get_VOB(vob);
                    if (string.IsNullOrEmpty(BranchName))
                    {
                        // BranchName is empty. This is possible when the user provide a precreated view in the configuration file.
                        // Skip the logic to verify branches.
                        continue;
                    }
                }
                catch (COMException)
                {
                    throw new MigrationException("VOB {0} does not exist.", vob);
                }
                try
                {
                    ccVob.get_BranchType(BranchName, false);
                }
                catch(COMException)
                {
                    TraceManager.TraceInformation("Create branch type {0} in VOB {1}.", BranchName, vob);
                    ccVob.CreateBranchType(BranchName, "Created by ClearCaseDetailedHistoryAdapter", CCTypeConstraint.ccConstraint_PerBranch, false, false);
                }
            }
        }

        /// <summary>
        /// Undo all checkouts under the specified path and then the path itself.
        /// </summary>
        /// <param name="path"></param>
        public void UndoCheckoutRecursive(string path)
        {
            List<string> checkoutFileList;
            string lsCheckoutCmdOutput = null;
            try
            {
                // Query checkout on the path itself.
                string lsCheckoutCmd = string.Format(ClearToolCommand.lscheckoutNonRecursive, ClearCasePath.MakeRelative(path));
                lsCheckoutCmdOutput = ExecuteClearToolCommand(lsCheckoutCmd);
                checkoutFileList = CCTextParser.ParseLSOutput(lsCheckoutCmdOutput);
                UndoCheckout(checkoutFileList);

                // Query all checkouts recursively.
                lsCheckoutCmd = string.Format(ClearToolCommand.lscheckoutRecursive, ClearCasePath.MakeRelative(path));
                lsCheckoutCmdOutput = ExecuteClearToolCommand(lsCheckoutCmd);
                checkoutFileList = CCTextParser.ParseLSOutput(lsCheckoutCmdOutput);
                UndoCheckout(checkoutFileList);
            }
            catch (COMException ce)
            {
                COMExceptionResult rslt = CCTextParser.ProcessComException(ce);
                if ((rslt == COMExceptionResult.NotAccessible)
                    || (rslt == COMExceptionResult.UnableToDetermineDynamicView)
                    || (rslt == COMExceptionResult.PathNotFound))
                {
                    return;
                }
                else
                {
                    throw;
                }
            }

        }

        public List<string> QueryViewPrivateFiles(string viewName)
        {
            List<string> viewPrivateFileList = new List<string>();
            try
            {
                foreach(string vob in VobList)
                {
                    string lsPrivateCmd = string.Format("lsprivate -tag \"{0}\" -invob \"{1}\" -other ", viewName, vob);
                    viewPrivateFileList.AddRange(
                        CCTextParser.ParseLSOutput(ExecuteClearToolCommand(lsPrivateCmd)));
                }
            }
            catch (COMException ce)
            {
                Trace.TraceWarning(string.Format("Failed to list private files for view \"{0}\". Error message {1}", viewName, ce.Message));
                throw;
            }

            return viewPrivateFileList;
        }

        public void UndoCheckout(List<string> checkoutFileList)
        {
            string uncheckoutCmd;
            string uncheckoutCmdOutput;
            if ((checkoutFileList == null) || (checkoutFileList.Count == 0))
            {
                return;
            }
            foreach (string checkoutFile in checkoutFileList)
            {
                uncheckoutCmd = string.Format("uncheckout -rm \"{0}\"", checkoutFile);
                try
                {
                    uncheckoutCmdOutput = ExecuteClearToolCommand(uncheckoutCmd);
                }
                catch (COMException ce)
                {
                    Trace.TraceWarning(string.Format("Failed to uncheckout element \"{0}\". Error message {1}", checkoutFile, ce.Message));
                }
            }
        }

        /// <summary>
        /// Create a configspec based on configuration file.
        /// </summary>
        private void createConfigSpec()
        {
            StringBuilder configSpecRule = new StringBuilder(CCResources.ConfigSpecCheckOutRule);
            if (string.IsNullOrEmpty(BranchVersionString) ||
                string.Equals(BranchVersionString, "main", StringComparison.OrdinalIgnoreCase))
            {
                configSpecRule.AppendFormat(CCResources.ConfigSpecSelectMain);
            }
            else
            {
                configSpecRule.AppendFormat(string.Format(CCResources.ConfigSpecSelectBranch, BranchVersionString));
                configSpecRule.AppendFormat(string.Format(CCResources.ConfigSpecCreateBranch, BranchName));
            }

            foreach (string vob in VobList)
            {
                configSpecRule.AppendFormat(CCResources.ConfigSpecLoadRule, vob);
            }

            SetDefaultConfigSpec(configSpecRule.ToString());
        }

        /// <summary>
        /// Set the config spec to add the "time 000:00:00" used by snapshot start time.
        /// </summary>
        /// <param name="snapshotStartTime"></param>
        public void SetConfigSpecForSnapshotStartPoint(DateTime snapshotStartTime)
        {
            if (snapshotStartTime == DateTime.MinValue)
            {
                return;
            }

            string newConfigSpecPath = Path.Combine(Path.GetDirectoryName(Path.GetTempFileName()), "NewConfigSpec.txt");

            //Fire the cleartool command to cat config spec
            string cmdOutput = ExecuteClearToolCommand(ClearToolCommand.catcs);

            try
            {
                using (StreamWriter sw = new StreamWriter(newConfigSpecPath))
                {
                    // Add some text to the file.
                    sw.WriteLine(string.Format("time {0}", snapshotStartTime.ToString("dd-MMM-yyyy.HH:mm:ss")));
                    using (StringReader sr = new StringReader(cmdOutput))
                    {
                        while (sr.Peek() >= 0)
                        {
                            sw.WriteLine(sr.ReadLine());
                        }
                    }
                }
            }
            catch (IOException)
            {
                throw;
            }

            string setConfigSpecCmd = string.Format(ClearToolCommand.setcs, newConfigSpecPath);
            ExecuteClearToolCommand(setConfigSpecCmd);
        }

        /// <summary>
        /// Reset the config spec to remove the "time 000:00:00" set by the snapshotstart time change.
        /// </summary>
        public void ResetConfigSpec()
        {
            string newConfigSpecPath = Path.Combine(Path.GetDirectoryName(Path.GetTempFileName()), "NewConfigSpec.txt");

            //Fire the cleartool command to cat config spec
            string cmdOutput = ExecuteClearToolCommand(ClearToolCommand.catcs);

            try
            {
                using (StreamWriter sw = new StreamWriter(newConfigSpecPath))
                {
                    using (StringReader sr = new StringReader(cmdOutput))
                    {
                        while (sr.Peek() >= 0)
                        {
                            string line = sr.ReadLine();
                            if (line.StartsWith("time"))
                            {
                                continue;
                            }
                            sw.WriteLine(line);
                        }
                    }
                }
            }
            catch (IOException)
            {
                throw;
            }

            string setConfigSpecCmd = string.Format(ClearToolCommand.setcs, newConfigSpecPath);
            ExecuteClearToolCommand(setConfigSpecCmd);
        }

        /// <summary>
        /// Initialize the clearcase server
        /// 1. Mount the Vob
        /// 2. Create the default view.
        /// 3. Create config spec for the view.
        /// </summary>
        public void Initialize()
        {
            // Create the default view
            if (UsePrecreatedView)
            {
                if (UseDynamicView)
                {
                    StartView(ViewName);
                }
                else
                {
                    Update(ViewRootLocalPath);
                }
            }
            else if (!IsViewExists(ViewName))
            {
                CreateNewView(ViewName, StorageLocation);
            }

            // Set current directory to the view's root path
            SetDefaultViewPath();

            if (!UsePrecreatedView)
            {
                createConfigSpec();
            }
        }

        /// <summary>
        /// Clean up the COM object hold by this ClearCaseServer object.
        /// </summary>
        private void cleanUp()
        {
            ApplicationClass = null;
            m_clearCaseTool = null;
        }

        /// <summary>
        /// Returns true if the specified view exists on the clearcase server
        /// </summary>
        /// <param name="viewName"></param>
        /// <returns></returns>
        internal bool IsViewExists(string viewName)
        {
            CCViews viewCollection = ApplicationClass.get_Views(false, string.Empty);

            foreach (CCView view in viewCollection)
            {
                if (view.TagName == viewName)
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Mount the specified Vob.
        /// </summary>
        /// <param name="vobName"></param>
        internal void MountVob(string vobName)
        {
            string mountVObCmd =
                string.Format(ClearToolCommand.mount, vobName);
            ExecuteClearToolCommand(mountVObCmd);
        }

        /// <summary>
        /// Set the current working director to the view's default path
        /// </summary>
        internal void SetDefaultViewPath()
        {
            string changeDirCmd = string.Format("cd {0}", ViewRootLocalPath);
            try
            {
                ExecuteClearToolCommand(changeDirCmd);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Sets defaule config spec for view
        /// </summary>
        /// <param name="configSpecRule">Spec rule</param>
        private void SetDefaultConfigSpec(string configSpecRule)
        {
            //Check for null input
            if (string.IsNullOrEmpty(configSpecRule))
            {
                throw new ArgumentNullException("configSpecRule");
            }

            string configSpecPath = GetDefaultConfigSpecPath(configSpecRule);

            //Form the command string for setting config spec
            string setConfigSpecCmd = string.Format(ClearToolCommand.setcs, configSpecPath);

            //Fire the cleartool command to set config spec
            ExecuteClearToolCommand(setConfigSpecCmd);
        }

        /// <summary>
        /// Add a new load rule of the specified pname into the current view's config spec.
        /// </summary>
        /// <param name="vobName"></param>
        public void AddLoadRuleToConfigSpec(string pName)
        {
            string newConfigSpec = ClearCaseConfigSpec.AddLoadRule(ClearCaseView.ConfigSpec, pName);
            ClearCaseView.ConfigSpec = newConfigSpec;
        }

        /// <summary>
        /// Update the loaded elements
        /// </summary>
        /// <param name="pName"></param>
        public void Update(string pName)
        {
            if (string.IsNullOrEmpty(pName))
            {
                return;
            }
            Debug.Assert(!UseDynamicView, "Clearcase dynamic view cannot be updated");
            string updateCommandString = string.Format(ClearToolCommand.update, pName);
            ExecuteClearToolCommand(updateCommandString);
        }

        /// <summary>
        /// Update a list of elements
        /// </summary>
        /// <param name="pNameList"></param>
        public void Update(List<string> pNameList)
        {
            if ((pNameList == null) || (pNameList.Count == 0))
            {
                return;
            }
            Debug.Assert(!UseDynamicView, "Clearcase dynamic view cannot be updated");
            StringBuilder pNameStringBuilder = new StringBuilder();
            foreach (string pName in pNameList)
            {
                pNameStringBuilder = pNameStringBuilder.Append(string.Format("'{0}' ", pName));
            }

            ExecuteClearToolCommand(string.Format(ClearToolCommand.update, pNameStringBuilder.ToString()));
        }

        /// <summary>
        /// Create view with specified name and default config spec
        /// </summary>
        /// <param name="viewName">Name of view</param>
        /// <param name="storageLocation">storage location name</param>
        public void CreateNewView(string viewName, string storageLocation)
        {
            //Form the mkview command
            string mkViewCommandString = string.Format(ClearToolCommand.mkviewSnapshot, viewName, ViewRootPath);
            ExecuteClearToolCommand(mkViewCommandString);
        }

        internal void RemoveView(string viewName, string storageLocation)
        {
            if (!UsePrecreatedView)
            {
                //Delete snapshot view
                string fullStoragePath = ClearCasePath.Combine(storageLocation, viewName);

                //Form the rmview command
                string rmViewCommandString = string.Format(ClearToolCommand.rmview, fullStoragePath);
                ExecuteClearToolCommand(rmViewCommandString);
            }
        }

        /// <summary>
        /// Given a view local path, return the absolute vob path.
        /// </summary>
        /// <param name="viewLocalPath"></param>
        /// <returns></returns>
        public string GetServerPathFromViewLocalPath(string viewLocalPath)
        {
            if (string.IsNullOrEmpty(viewLocalPath))
            {
                return null;
            }

            string viewRootPath = ViewRootPath;
            if (viewRootPath[viewRootPath.Length-1] == ClearCasePath.Separator)
            {
                viewRootPath = viewRootPath.Substring(0, viewRootPath.Length - 1);
            }
            if (ClearCasePath.IsSubItem(viewLocalPath, viewRootPath, false))
            {
                return viewLocalPath.Substring(viewRootPath.Length);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Given a server path, return the view local path.
        /// </summary>
        /// <param name="serverPath"></param>
        /// <returns></returns>
        public string GetViewLocalPathFromServerPath(string serverPath)
        {
            if (serverPath == null)
            {
                return null;
            }

            return ClearCasePath.Combine(ViewRootPath, serverPath);
        }

        public string GetCheckinPathFromServerPath(string serverPath)
        {
            return GetVobAbsolutePathFromRelativePath(serverPath);
        }

        public bool IsVob(string path)
        {
            if (VobList.Contains(path))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private string GetViewPath(string extendedPath, string versionPath, string datasourcePath)
        {
            //Check for null input parameters
            if (string.IsNullOrEmpty(extendedPath))
                throw new ArgumentNullException("extendedPath");

            if (string.IsNullOrEmpty(datasourcePath))
                throw new ArgumentNullException("datasourcePath");

            //Form the element path starting from vob name
            string vobPrefixedPath = string.Empty;
            string viewExtendedPath = string.Empty;

            extendedPath = extendedPath.TrimStart('\\');

            //if element path is not root folder
            if (ClearCasePath.Equals(extendedPath, ClearCasePath.VobRoot))
            {
                // s_elementPath = s_elementPath.TrimStart('.');

                string startStr = datasourcePath + '\\' + ViewName + datasourcePath;

                // In some cases extended path can contain datasource path
                if (extendedPath.StartsWith(startStr))
                {
                    if (string.IsNullOrEmpty(versionPath))
                    {
                        viewExtendedPath = extendedPath;
                    }
                    else
                    {
                        viewExtendedPath = ClearCasePath.CombinePathWithVersion(extendedPath, versionPath);
                    }

                    return viewExtendedPath;
                }
                else
                {
                    if (string.IsNullOrEmpty(versionPath))
                    {
                        vobPrefixedPath = datasourcePath + ClearCasePath.Separator + extendedPath;
                    }
                    else
                    {
                        vobPrefixedPath = ClearCasePath.CombinePathWithVersion(
                            datasourcePath + ClearCasePath.Separator + extendedPath,
                            versionPath);
                    }
                }
            }
            else //if root folder
            {
                //if root folder is entire VOB
                if (datasourcePath == ClearCasePath.GetVobName(datasourcePath))
                {
                    if (string.IsNullOrEmpty(versionPath))
                    {
                        vobPrefixedPath = datasourcePath + "\\.";
                    }
                    else
                    {
                        vobPrefixedPath = ClearCasePath.CombinePathWithVersion(
                            datasourcePath + "\\." ,
                            versionPath);
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(versionPath))
                    {
                        vobPrefixedPath = datasourcePath;
                    }
                    else
                    {
                        vobPrefixedPath = ClearCasePath.CombinePathWithVersion(datasourcePath, versionPath);
                    }
                }
            }
            viewExtendedPath = ViewRootPath + vobPrefixedPath;
            return viewExtendedPath;
        }

        internal string GetRootElementPath(string sourcePath)
        {
            if (UsePrecreatedView)
            {
                return ClearCasePath.Combine(ViewRootPath, sourcePath);
            }
            else
            {
                CCElement rootElement = queryCCElement(ClearCasePath.GetViewExtendedPath(ClearCasePath.VobRoot.ToString(), sourcePath, ViewName, StorageLocation));
                if (rootElement.Path.EndsWith(ClearCasePath.VobRoot.ToString()))
                {
                    return rootElement.Path.Substring(0, rootElement.Path.Length - ClearCasePath.VobRoot.ToString().Length);
                }
                else
                {
                    return rootElement.Path;
                }
            }
        }

        internal void analyzeHistoryRecord(CCHistoryRecord historyRecord)
        {
            throw new NotImplementedException("analyzeHistoryRecord");
        }

        public List<CCHistoryRecord> GetHistoryRecords(
            ReadOnlyCollection<MappingEntry> filters,
            DateTime since,
            bool writeHistoryRecordsFound)
        {
            List<CCHistoryRecord> historyRecordList = new List<CCHistoryRecord>();

            string extendedPath;
            string historyCmd;
            string cmdOutput = null;
            foreach (MappingEntry mapping in filters)
            {
                //Creates extended path for source folder.
                //Query from the parent of the mapped path unless the mapped path itself is a vob root.
                if (UsePrecreatedView)
                {
                    if (!ClearCasePath.IsVobRoot(mapping.Path))
                    {
                        extendedPath = ClearCasePath.GetFolderName(mapping.Path);
                    }
                    else
                    {
                        extendedPath = mapping.Path;
                    }
                    historyCmd = string.Format(
                    "lshistory -minor -since {0} -eventid -recurse -fmt \"{1}\" -pname {2}",
                    since.ToString(CCResources.ClearCaseDateTimeFormat),
                    ClearCaseCommandSpec.HistoryParserString,
                    extendedPath);
                }
                else
                {
                    if (!ClearCasePath.IsVobRoot(mapping.Path))
                    {
                        extendedPath = ClearCasePath.GetViewExtendedPath(".",
                            ClearCasePath.GetFolderName(mapping.Path), ViewName, StorageLocation);
                    }
                    else
                    {
                        extendedPath = ClearCasePath.GetViewExtendedPath(".", mapping.Path, ViewName, StorageLocation);
                    }
                    historyCmd = string.Format(
                    "lshistory -minor -since {0} -branch {1} -eventid -fmt \"{2}\" -pname {3}",
                    since.ToString(CCResources.ClearCaseDateTimeFormat),
                    BranchName,
                    ClearCaseCommandSpec.HistoryParserString,
                    extendedPath);
                }
                try
                {
                    cmdOutput = ExecuteClearToolCommand(historyCmd);
                }
                catch (COMException ce)
                {
                    COMExceptionResult comResult = CCTextParser.ProcessComException(ce);
                    if (comResult == COMExceptionResult.NotAccessible
                        || comResult == COMExceptionResult.BranchTypeNotFound
                        || comResult == COMExceptionResult.PathNotFound)
                    {
                        continue;
                    }
                    throw;
                }

                if (string.IsNullOrEmpty(cmdOutput))
                {
                    TraceManager.TraceInformation(string.Format("No history event was found under path {0}", extendedPath));
                }
                else
                {
                    string[] historyRows = ClearCaseCommandSpec.ParseHistoryTable(cmdOutput);
                    CCHistoryRecord historyRecord;
                    foreach (string historyRow in historyRows)
                    {
                        historyRecord = new CCHistoryRecord(historyRow);
                        if (Utils.IsOurChange(historyRecord))
                        {
                            continue;
                        }
                        if (writeHistoryRecordsFound)
                        {
                            WriteHistoryRecord(historyRecord);
                        }
                        historyRecordList.Add(historyRecord);
                    }
                }
            }

            return historyRecordList;
        }

        internal void WriteHistoryRecord(CCHistoryRecord historyRecord)
        {
            // Todo - verbose information to be deleted.
            TraceManager.TraceInformation("||{0} | {1} | {2} | {3} | {4} | {5} | {6} ", historyRecord.EventId, historyRecord.OperationType,
                historyRecord.OperationDescription, historyRecord.Comment, historyRecord.VersionTime, historyRecord.UserComment, historyRecord.VersionExtendedPath);
        }

        #region algorithms
        #endregion

        internal CCElement queryCCElement(string elementPath)
        {
            CCElement ccElement= null;
            try
            {
                ccElement = ApplicationClass.get_Element(elementPath);
            }
            catch (Exception)
            {
                throw ;
            }
            return ccElement;
        }

        /* Todo
        /// <summary>
        /// Traverse the version tree of the given element.
        /// </summary>
        /// <param name="element"></param>
        private void TraverseVersionTree(CCElement element)
        {
            bool mainBranchTraversed = m_startFromMiddle;

            // Re-intialize the buffer which contains all the parents
            // of the currentElement and all their branches.
            m_parentsAndTheirBranches = new Dictionary<string, Collection<CCBranchType>>();

            while (m_branchCollection.Count > 0 || !mainBranchTraversed)
            {
                CCBranch currentBranch = null;
                CCBranchType currentBranchType = null;

                // Traverse the main branch if the main branch has not been traversed.
                if (!mainBranchTraversed)
                {
                    currentBranchType = m_branchTypeCollection[ClearCasePath.MainBranchName];
                }
                else
                {
                    currentBranch = m_branchCollection[0];
                    m_branchCollection.RemoveAt(0);
                    currentBranchType = currentBranch.Type;
                }

                if (currentBranch != null)
                {
                    TraverseBranch(element, currentBranch.BranchPointVersion, currentBranch.Type);
                }
                else
                {
                    TraverseBranch(element, null, currentBranchType);
                }
            }

            m_startFromMiddle = false;
            m_traversedBranchTypes.Clear();
        }

        Todo,
         *
         * private void TraverseBranch(CCElement element, CCVersion branchPointVersion, CCBranchType branchType)
        {
            // Branch type is not listed.
            if (!m_branchTypeCollection.ContainsKey(branchType.Name))
            {
                return;
            }

            // Add the branchType which is being traversed to traversed list.
            m_traversedBranchTypes.Add(branchType);

            CCVersion currentVersion = null;

            string branchSelector = branchType.Name;

            if (m_startingVersion == null)
            {
                // Get the first version of the given element on the given branch.
                currentVersion = element.get_Version(ClearCasePath.CombineVersionExtendedPath(element.ExtendedPath, branchType.Name, "0"));
            }
            else
            {
                // Before starting with the next version make sure that
                // the processing for the last version which was added before
                // the crash is completed.
                UpdateBranchCollection(m_startingVersion, element);
                ProcessFolderVersion(m_startingVersion, element);

                // Get he next version in case the starting version is
                // not null as in case of crash recovery we need to get
                // the next version which to be traversed.
                currentVersion = GetNextVersion(m_startingVersion);
            }

            while (currentVersion != null)
            {
                // Add file/folder versions to the database
                bool versionAdded = AddVersion(
                    MigrationManager.CurrentMapping,
                    currentVersion,
                    element);

                // Update the collections of branches which need to
                // be traversed
                UpdateBranchCollection(currentVersion, element);

                if (versionAdded)
                {
                    // Get the details of the folder operations performed
                    // on this version
                    ProcessFolderVersion(
                        currentVersion,
                        element);

                    // Generate task for the extractor component
                    GenerateTask(currentVersion);
                }

                currentVersion = element.GetNextVersion(currentVersion);
            }
        }

        /// <summary>
        /// NOTE - Not implemented as of now.
        /// Gets the next version selected by the view for the
        /// specified version
        /// IMP - Consider case in which multiple branches sprout
        /// from a version.
        /// </summary>
        /// <returns>ClearCaseFileVersion object</returns>
        internal Version GetNextVersion(Version inputVersion)
        {
            if (inputVersion == null)
                throw new ArgumentNullException("inputVersion");

            ClearCaseFileVersion converterFileVersion = null;

            ClearCaseFileVersion ccInputVersion = inputVersion as ClearCaseFileVersion;

            string branchAbsolutePath = GetBranchAbsolutePath(inputVersion);

            CCVersion previousCCVersion = null;
            CCVersion nextCCVersion = null;

            try
            {
                if (ccInputVersion != null)
                {
                    //Get previous CCVersion for the specified input
                    previousCCVersion = ccInputVersion.CalVersion;
                }
                else
                {
                    //Get previous CCVersion for the specified input
                    previousCCVersion = ClearCaseHelper.GetCCVersion( this.ccFileElement, branchAbsolutePath, (int)inputVersion.VersionNo);
                }
            }
            catch (Exception dataExp)
            {
                //Todo
                return null;
            }

            // If input verison is not the latest version then
            // get the next version
            if (!previousCCVersion.IsLatest)
            {
                int nextVersionNumber = (int)inputVersion.VersionNo;
                nextVersionNumber++;

                while (nextVersionNumber <= previousCCVersion.Branch.LatestVersion.VersionNumber)
                {
                    try
                    {
                        nextCCVersion = GetCCVersion(this.ccFileElement, branchAbsolutePath, nextVersionNumber);
                        break;
                    }
                    catch (Exception)
                    {
                        // Todo DataNotAvailableException
                        //MigrationTrace.WriteTrace(
                        //    MigrationTraceLevel.Low,
                        //    string.Format(
                        //        CultureInfo.InvariantCulture,
                        //        "Version {0} does not exist for file {1}. " +
                        //        "Hence incrementating the version count number.",
                        //        new object[] { branchAbsolutePath + nextNo, this.Path }),
                        //    "ClearCaseFile.GetNextVersion");

                        nextVersionNumber++;
                    }
                }

                // If the nextCCVersion is not null then get the ClearCase
                // file version
                if (nextCCVersion != null)
                {
                    CCBranchType converterBranchType = m_branchTypeCollection[nextCCVersion.Branch.Type.Name];

                    try
                    {
                        converterFileVersion =
                            new ClearCaseFileVersion(
                                (uint)nextCCVersion.VersionNumber,
                                nextCCVersion.CreationRecord.Date,
                                nextCCVersion.Identifier,
                                converterBranchType,
                                this.Id,
                                this.Path,
                                nextCCVersion.CreationRecord.UserLoginName,
                                nextCCVersion.Comment,
                                nextCCVersion);
                    }
                    catch (Exception exp)
                    {
                        //Todo

                    }
                }
            }

            return converterFileVersion;
        }

        private void ProcessFolderVersion(Version version, CCElement element)
        {
            FolderVersion folderVersion = version as FolderVersion;
            if (folderVersion != null)
            {
                // Get all the folder operation and add all the
                // newly added files which are to be traversed in
                // the files to be traversed collection
                Collection<FolderOperation> operations = folderVersion.FolderOperations;

                foreach (FolderOperation operation in operations)
                {
                    RenameOperation renOperation =
                            operation as RenameOperation;

                    if (operation is AddOperation)
                    {
                        // Process add operation
                        ProcessAddOperation(operation, folderVersion, element);
                    }
                    else if (renOperation != null)
                    {
                        // Process rename operation
                        ProcessRenameOperation(renOperation, element);
                    }
                    else if (operation is DeleteOperation)
                    {
                        // Process the delete operation
                        ProcessDeleteOperation(operation);
                    }
                    else if (operation is NullOperation)
                    {
                        // Process the null operation
                        this.ProcessNullOperation(operation);
                    }
                }
            }
        }

        private void UpdateBranchCollection(Version currentVersion, CCElement element)
        {
            // Add all the branches which are on the current version
            // in the branches to be traversed collection
            // NOTE: It is assumed here that no branch will come out
            // of the same version
            foreach (Branch currentBranch in currentVersion.Branches)
            {
                // If the traversedBranchTypes already contains the
                // branch then ignore this branch and log an
                // error
                if (m_traversedBranchTypes.Contains(currentBranch.Type))
                {
                    string message =  string.Format(
                            CultureInfo.InvariantCulture,
                            CCResources.ErrorMultipleBranchInstance,
                            new object[] {
                                    element.ToString(),
                                    currentBranch.Type,
                                    currentVersion.ToString() });
                    throw new NotImplementedException();
                    continue;
                }

                m_branchCollection.Add(currentBranch);

                // Todo:
                // Add the branch in the branch version map this needs to be
                // done because suppose if extractor is adding the branch info
                // in branchversion map then if the tool is closed when the
                // traverser marks a branch as UnProcessed and the extractor has
                // not yet added the branch info in branch version map. In such
                // a case the GetPendingBranches() fn fails as it does not get
                // a branchpoint version from the DB.
                // AddBranch(curBranch, currentVersion, databaseServer);

                // Todo, mark the status of the branch as UnProcessed
                // as this branch needs to be traversed upon
            }
        }

        // Comment out for now.

        /// <summary>
        /// Gets collection of CCBranchType on specfied Vob path
        /// </summary>
        /// <returns>Collection of CCBranchType</returns>
        internal CCBranchTypes GetBranchTypes()
        {
            try
            {
                //Get the CCBranchTypes on specified vob
                CCBranchTypes branchTypes = m_vob.get_BranchTypes(false, false);
                return branchTypes;
            }
            catch (Exception ex)
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// Gets collection of ClearCaseBranchTypes on specified vob
        /// </summary>
        /// <returns>Dictionary of ClearCaseBranchTypes</returns>
        private void getBranchTypeCollection()
        {
            if (m_branchTypeCollection == null || m_branchTypeCollection.Count <= 0)
            {
                CCBranchTypes ccBranchTypes = GetBranchTypes();

                m_branchTypeCollection = new Dictionary<string, CCBranchType>();

                foreach (CCBranchType ccBranchType in ccBranchTypes)
                {
                    if (m_branchTypeCollection.ContainsKey(ccBranchType.Name))
                    {
                        continue;
                    }

                    CCBranchType branchType;
                    if (m_branches.Contains(ccBranchType.Name) || ccBranchType.Name == ClearCasePath.MainBranchName)
                    {
                        branchType = new CCBranchType(ccBranchType.Name, true);
                    }
                    else
                    {
                        branchType = new CCBranchType(ccBranchType.Name, false);
                    }
                }
            }
        }*/

        /// <summary>
        /// Starts the specified view
        /// </summary>
        /// <param name="viewName">Name of the view.</param>
        private void StartView(string viewName)
        {
            if (string.IsNullOrEmpty(viewName))
                throw new ArgumentNullException("viewName");

            string cmd = string.Format(ClearToolCommand.startview, viewName);
            ExecuteClearToolCommand(cmd);
        }

        /// <summary>
        /// Find symbolic links of a vob and store them in the supplied hashset.
        /// </summary>
        /// <param name="vob">Vob to be searched for.</param>
        /// <param name="symbolicLinks">List for symbolic links found.</param>
        public void FindSymbolicLink(string vob, HashSet<string> symbolicLinks)
        {
            if (symbolicLinks == null)
            {
                throw new ArgumentNullException("symbolicLinks");
            }
            if (string.IsNullOrEmpty(vob))
            {
                throw new ArgumentNullException("vob");
            }

            string findOutput = ExecuteClearToolCommand(string.Format(ClearToolCommand.findSymbolicLink, ClearCasePath.MakeRelative(vob)));

            if (string.IsNullOrEmpty(findOutput))
            {
                return;
            }

            string outputLine;
            using (StringReader outputReader = new StringReader(findOutput))
            {
                while (true)
                {
                    outputLine = outputReader.ReadLine();
                    if (outputLine == null)
                    {
                        break;
                    }
                    else
                    {
                        // Todo verify it is a valid path
                        if (!symbolicLinks.Contains(outputLine))
                        {
                            symbolicLinks.Add(outputLine);
                        }
                    }
                }
            }
        }

        private static string GetDefaultConfigSpecPath(string specRule)
        {
            string configSpecPath = string.Empty;

            // Create a temp file to hold the default config spec
            try
            {
                configSpecPath = Path.Combine(Path.GetDirectoryName(Path.GetTempFileName()), "ConfigSpec.txt");
                using (StreamWriter sw = new StreamWriter(configSpecPath))
                {
                    // Add some text to the file.
                    sw.Write(specRule);
                }
            }
            catch (IOException)
            {
                throw;
            }

            return configSpecPath;
        }

        /// <summary>
        /// Execute a clearcase command.
        /// </summary>
        /// <param name="commandString"></param>
        /// <returns></returns>
        public string ExecuteClearToolCommand(string commandString)
        {
            string commandOutput = string.Empty;

            try
            {
                commandOutput = m_clearCaseTool.CmdExec(commandString);
                return commandOutput;
            }
            catch (Exception)
            {
                throw ;
            }
        }

        /// <summary>
        /// Exceutes a command by forking a new process
        /// Some command cannot be executed from ClearToolClass object.
        /// </summary>
        /// <param name="cmdString">command string to be executed</param>
        /// <param name="isError">bool indicating if the command execution
        /// resulted in an error</param>
        /// <returns>output string</returns>
        internal static string ExecuteCommand(string cmdString, out bool isError)
        {
            //Check for null input
            if (string.IsNullOrEmpty(cmdString))
                throw new ArgumentNullException("cmdString");

            // /C carries out command from within cmd shell and then terminates
            cmdString = string.Format("/c {0}", cmdString);
            string output = string.Empty;
            isError = false;
            string errorString;

            try
            {
                using (Process process = new Process())
                {
                    ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", cmdString);
                    processStartInfo.UseShellExecute = false;
                    processStartInfo.RedirectStandardError = true;
                    processStartInfo.CreateNoWindow = true;
                    process.StartInfo = processStartInfo;
                    process.Start();

                    StreamReader errorStreamReader = process.StandardError;

                    // Read the standard output of the spawned process.
                    errorString = errorStreamReader.ReadToEnd();
                    errorStreamReader.Close();

                }
                if (errorString.Length > 0)
                {
                    isError = true;
                    output = errorString;
                }

                return output;
            }
            catch (Exception)
            {
                throw;
            }
        }
        internal static Dictionary<string,ClearfsimportResult> ExecuteClearfsimportCommand(string cmdString)
        {
            if (string.IsNullOrEmpty(cmdString))
            {
                throw new ArgumentNullException("cmdString");
            }
            // /C carries out command from within cmd shell and then terminates
            cmdString = string.Format("/c {0}", cmdString);

            s_clearfsimportOutput.Clear();
            s_clearfsimportErrorOutput.Clear();
            try
            {
                using (Process process = new Process())
                {
                    ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", cmdString);
                    processStartInfo.UseShellExecute = false;
                    processStartInfo.RedirectStandardError = true;
                    processStartInfo.RedirectStandardOutput = true;
                    processStartInfo.CreateNoWindow = true;
                    process.StartInfo = processStartInfo;
                    process.OutputDataReceived += new DataReceivedEventHandler(ClearfsimportDataOutputHandler);
                    process.ErrorDataReceived += new DataReceivedEventHandler(ClearfsimportDataErrorHandler);
                    process.Start();

                    // Read the standard output of the spawned process.
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    process.WaitForExit();
                    process.Close();
                }
                if (s_clearfsimportErrorOutput.Count > 0)
                {
                    // We just write a trace error here.
                    // CC adapter uses s_clearfsimportOutput to determine whether an import is successful or not.
                    foreach (string errorLine in s_clearfsimportErrorOutput)
                    {
                        TraceManager.TraceError("Clearfsimport error: {0}", errorLine);
                    }
                }

                return s_clearfsimportOutput;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Generate a label for CC adapter check ins.
        /// </summary>
        /// <param name="changeGroupId"></param>
        /// <returns></returns>
        internal static string GenerateCheckinLabelType(long changeGroupId)
        {
            return string.Format(CCResources.CheckinLabelFormat, DateTime.Now);
        }

        private static void ClearfsimportDataOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
        {
            TraceManager.TraceVerbose(outLine.Data);
            bool addEntry = false;
            if (!string.IsNullOrEmpty(outLine.Data))
            {
                if (outLine.Data.StartsWith("Creating directory \"", StringComparison.Ordinal))
                {
                    s_elementPath = outLine.Data.Substring(20);
                    Debug.Assert(s_elementPath.Length > 2, "Error element path");
                    s_elementPath = s_elementPath.Substring(0, s_elementPath.Length -2);
                    s_previousState = ClearfsimportResult.CreateDirectory;
                    addEntry = true;
                }
                else if (outLine.Data.StartsWith("Validating directory \"", StringComparison.Ordinal))
                {
                    s_elementPath = outLine.Data.Substring(22);
                    Debug.Assert(s_elementPath.Length > 2, "Error element path");
                    s_elementPath = s_elementPath.Substring(0, s_elementPath.Length - 2);
                    s_previousState = ClearfsimportResult.ValidatingDirectory;
                    addEntry = true;
                }
                else if (outLine.Data.StartsWith("Creating element \"", StringComparison.Ordinal))
                {
                    s_elementPath = outLine.Data.Substring(18);
                    Debug.Assert(s_elementPath.Length > 2, "Error element path");
                    s_elementPath = s_elementPath.Substring(0, s_elementPath.Length - 2);
                    s_previousState = ClearfsimportResult.CreateElement;
                    addEntry = true;
                }
                else if (outLine.Data.StartsWith("Validating element \"", StringComparison.Ordinal))
                {
                    s_elementPath = outLine.Data.Substring(20);
                    Debug.Assert(s_elementPath.Length > 2, "Error element path");
                    s_elementPath = s_elementPath.Substring(0, s_elementPath.Length - 2);
                    s_previousState = ClearfsimportResult.ValidatingElement;
                }
                else if ((outLine.Data.StartsWith("Created branch \"", StringComparison.Ordinal))
                    && (s_previousState == ClearfsimportResult.ValidatingElement))
                {
                    s_previousState = ClearfsimportResult.UpdateElement;
                    addEntry = true;
                }
                else if ((outLine.Data.StartsWith("    update version \"", StringComparison.Ordinal))
                    && (s_previousState == ClearfsimportResult.ValidatingElement))
                {
                    s_previousState = ClearfsimportResult.UpdateElement;
                    addEntry = true;
                }
                else if ((outLine.Data.StartsWith("    Skipping element \"", StringComparison.Ordinal))
                    && (s_previousState == ClearfsimportResult.ValidatingElement))
                {
                    s_previousState = ClearfsimportResult.UpdateElement;
                    addEntry = true;
                }
                else
                {
                    s_elementPath = string.Empty;
                }

                if (addEntry)
                {
                    if (s_clearfsimportOutput.ContainsKey(s_elementPath))
                    {
                        TraceManager.TraceInformation(string.Format("Item {0} already added to the clearfsimport output", s_elementPath));
                    }
                    else
                    {
                        s_clearfsimportOutput.Add(s_elementPath, s_previousState);
                    }
                }
            }
        }

        private static void ClearfsimportDataErrorHandler(object sendingProcess, DataReceivedEventArgs outLine)
        {
            if (!string.IsNullOrEmpty(outLine.Data))
            {
                string errorLine = CCTextParser.ParseClearfsimportErrorOutput(outLine.Data);
                if (!string.IsNullOrEmpty(errorLine))
                {
                    s_clearfsimportErrorOutput.Add(errorLine);
                }
            }
        }
    }
}


text:
package au.com.breakpoint.hedron.core.context;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import au.com.breakpoint.hedron.core.context.ExecutionScope;
import au.com.breakpoint.hedron.core.context.IScope;
import au.com.breakpoint.hedron.core.context.ThreadContext;

public class ExecutionScopeTest
{
    @Test
    public void testNestedExecutionScopeContextId ()
    {
        for (int i = 0; i < 4; ++i)
        {
            try (IScope scopeOuter = new ExecutionScope ())
            {
                final String contextIdOuter = ThreadContext.getContextId ();
                System.out.printf ("contextId0   %s%n", contextIdOuter);
                assertEquals (contextIdOuter, ThreadContext.getContextId ());

                for (int j = 0; j < 2; ++j)
                {
                    try (IScope scopeInner = new ExecutionScope ())
                    {
                        final String contextIdInner = ThreadContext.getContextId ();
                        System.out.printf ("contextId01  %s%n", contextIdInner);
                        assertTrue (!contextIdOuter.equals (contextIdInner));

                        for (int k = 0; k < 3; ++k)
                        {
                            try (IScope scopeInnerInner = new ExecutionScope ())
                            {
                                final String contextIdInnerInner = ThreadContext.getContextId ();
                                System.out.printf ("contextId012 %s%n", contextIdInnerInner);
                                assertTrue (!contextIdInner.equals (contextIdInnerInner));
                                assertTrue (!contextIdOuter.equals (contextIdInnerInner));
                            }
                        }

                    }
                }
            }

            // No scope left.
            assertEquals ("{}", ThreadContext.getContextId ());
        }
    }
}