GameVersionAnimation* GameVersionAnimation::initWithType()
{
	auto animation = Animation::create();
	animation->setDelayPerUnit(0.15f);

	String spriteFrameName;
	String frameName;
	spriteFrameName = String("Headline_two_1-hd.png");
	for (int i = 1; i <= 6; i++)
	{

		frameName = String(String::createWithFormat("Headline_two_%d-hd.png", i)->getCString());
		SpriteFrame *frame;
		frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(frameName.getCString());
		animation->addSpriteFrame(frame);
	}
	if (this->initWithSpriteFrameName(spriteFrameName.getCString())){
		this->setRotation(-12);
		auto animateAction = RepeatForever::create(Animate::create(animation));
		this->runAction(animateAction);
		auto rotate1 = RotateBy::create(2, 24);
		auto rotate2 = RotateBy::create(2, -24);
		auto rotation = Sequence::createWithTwoActions(rotate1, rotate2);
		this->runAction(rotation);
	}

	return this;
}
TableViewCell* TableViewTestLayer::tableCellAtIndex(TableView *table, unsigned int idx)
{
    String *string = String::createWithFormat("%d", idx);
    TableViewCell *cell = table->dequeueCell();
    if (!cell) {
        cell = new CustomTableViewCell();
        cell->autorelease();
        Sprite *sprite = Sprite::create("Images/Icon.png");
        sprite->setAnchorPoint(PointZero);
        sprite->setPosition(ccp(0, 0));
        cell->addChild(sprite);

        LabelTTF *label = LabelTTF::create(string->getCString(), "Helvetica", 20.0);
        label->setPosition(PointZero);
		label->setAnchorPoint(PointZero);
        label->setTag(123);
        cell->addChild(label);
    }
    else
    {
        LabelTTF *label = (LabelTTF*)cell->getChildByTag(123);
        label->setString(string->getCString());
    }


    return cell;
}
Example #3
0
String operator+( String& a, String& b)
{
	String c;
	c += a.getCString();
	c += b.getCString();
	return c;
}
Example #4
0
void CIMExportClient::exportIndication(
   const String& url,
   const CIMInstance& instanceName,
   const ContentLanguageList& contentLanguages)
{
    PEG_METHOD_ENTER (TRC_EXPORT_CLIENT, "CIMExportClient::exportIndication()");

    try
    {
        // encode request
        CIMRequestMessage* request = new CIMExportIndicationRequestMessage(
            String::EMPTY,
            url,
            instanceName,
            QueueIdStack(),
            String::EMPTY,
            String::EMPTY);

        request->operationContext.set
            (ContentLanguageListContainer(contentLanguages));

        PEG_TRACE ((TRC_INDICATION_GENERATION, Tracer::LEVEL4,
            "Exporting %s Indication for destination %s:%d%s",
            (const char*)(instanceName.getClassName().getString().
            getCString()),
            (const char*)(_connectHost.getCString()), _connectPortNumber,
            (const char*)(url.getCString())));

        Message* message = _doRequest(request,
            CIM_EXPORT_INDICATION_RESPONSE_MESSAGE);

        PEG_TRACE ((TRC_INDICATION_GENERATION, Tracer::LEVEL4,
            "%s Indication for destination %s:%d%s exported successfully",
            (const char*)(instanceName.getClassName().getString().
            getCString()),
            (const char*)(_connectHost.getCString()), _connectPortNumber,
            (const char*)(url.getCString())));

        CIMExportIndicationResponseMessage* response =
            (CIMExportIndicationResponseMessage*)message;

        AutoPtr<CIMExportIndicationResponseMessage> ap(response);
    }
    catch (const Exception& e)
    {
        PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1,
            "Failed to export indication: %s",
            (const char*)e.getMessage().getCString()));
        throw;
    }
    catch (...)
    {
        PEG_TRACE_CSTRING (TRC_DISCARDED_DATA, Tracer::LEVEL1,
            "Failed to export indication");
        throw;
    }
    PEG_METHOD_EXIT();
}
Example #5
0
void WarLayer::setLabelWarContent(String content) {
	if (label_war_content != NULL) {
		label_war_content->setString(content.getCString());
		return;
	}
	label_war_content = Label::createWithTTF(content.getCString(), "fonts/Marker Felt.ttf", WAR_CONTENT_SIZE);
	label_war_content->setTextColor(Color4B::WHITE);
	label_war_content->setPosition(0, -10);
	this->addChild(label_war_content, 2);
}
Example #6
0
void WarLayer::setLabelWarTitle(String title) {
	if (label_war_title != NULL) {
		label_war_title->setString(title.getCString());
		return;
	}
	//label_war_title = Label::createWithTTF(title, "fonts/Marker Felt.ttf", WAR_SIZE);
	label_war_title = Label::createWithTTF(title.getCString(), "fonts/Marker Felt.ttf", WAR_TITLE_SIZE);
	label_war_title->setTextColor(Color4B::ORANGE);
	label_war_title->setPosition(Point(0, 30));
	this->addChild(label_war_title, 2);
}
Example #7
0
void PopupLayer::buttonCallback(cocos2d::CCObject *pSender){
    CCNode* node = dynamic_cast<CCNode*>(pSender);
	int tag = node->getTag();
	//quit
	if(tag == 40)
	{
		#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
			MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
			return;
		#endif

			Director::getInstance()->end();

		#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
			exit(0);
		#endif
	}
	//resume
	else if (tag == 41)
	{
		node->getParent()->getParent()->getParent()->resume();
	}
	//restart
	else if(tag == 42)
	{
		GameMain::score = 0;
		GameMain::gravity = 0;
		ui::TextAtlas* score_lbl = (ui::TextAtlas*)(node->getParent()->getParent()->getParent()->getChildByTag(1)->getChildByTag(5)->getChildByTag(2));
		String* s = String::createWithFormat("%d", GameMain::score*5);
		score_lbl->setStringValue(s->getCString());
		ui::LoadingBar* score_bar = (ui::LoadingBar* )(node->getParent()->getParent()->getParent()->getChildByTag(1)->getChildByTag(5)->getChildByTag(1));
		score_bar->setPercent(GameMain::score*5);
		node->getParent()->getParent()->getParent()->resume();
	}
	//next
	else if (tag == 43)
	{
		GameMain::score = 0;
		GameMain::gravity = 0;
		ui::TextAtlas* score_lbl = (ui::TextAtlas*)(node->getParent()->getParent()->getParent()->getChildByTag(1)->getChildByTag(5)->getChildByTag(2));
		String* s = String::createWithFormat("%d", GameMain::score*5);
		score_lbl->setStringValue(s->getCString());
		GameMain::page+=2;
		ui::LoadingBar* score_bar = (ui::LoadingBar* )(node->getParent()->getParent()->getParent()->getChildByTag(1)->getChildByTag(5)->getChildByTag(1));
		score_bar->setPercent(GameMain::score*5);
		node->getParent()->getParent()->getParent()->resume();
	}
    this->removeFromParent();
}
void TileMapAtlas::updateAtlasValues()
{
    CCAssert( _TGAInfo != NULL, "tgaInfo must be non-nil");

    int total = 0;

    for(int x=0;x < _TGAInfo->width; x++ ) 
    {
        for( int y=0; y < _TGAInfo->height; y++ ) 
        {
            if( total < _itemsToRender ) 
            {
                ccColor3B *ptr = (ccColor3B*) _TGAInfo->imageData;
                ccColor3B value = ptr[x + y * _TGAInfo->width];

                if( value.r != 0 )
                {
                    this->updateAtlasValueAt(ccp(x,y), value, total);

                    String *key = String::createWithFormat("%d,%d", x,y);
                    Integer *num = Integer::create(total);
                    _posToAtlasIndex->setObject(num, key->getCString());

                    total++;
                }
            }
        }
    }
}
DynamicLibrary::LIBRARY_SYMBOL DynamicLibrary::getSymbol(const String & symbolName)
{
    LIBRARY_SYMBOL func = 0;

    if(isLoaded())
    {
        CString cstr = symbolName.getCString();

        if(shl_findsym((shl_t *)&_handle, cstr, TYPE_UNDEFINED, &func) == 0)
        {
            return(func);
        }

        // NOTE: should the underscore be prepended by the caller or should
        // this be a compile time option?

        cstr = String(String("_") + symbolName).getCString();

        if(shl_findsym((shl_t *)_handle, cstr, TYPE_UNDEFINED, &func) == 0)
        {
            return(func);
        }
    }

    return(0);
}
Example #10
0
PEGASUS_NAMESPACE_BEGIN


//////////////////////////////////////////
//
//   IPV4NetInformation methods
//
//////////////////////////////////////////

void IPV4NetInformation::ParseDottedQuad(String const &quad_string,
        validated<dottedquad_t> *quad) const
{
    int int_octets[4];
    int fields, i;
    dottedquad_t byte_octets;

    fields = sscanf(quad_string.getCString(), "%d.%d.%d.%d",
                    &int_octets[0], &int_octets[1],
                    &int_octets[2], &int_octets[3]);


    if (fields != 4)
        return;

    for (i = 0; i < 4; i++) {
        if (int_octets[i] < 0 || int_octets[i] > 255)
            return;
        byte_octets.octets[i] = (unsigned char) int_octets[i];
    }

    /* If we make it here, we have a valid dotted quad, set the value on the
     * validated type. */
    quad->setValue(byte_octets);
}
Example #11
0
Boolean FileSystem::compareFiles(
    const String& path1,
    const String& path2)
{
    Uint32 fileSize1;

    if (!getFileSize(path1, fileSize1))
        throw CannotOpenFile(path1);

    Uint32 fileSize2;

    if (!getFileSize(path2, fileSize2))
        throw CannotOpenFile(path2);

    if (fileSize1 != fileSize2)
        return false;

    FILE* fp1 = fopen(path1.getCString(), "rb");

    if (fp1 == NULL)
        throw CannotOpenFile(path1);

    FILE* fp2 = fopen(path2.getCString(), "rb");

    if (fp2 == NULL)
    {
        fclose(fp1);
        throw CannotOpenFile(path2);
    }

    int c1;
    int c2;

    while ((c1 = fgetc(fp1)) != EOF && (c2 = fgetc(fp2)) != EOF)
    {
        if (c1 != c2)
        {
            fclose(fp1);
            fclose(fp2);
            return false;
        }
    }

    fclose(fp1);
    fclose(fp2);
    return true;
}
KDvoid SampleLayer::addCharacter ( KDvoid )
{
	// plist 에서 달리기 애니매이션 로딩
	SpriteFrameCache*	pFrameCache = SpriteFrameCache::getInstance ( );
	pFrameCache->addSpriteFramesWithFile ( "ch01.plist" );

	Dictionary*		pDictionary = Dictionary::createWithContentsOfFile ( "ch01_1_aniinfo.plist" );
	Array*			pAnimationList = (Array*) pDictionary->objectForKey ( "animationlist" );
	Array*			pFrameList = (Array*) pDictionary->objectForKey ( "framelist" );
	String*			pName = (String*) pDictionary->objectForKey ( "name" );
	String*			pTexture = (String*) pDictionary->objectForKey ( "texture" );
	String*			pType = (String*) pDictionary->objectForKey ( "type" );

	Dictionary*		pAnimationItem = (Dictionary*) pAnimationList->getObjectAtIndex ( 12 );

	Array*			pTemp = (Array*) pAnimationItem->objectForKey ( "FrameList" );
	KDfloat			fTemp = ( (String*) pAnimationItem->objectForKey ( "FPS" ) )->floatValue ( );

	Array*			pArraySpriteFrame = Array::createWithCapacity ( pTemp->count ( ) );

	Animation*		pAnimation = Animation::create ( );

	for ( KDint32 i = 0; i < pTemp->count ( ); i++ )
	{
		KDint		ii = ( (String*) pTemp->getObjectAtIndex ( i ) )->intValue ( );
		String*		pString = (String*) pFrameList->getObjectAtIndex ( ii );
		pAnimation->addSpriteFrame ( pFrameCache->getSpriteFrameByName ( pString->getCString ( ) ) );
	}
	pAnimation->setDelayPerUnit ( fTemp );

	Sprite*			pSprite = Sprite::createWithSpriteFrameName ( ( (String*) pFrameList->getObjectAtIndex ( 21 ) )->getCString ( ) );
	Point			tPoint = Point ( Point ( 100, 200 ) );
	Point tOffset = pSprite->getDisplayFrame ( )->getOffset ( );
	pSprite->setPosition ( tPoint - tOffset );
	
	pSprite->runAction ( RepeatForever::create ( Animate::create ( pAnimation ) ) );
	pSprite->setTag ( 10 );
	this->addChild ( pSprite );

	// Box2D body setting
	b2BodyDef		tBodyDef;
	tBodyDef.type = b2_dynamicBody;
	tBodyDef.position.Set ( tPoint.x / PTM_RATIO, tPoint.y / PTM_RATIO );
	tBodyDef.userData = pSprite;

	b2PolygonShape	tDynamicBox;
	Size tSize = pSprite->getDisplayFrame ( )->getRect ( ).size;
	tDynamicBox.SetAsBox ( tSize.width / 2 / PTM_RATIO, tSize.height / 2 / PTM_RATIO );

	m_pBody = m_pWorld->CreateBody ( &tBodyDef );

	b2FixtureDef	tFixtureDef;
	tFixtureDef.shape = &tDynamicBox;
	tFixtureDef.density = 1.0f;
	tFixtureDef.friction = 0.0f;

	m_pBody->CreateFixture ( &tFixtureDef );
}
//
// Perform http authentication
//
AuthenticationStatus AuthenticationManager::performHttpAuthentication(
    const String& authHeader,
    AuthenticationInfo* authInfo)
{
    PEG_METHOD_ENTER(TRC_AUTHENTICATION,
        "AuthenticationManager::performHttpAuthentication()");

    String authType;
    String cookie;

    //
    // Parse the HTTP authentication header for authentication information
    //
    if ( !HTTPMessage::parseHttpAuthHeader(authHeader, authType, cookie) )
    {
        PEG_TRACE((
            TRC_DISCARDED_DATA,
            Tracer::LEVEL1,
            "HTTPAuthentication failed. "
                "Malformed HTTP authentication header: %s",
            (const char*)authHeader.getCString()));
        PEG_METHOD_EXIT();
        return AuthenticationStatus(AUTHSC_UNAUTHORIZED);
    }

    AuthenticationStatus authStatus(AUTHSC_UNAUTHORIZED);

    //
    // Check the authenticationinformation and do the authentication
    //
    if ( String::equalNoCase(authType, "Basic") &&
         String::equal(_httpAuthType, "Basic") )
    {
        authStatus = _httpAuthHandler->authenticate(cookie, authInfo);
    }
#ifdef PEGASUS_NEGOTIATE_AUTHENTICATION
    else if ( String::equalNoCase(authType, "Negotiate") &&
              String::equal(_httpAuthType, "Negotiate") )
    {
        authStatus = _httpAuthHandler->authenticate(cookie, authInfo);
    }
#endif
    // FUTURE: Add code to check for "Digest" when digest
    // authentication is implemented.

    if ( authStatus.isSuccess() )
    {
        authInfo->setAuthType(authType);
    }

    PEG_METHOD_EXIT();

    return authStatus;
}
Example #14
0
/**
 *加载地图
*/
void HelloWorld::loadMap(const std::string& mapName)
{
    String* mapXml = String::createWithContentsOfFile("gamemap.tmx");
    m_gamemap = TMXTiledMap::createWithXML(mapXml->getCString(), "");
    assert(m_gamemap);
    TMXLayer* layer = m_gamemap->layerNamed("block");
    if (layer != NULL)
        layer->setVisible(false);

    this->addChild(m_gamemap);
}
Example #15
0
//------------------------------------------------------------------------------
// FUNCTION: isHostAddress
//
// REMARKS: Verify if host is address
//
// PARAMETERS:  [IN] host -> string containing the host name or address
//
// RETURN: TRUE if host address, FALSE otherwise
//------------------------------------------------------------------------------
Boolean NTPService::isHostAddress(String host) {
    int ps;
    String strValue;
    Boolean ok = false;
    
    ps = host.find(".");
    if(ps > 0) {
        strValue.assign(host.subString(0, ps - 1));
        ok = (atoi(strValue.getCString()) > 0);
    }
    return ok;
}
Example #16
0
PEGASUS_NAMESPACE_BEGIN

// Clone the path as a C String but discard trailing slash if any:

static CString _clonePath(const String& path)
{
    String clone = path;

    if (clone.size() && clone[clone.size()-1] == '/')
        clone.remove(clone.size()-1);

    return clone.getCString();
}
Example #17
0
int IPV4IFInformation::SetInterrupt(String const &interrupt_string)
{
    char *eptr;
    CString p;
    Uint32 int_hold;

    p = interrupt_string.getCString();
    int_hold = strtoul(p, &eptr, 10);

    if (*eptr == 0) {
        interrupt.setValue(int_hold);
        return 0;
    } else {
        return -1;
    }
}
Example #18
0
int IPV4IFInformation::SetMTU(String const &mtu_string)
{
    char *eptr;
    Uint32 hold_mtu;

    CString p;
    p = mtu_string.getCString();
    hold_mtu = strtoul(p, &eptr, 10);

    if (*eptr == 0) {
        mtu.setValue(hold_mtu);
        return 0;
    } else {
        return -1;
    }
}
Example #19
0
String WsmUtils::getRootResourceUri(const String& resourceUri)
{
    CString cstr(resourceUri.getCString());
    const char* start = cstr;
    const char* end = skipHostUri(start);
    const size_t n = sizeof(WSM_RESOURCEURI_CIMSCHEMAV2_SUFFIX) - 1;

    if (strncmp(end, WSM_RESOURCEURI_CIMSCHEMAV2_SUFFIX, n) == 0)
    {
        end += n;
        return String(start, end - start);
    }

    const int NS = WsmNamespaces::WS_CIM_SCHEMA;
    return String(WsmNamespaces::supportedNamespaces[NS].extendedName);
}
Example #20
0
int IPV4IFInformation::SetBaseAddr(String const &base_address_string)
{
    char *eptr;
    CString p;
    Uint32 hold_base;

    p = base_address_string.getCString();
    hold_base = strtoul(p, &eptr, 16);

    if (*eptr == 0) {
        base_address.setValue(hold_base);
        return 0;
    } else {
        return -1;
    }
}
Example #21
0
//------------------------------------------------------------------------------
// FUNCTION: getHostAddress
//
// REMARKS: Resolves address servers
//
// PARAMETERS:  [IN] serverName     -> string containing the name server
//                [OUT] serverAddress -> string that will contain the IP server
//
// RETURN: TRUE if valid host name, FALSE otherwise
//------------------------------------------------------------------------------
Boolean NTPService::getHostAddress(String serverName, String & serverAddress) 
{
    Boolean ok = false;
    int ps, value = 0;
    String strValue;
    struct hostent *host;
    struct in_addr ia;
    
    serverAddress.clear();
    host = gethostbyname(serverName.getCString());
    if(host != NULL) 
    {
        ia = *(struct in_addr *)(host->h_addr);
        serverAddress.assign(inet_ntoa(ia));
        ok = true;
    }
    return ok;
}    
//
// Perform pegasus sepcific local authentication
//
AuthenticationStatus AuthenticationManager::performPegasusAuthentication(
    const String& authHeader,
    AuthenticationInfo* authInfo)
{
    PEG_METHOD_ENTER(TRC_AUTHENTICATION,
        "AuthenticationManager::performPegasusAuthentication()");

    AuthenticationStatus authStatus(AUTHSC_UNAUTHORIZED);

    String authType;
    String userName;
    String cookie;

    //
    // Parse the pegasus authentication header authentication information
    //
    if ( !HTTPMessage::parseLocalAuthHeader(authHeader,
              authType, userName, cookie) )
    {
        PEG_TRACE((
            TRC_DISCARDED_DATA,
            Tracer::LEVEL1,
            "PegasusAuthentication failed. "
                "Malformed Pegasus authentication header: %s",
            (const char*)authHeader.getCString()));
        PEG_METHOD_EXIT();
        return AuthenticationStatus(AUTHSC_UNAUTHORIZED);
    }

    // The HTTPAuthenticatorDelegator ensures only local authentication
    // requests get here.
    PEGASUS_ASSERT(authType == "Local");

    authStatus = _localAuthHandler->authenticate(cookie, authInfo);

    if ( authStatus.isSuccess() )
    {
        authInfo->setAuthType(authType);
    }

    PEG_METHOD_EXIT();

    return authStatus;
}
Example #23
0
bool AlienLayer::initWithPlist(const char* plist, const char* frameName)
{
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plist);
	
	if(sprtfrm_Alien = SpriteFrameCache::getInstance()->getSpriteFrameByName(frameName))
	{
		sprt_Alien = Sprite::createWithSpriteFrame(sprtfrm_Alien);
		addChild(sprt_Alien, 1);

		// Alien's Animation
		Array* animFrames = Array::createWithCapacity(3);

		for(int i = 1; i < 4; i++) 
		{
			String* strAlien = String::createWithFormat("chorogging%d.png", i);
			SpriteFrame* frame = SpriteFrameCache::getInstance()->getSpriteFrameByName( strAlien->getCString() );
			animFrames->addObject(frame);
		}

		auto animation = Animation::createWithSpriteFrames(animFrames, 0.3f);
		sprt_Alien->runAction( RepeatForever::create( Animate::create(animation) ) );

		// Get random x,y pos
		//posX = UtilFunc::getRandomRangeValue(cAlienGenPosXMin, cAlienGenPosXMax);
		int randXIdx = (rand() % 6);
		posX = cAlienGenPosX[randXIdx];

		int yPos = UtilFunc::getRandomRangeValue(cAlienGenPosY-100, cAlienGenPosY);
		setPosition(Point(posX, yPos));

		// Get random actualDuration
		//float actualDuration = UtilFunc::getRandomRangeValue(0.4f, 6.4f);
		float actualDuration = cAlienMoveSpeed[randXIdx];

		// Action
		actionSequenceTopToBottom(this, actualDuration);
	}

	return true;
}
Example #24
0
//------------------------------------------------------------------------------
// FUNCTION: getHostName
//
// REMARKS: Resolves name servers
//
// PARAMETERS:  [IN] serverAddress -> string containing the IP address
//                [OUT] hostName -> string that will contain the name server
//
// RETURN: TRUE if valid host IP, FALSE otherwise
//------------------------------------------------------------------------------
Boolean NTPService::getHostName(String serverAddress, String & hostName) 
{
    Boolean ok = false;
    int ps, value = 0;
    String strValue;
    struct hostent *host;
    struct in_addr ia;
    
    hostName.clear();
    if((ia.s_addr = inet_addr(serverAddress.getCString())) != -1) 
    {
        host = gethostbyaddr((const char *)&ia, 
                              sizeof(struct in_addr),
                               AF_INET);
        if(host != NULL) 
        {
            hostName.assign(host->h_name);
            ok = true;
        }
   }
   return ok;
}    
Example #25
0
void FileSystem::loadFileToMemory(
    Buffer& array,
    const String& fileName)
{
    Uint32 fileSize;

    if (!getFileSize(fileName, fileSize))
        throw CannotOpenFile(fileName);

    FILE* fp = fopen(fileName.getCString(), "rb");

    if (fp == NULL)
        throw CannotOpenFile(fileName);

    array.reserveCapacity(fileSize);
    char buffer[4096];
    size_t n;

    while ((n = fread(buffer, 1, sizeof(buffer), fp)) > 0)
        array.append(buffer, static_cast<Uint32>(n));

    fclose(fp);
}
Example #26
0
bool TujiLayer::init()
{
	if (!Layer::init())
	{
		return false;
	}

	m_iBeforeSel = 0;

	// 背景
	auto bgSprite = Sprite::create("PhotoGalleryBackground.png");
	bgSprite->setPosition(WINSIZE.width / 2, WINSIZE.height / 2);
	this->addChild(bgSprite);

	auto closeItem = MenuItemSprite::create(
		Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("GalleryOffNormal.png")),
		Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("GalleryOffSelected.png")),
		[&](Ref * ref){
		PLAYEFFECT;
		//弹出场景
		Director::getInstance()->replaceScene(StartLayer::createScene()); });
	// 关闭按钮
	closeItem->setPosition(WINSIZE.width/2+580, WINSIZE.height/2+320);
	auto menu = Menu::create(closeItem, NULL);
	menu->setPosition(Point::ZERO);
	bgSprite->addChild(menu);

	// 怪物图鉴
// 	char *inBuf = "木\n桩\n怪";
// 	size_t inLen = strlen(inBuf);
// 	size_t outLen = inLen << 1;
// 	char *outBuf = (char *)malloc(outLen);
// 	gbk2utf8(inBuf, inLen, outBuf, outLen);

	XMLParser *pXmlParser = XMLParser::parseWithFile("tujiLayer.xml");
	String *mz = pXmlParser->getString("muzhuang");

	m_pMZ_Pic = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("ManWood.png"));
	m_pMZ_Txt = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("Text.png"));
	m_pMZLabel = LabelTTF::create(mz->getCString(), "", 30);
	m_pMZLabel->setColor(ccc3(0, 255, 255));

//  free(outBuf);
	m_pLion_Pic = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("ManLion.png"));
	m_pLionLabel = LabelTTF::create("狮\n子\n怪 ", "", 30);
	m_pLionLabel->setColor(ccc3(0, 255, 255));
	m_pStone_Pic = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("ManStone.png"));
	m_pStoneLabel = LabelTTF::create("石\n头\n怪 ", "", 30);
	m_pStoneLabel->setColor(ccc3(0, 255, 255));
	m_pStoneLabel->setRotation(90);

	m_pMZ_Pic->setPosition(WINSIZE.width / 2 + 50, WINSIZE.height / 2);
	m_pMZ_Pic->setVisible(true);
	m_pMZ_Txt->setPosition(WINSIZE.width / 2 + 460, WINSIZE.height / 2 );
	m_pMZ_Txt->setVisible(true);
	m_pMZLabel->setPosition(WINSIZE.width / 2 + 265, WINSIZE.height / 2 - 120);
	m_pMZLabel->setVisible(true);

	m_pLion_Pic->setPosition(WINSIZE.width / 2+50, WINSIZE.height / 2);
	m_pLion_Pic->setVisible(false);
	m_pLionLabel->setPosition(WINSIZE.width / 2 + 265, WINSIZE.height / 2 - 120);
	m_pLionLabel->setVisible(false);

	m_pStone_Pic->setPosition(WINSIZE.width / 2 , WINSIZE.height / 2 );
	m_pStone_Pic->setVisible(false);
	m_pStoneLabel->setPosition(WINSIZE.width / 2 + 265, WINSIZE.height / 2 - 120);
	m_pStoneLabel->setVisible(false);

	bgSprite->addChild(m_pMZ_Pic);
	bgSprite->addChild(m_pMZ_Txt);
	bgSprite->addChild(m_pMZLabel);
	bgSprite->addChild(m_pLion_Pic);
	bgSprite->addChild(m_pLionLabel);
	bgSprite->addChild(m_pStone_Pic);
	bgSprite->addChild(m_pStoneLabel);

	listView = ListView::create();
	listView->setDirection(SCROLLVIEW_DIR_VERTICAL);
	listView->setTouchEnabled(true);
	listView->setBounceEnabled(true);  // 反弹
	listView->setSize(Size(445, 500));
	listView->ignoreContentAdaptWithSize(false);
	listView->setAnchorPoint(Point(0.0, 0.0));
	listView->setPosition(Point(0, WINSIZE.height / 4));
	listView->addEventListenerListView(this, SEL_ListViewEvent(&TujiLayer::selectedItemEvent));
	
	bgSprite->addChild(listView);

	Button* default_button = Button::create("Cell_0.png", "CellSel_0.png", "", UI_TEX_TYPE_PLIST);
	
	default_button->setName("Title Button");

	Layout* default_item = Layout::create();
	default_item->setTouchEnabled(true);
	default_item->setSize(default_button->getSize());
	default_button->setPosition(Point(default_item->getSize().width / 2.0f,
	default_item->getSize().height / 2.0f));
	default_item->addChild(default_button);
	
	// set model 将创建的模板设置为项目模板  
	listView->setItemModel(default_item);


	// 1
	Button* custom_buttonMZ = Button::create("CellSel_0.png", "Cell_0.png", "", UI_TEX_TYPE_PLIST);
	custom_buttonMZ->setName("one Button");
	custom_buttonMZ->setScale9Enabled(true);
	custom_buttonMZ->setSize(default_button->getSize());
	Layout *custom_itemMZ = Layout::create();
	custom_itemMZ->setSize(custom_buttonMZ->getSize());
	custom_buttonMZ->setPosition(Point(custom_itemMZ->getSize().width / 2.0f, custom_itemMZ->getSize().height / 2.0f));
	custom_itemMZ->addChild(custom_buttonMZ);

	// 2
	Button* custom_buttonLion = Button::create("CellSel_1.png", "Cell_1.png", "", UI_TEX_TYPE_PLIST);
	custom_buttonLion->setName("two Button");
	custom_buttonLion->setScale9Enabled(true);
	custom_buttonLion->setSize(default_button->getSize());
	Layout *custom_itemLion = Layout::create();
	custom_itemLion->setSize(custom_buttonLion->getSize());
	custom_buttonLion->setPosition(Point(custom_itemLion->getSize().width / 2.0f, custom_itemLion->getSize().height / 2.0f));
	custom_itemLion->addChild(custom_buttonLion);

	// 3
	Button* custom_buttonStone = Button::create("CellSel_2.png", "Cell_2.png", "", UI_TEX_TYPE_PLIST);
	custom_buttonStone->setName("three Button");
	custom_buttonStone->setScale9Enabled(true);
	custom_buttonStone->setSize(default_button->getSize());
	Layout *custom_itemStone = Layout::create();
	custom_itemStone->setSize(custom_buttonStone->getSize());
	custom_buttonStone->setPosition(Point(custom_itemStone->getSize().width / 2.0f, custom_itemStone->getSize().height / 2.0f));
	custom_itemStone->addChild(custom_buttonStone);

	// 4
	Button* custom_buttonWood = Button::create("CellSel_3.png", "Cell_3.png", "", UI_TEX_TYPE_PLIST);
	custom_buttonWood->setName("four Button");
	custom_buttonWood->setScale9Enabled(true);
	custom_buttonWood->setSize(default_button->getSize());
	Layout *custom_itemWood = Layout::create();
	custom_itemWood->setSize(custom_buttonWood->getSize());
	custom_buttonWood->setPosition(Point(custom_itemWood->getSize().width / 2.0f, custom_itemWood->getSize().height / 2.0f));
	custom_itemWood->addChild(custom_buttonWood);

 	listView->pushBackCustomItem(custom_itemMZ);
 	listView->pushBackCustomItem(custom_itemLion);
	listView->pushBackCustomItem(custom_itemStone);
	listView->pushBackCustomItem(custom_itemWood);


	return true;
}
Example #27
0
void GameScene::update(float dt)
{
	Point hitWorld = convertToNodeSpace(boxHitPos);
	float realDistance = player->getPosition().distance(hitWorld);

	player->update();
	LabelCubeTest->setPosition(Vec2(-this->getPosition().x + LabelCubeTest->getContentSize().width / 2, -this->getPosition().y + visibleSize.height - LabelCubeTest->getContentSize().height / 2));
	LabelCubeTest->setColor(ccc3(255, 255, 0));
	String *score = String::createWithFormat("Time: %.2f", timeMilliseconds);

	LabelCubeTest->setString(score->getCString());
	attempts->setPosition(Vec2(-this->getPosition().x + attempts->getContentSize().width / 2, -this->getPosition().y + visibleSize.height - LabelCubeTest->getContentSize().height / 2 - attempts->getContentSize().height));

	// Collision resting
	if (isMapLoaded)
	{
		tile->getminiMap()->setPosition(Vec2(-this->getPosition().x, -this->getPosition().y));
		int colCount = 0;
		for (int i = 0; i < tile->tileCollisions.size(); i++)
		{
			if (tile->tileCollisions[i]->getPhysicsBody()->isEnabled())
			{
				colCount++;
			}
			if (tile->tileCollisions[i]->getPositionX() < -this->getPositionX() + visibleSize.width &&
				tile->tileCollisions[i]->getPositionX() > -this->getPositionX() && 

				tile->tileCollisions[i]->getPositionY() < -this->getPositionY() + MAXDISTANCE + visibleSize.height &&
				tile->tileCollisions[i]->getPositionY() > -this->getPositionY() - MAXDISTANCE)
			{
				tile->tileCollisions[i]->getPhysicsBody()->setEnable(true);
			}
			else
				tile->tileCollisions[i]->getPhysicsBody()->setEnable(false);
		}

		for (int i = 0; i < tile->tiles.size(); i++)
		{
			float distanceToTile = player->getPosition().distance(tile->tiles[i]->getPosition());
			float distanceToTileFromHook = sprite->getPosition().distance(tile->tiles[i]->getPosition());
			if (tile->tiles[i]->getPhysicsBody()->isEnabled())
			{
				colCount++;
			}
			if ( distanceToTile < 100 || distanceToTileFromHook < 100)
			{
				tile->tiles[i]->getPhysicsBody()->setEnable(true);
			}
			else
				tile->tiles[i]->getPhysicsBody()->setEnable(false);
		}

		CCLOG("Number of enabled tiles: %i", colCount);
	}

	if (realDistance > 50 && player->isTouchHold && player->isHooked && !isAlreadyRoped)
	{
		rope->getRopePhysicsBody()->setEnable(false);
		rope->getRopePhysicsBody()->setDynamic(false);

		rope->setPosition(sprite->getPosition());

		ropeJoint = PhysicsJointDistance::construct(player->getPlayerPhysicsBody(), rope->getRopePhysicsBody(), Vec2(Point::ZERO.x + 25, Point::ZERO.y), Vec2(Point::ZERO.x, Point::ZERO.y));
		ropeJoint->setCollisionEnable(true);

		_world->addJoint(ropeJoint);
		isAlreadyRoped = true;

		CocosDenshion::SimpleAudioEngine::sharedEngine()->stopAllEffects();
		if (!Constant::soundMuted)
		{
			CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("Sounds/Konks/HitMetal 6095_51_1.mp3");
		}
	}

	if (realDistance > 50 && player->isTouchHold && player->isHooked && isAlreadyRoped)
	{
		//player->update();
	}

	//Checks if the player is outside of the screen
	if ((player->getPosition().x <= 0 || player->getPosition().y <= 0 - 200) && !isPlayerDead)
	{
		isPlayerDead = true;
		this->RestartScene(this);
	}

	// Hide hook if it doesnt hit the wall
	if (sprite && !player->isHooked && player->isTouchHold)
	{
		if (sprite->numberOfRunningActions() == 0)
			sprite->setPosition(Vec2(-1000, -1000));
	}

	if (_drawNode)
	{
		removeChild(_drawNode);
	}

	_drawNode = DrawNode::create();

	float rayCastOffset = 100;
	if (isAlreadyRoped)
	{
		Point ropeBodyA = Vec2(player->getPlayer()->getPosition().x + 25, player->getPlayer()->getPosition().y);
		Point ropeBodyB = Vec2(rope->getRope()->getPosition().x, rope->getRope()->getPosition().y);

		Point fromplayertohook = ccpSub(player->getPosition(), sprite->getPosition());
		float angle = -CC_RADIANS_TO_DEGREES(ccpToAngle(fromplayertohook));
		float realangle = angle + 270;
		player->getPlayer()->setRotation(realangle);

		_drawNode->drawSegment(ropeBodyA, ropeBodyB, 1, Color4F::RED);

	}
	this->addChild(_drawNode, 90000001);
}
Example #28
0
//------------------------------------------------------------------------------
// FUNCTION: getNTPInfo
//
// REMARKS: Retrieves the NTP information from the "/etc/ntp.conf" file, 
//            and sets private variables to hold the data read.
//
// RETURN: 
//------------------------------------------------------------------------------
Boolean NTPService::getNTPInfo() 
{
    FILE *fp;
    int i, ps = 0;
    long lstPos = 0;
    char buffer[5000];
    Boolean ok = false,
            okRet = false;
    String strKey, 
           strHost, 
           strBuffer;

    // Open NTP configuration file
    if((fp = fopen(NTP_FILE_CONFIG.getCString(), "r")) == NULL)
        return ok;

    // Clear attributes 
    ntpName.clear();
    ntpServerAddress.clear();

    memset(buffer, 0, sizeof(buffer));
    while(fgets(buffer, sizeof(buffer), fp) != NULL) 
    {
        buffer[strlen(buffer)-1] = 0;
        strBuffer.assign(buffer);

        ps = strBuffer.find(NTP_ROLE_CLIENT);
        
        okRet = true;
        if(ps == 0) 
        {
            okRet = true;
            fseek(fp, lstPos, SEEK_SET);
            fscanf(fp, "%s", buffer);
            strBuffer.assign(buffer);
            ps = strBuffer.find(NTP_ROLE_CLIENT);
            if(ps < 0) {
                lstPos = ftell(fp);
                continue;
            }

            fscanf(fp, "%s", buffer);
            strHost.assign(buffer);

            ok = false;    
            // Verify if name server exists in array
            for(i=0; i < ntpServerAddress.size(); i++) 
            {
                if(String::equalNoCase(ntpServerAddress[i], strHost)) 
                {
                    ok = true;
                    break;
                }
            }
            if(!ok) 
            {
                ntpServerAddress.append(strHost);
                if(ntpName.size() == 0) 
                    // Set ntpName variable with name server, if strHost variable
                    // is an IP address.
                    getHostName(strHost, ntpName);
            }
        }
        lstPos = ftell(fp);
    }
    fclose(fp);        
    return okRet;
}
Example #29
0
//
// Creates a new instance.
//
void UserAuthProvider::createInstance(
    const OperationContext & context,
    const CIMObjectPath & instanceReference,
    const CIMInstance & myInstance,
    ObjectPathResponseHandler & handler)
{
    PEG_METHOD_ENTER(TRC_USER_MANAGER,"UserAuthProvider::createInstance");

    CIMValue    userName;
    CIMValue    password;
    String      userNameStr;
    String      passwordStr;
    String      namespaceStr;
    String      authorizationStr;

    //
    // get userName
    //
    String user;
    try
    {
        const IdentityContainer container = context.get(IdentityContainer::NAME);
        user= container.getUserName();
    }
    catch (...)
    {
        user= String::EMPTY;
    }

    //
    // verify user authorizations
    //
    if ( user != String::EMPTY || user != "" )
    {
        _verifyAuthorization(user);
    }

    CIMInstance          modifiedInst = myInstance;

    // begin processing the request
    handler.processing();

#ifndef PEGASUS_NO_PASSWORDFILE
    //
    // check if the class name requested is PG_User
    //
    if (CLASS_NAME_PG_USER.equal (instanceReference.getClassName()))
    {
        try
        {
            //
            // Get the user name from the instance
            //
            Uint32 pos = myInstance.findProperty ( PROPERTY_NAME_USERNAME );
            CIMProperty prop = (CIMProperty)modifiedInst.getProperty(pos);
            userName = prop.getValue();
            userName.get(userNameStr);

            //
            // Get the password from the instance
            //
            pos = myInstance.findProperty ( PROPERTY_NAME_PASSWORD );
            prop = (CIMProperty) modifiedInst.getProperty(pos);
            password = prop.getValue();
            password.get(passwordStr);

            //
            // Add the user to the User Manager
            //
            _userManager->addUser( userNameStr, passwordStr);

        }
        catch ( const CIMException & )
        {
            handler.complete();
            PEG_METHOD_EXIT();
            throw;
        }
        catch ( const Exception &e )
        {
            handler.complete();
            PEG_METHOD_EXIT();
            throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage());
        }
    }
    //
    // check if the class name requested is PG_Authorization
    //
    else if (instanceReference.getClassName().equal
             (CLASS_NAME_PG_AUTHORIZATION))
#else
    if (instanceReference.getClassName().equal (CLASS_NAME_PG_AUTHORIZATION))
#endif
    {
        try
        {
            //
            // Get the user name from the instance
            //
            Uint32 pos = myInstance.findProperty ( PROPERTY_NAME_USERNAME );
            CIMProperty prop = (CIMProperty)modifiedInst.getProperty(pos);
            prop.getValue().get(userNameStr);

            //
            // Get the namespace from the instance
            //
            pos = myInstance.findProperty ( PROPERTY_NAME_NAMESPACE );
            prop = (CIMProperty)modifiedInst.getProperty(pos);
            prop.getValue().get(namespaceStr);

            //
            // Get the authorization from the instance
            //
            pos = myInstance.findProperty ( PROPERTY_NAME_AUTHORIZATION );
            prop = (CIMProperty)modifiedInst.getProperty(pos);
            prop.getValue().get(authorizationStr);

            //
            // Check if the user is a valid system user
            //
            if ( !System::isSystemUser( userNameStr.getCString() ) )
            {
                InvalidSystemUser isu(userNameStr);
                throw isu;
            }

#ifndef PEGASUS_NO_PASSWORDFILE
            //
            // check if the user is a valid CIM user
            //
            if ( !_userManager->verifyCIMUser( userNameStr ) )
            {
                InvalidUser iu(userNameStr);
                throw iu;
            }
#endif

            _repository->createInstance(
                instanceReference.getNameSpace(), myInstance);

            //
            // set authorization in the UserManager
            //
            _userManager->setAuthorization(
                userNameStr, namespaceStr, authorizationStr );
        }
        catch ( InvalidUser &iu )
        {
            PEG_METHOD_EXIT();
            throw PEGASUS_CIM_EXCEPTION(
                CIM_ERR_INVALID_PARAMETER, iu.getMessage());
        }
        catch ( InvalidSystemUser &isu )
        {
            PEG_METHOD_EXIT();
            throw PEGASUS_CIM_EXCEPTION(
                CIM_ERR_INVALID_PARAMETER, isu.getMessage());
        }
        catch ( InvalidNamespace &ins )
        {
            PEG_METHOD_EXIT();
            throw PEGASUS_CIM_EXCEPTION(
                CIM_ERR_INVALID_PARAMETER, ins.getMessage());
        }
        catch ( CIMException &e )
        {
            PEG_METHOD_EXIT();
            throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage());
        }
        catch ( Exception &e )
        {
            PEG_METHOD_EXIT();
            throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage());
        }
    }
    else
    {
        PEG_METHOD_EXIT();
        throw PEGASUS_CIM_EXCEPTION (
            CIM_ERR_NOT_SUPPORTED, instanceReference.getClassName().getString());
    }

    handler.deliver(instanceReference);

    // complete processing the request
    handler.complete();

    PEG_METHOD_EXIT();
    return;
}
Example #30
0
int CIMServerProcess::cimserver_run(
    int argc,
    char** argv,
    Boolean shutdownOption,
    Boolean debugOutputOption)
{
    Boolean daemonOption = false;

#if defined (PEGASUS_OS_PASE) && !defined (PEGASUS_DEBUG)
    // PASE have itself regular for checking privileged user
    if (!System::isPrivilegedUser("*CURRENT  "))
    {
        MessageLoaderParms parms(
                "src.Server.cimserver.NO_AUTHORITY.PEGASUS_OS_PASE",
                "The caller should be a privileged user,"
                " or the server will not run.");
        cerr << MessageLoader::getMessage(parms) << endl;
        exit (1);
    }
    char jobName[11];
    // this function only can be found in PASE environment
    umeGetJobName(jobName, false);
    if (strncmp("QUMECIMOM ", jobName, 10) != 0
            && strncmp("QUMEENDCIM", jobName, 10) != 0)
    {
        MessageLoaderParms parms(
                "src.Server.cimserver.NOT_OFFICIAL_START.PEGASUS_OS_PASE",
                "cimserver can not be started by user.\nServer will not run.");
        cerr << MessageLoader::getMessage(parms) << endl;
        exit (1);
    }

    // Direct standard input, output, and error to /dev/null,
    // PASE run this job in background, any output in not allowed
    freopen("/dev/null", "r", stdin);
    freopen("/dev/null", "w", stdout);
    freopen("/dev/null", "w", stderr);
#endif

    //
    // Get an instance of the Config Manager.
    //
    ConfigManager* configManager = ConfigManager::getInstance();
    configManager->useConfigFiles = true;

    try
    {
        //
        // Get options (from command line and from configuration file); this
        // removes corresponding options and their arguments from the command
        // line.  NOTE: If shutdownOption=true, the contents of current config
        // file are not overwritten by the planned config file.
        //
        GetOptions(configManager, argc, argv, shutdownOption);

        //
        // Initialize the message home directory in the MessageLoader.
        // This is the default directory where the resource bundles are found.
        //
        MessageLoader::setPegasusMsgHome(ConfigManager::getHomedPath(
            ConfigManager::getInstance()->getCurrentValue("messageDir")));

#if !defined(PEGASUS_USE_SYSLOGS)
        String logsDirectory = ConfigManager::getHomedPath(
            configManager->getCurrentValue("logdir"));

        // Set up the Logger.  This does not open the logs.
        // Might be more logical to clean before set.
        Logger::setHomeDirectory(logsDirectory);
#endif


#ifdef PEGASUS_OS_PASE
        /* write job log to tell where pegasus log is.*/
        if(logsDirectory.size() > 0)
            // this function only can be found in PASE environment
            logPegasusDir2joblog(logsDirectory.getCString());
        else
            logPegasusDir2joblog(".");

        // set ccsid to unicode for entire job
        // ccsid is globolization mechanism in PASE environment
        if (_SETCCSID(1208) == -1)
        {
            MessageLoaderParms parms(
                    "src.Server.cimserver.SET_CCSID_ERROR.PEGASUS_OS_PASE",
                    "Failed to set CCSID, server will stop.");
            cerr << MessageLoader::getMessage(parms) << endl;
            Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::FATAL,
                    parms);
            exit (1);
        }

        char fullJobName[29];
        umeGetJobName(fullJobName, true);
        Logger::put_l(Logger::STANDARD_LOG, System::CIMSERVER,
                Logger::INFORMATION,
                MessageLoaderParms(
                    "src.Server.cimserver.SERVER_JOB_NAME.PEGASUS_OS_PASE",
                    "CIM Server's Job Name is: $0", fullJobName));
#endif

#ifdef PEGASUS_DISABLE_LOCAL_DOMAIN_SOCKET
        // Make sure at least one connection is enabled

        Boolean enableHttpConnection = ConfigManager::parseBooleanValue(
            configManager->getCurrentValue("enableHttpConnection"));
        Boolean enableHttpsConnection = ConfigManager::parseBooleanValue(
            configManager->getCurrentValue("enableHttpsConnection"));

        if (!enableHttpConnection && !enableHttpsConnection)
        {
            MessageLoaderParms parms(
                "src.Server.cimserver.HTTP_NOT_ENABLED_SERVER_NOT_STARTING",
                "Neither HTTP nor HTTPS connection is enabled."
                    "  CIMServer will not be started.");
            Logger::put_l(
                Logger::STANDARD_LOG, System::CIMSERVER, Logger::WARNING,
                parms);
            cerr << MessageLoader::getMessage(parms) << endl;
            return 1;
        }
#endif

        //
        // Check to see if we should start Pegasus as a daemon
        //
        daemonOption = ConfigManager::parseBooleanValue(
            configManager->getCurrentValue("daemon"));

        if ((Executor::detectExecutor() == 0) && (daemonOption == false))
        {
            MessageLoaderParms parms(
                "src.Server.cimserver.PRIVSEP_REQUIRES_DAEMON",
                "Warning: The configuration setting daemon=false is ignored "
                    "with privilege separation enabled.");
            cerr << MessageLoader::getMessage(parms) << endl;
            daemonOption = true;
        }

        //
        // Check to see if we need to shutdown CIMOM
        //
        if (shutdownOption)
        {
#if defined(PEGASUS_OS_ZOS) && defined(PEGASUS_ZOS_SECURITY)
            // This checks whether user is authorized to stop the
            // CIM Server. When unauthorized a message is logged to
            // to the user and program exits.
            shutdownCheckProfileCIMSERVclassWBEM();
            // Depending on the success of the previous check we may not
            // reach this code!!!
#endif
            String configTimeout =
                configManager->getCurrentValue("shutdownTimeout");
            Uint32 timeoutValue =
                strtol(configTimeout.getCString(), (char **)0, 10);

            ServerShutdownClient serverShutdownClient(&_serverRunStatus);
            serverShutdownClient.shutdown(timeoutValue);

            MessageLoaderParms parms(
                "src.Server.cimserver.SERVER_STOPPED",
                "CIM Server stopped.");

            cout << MessageLoader::getMessage(parms) << endl;
            return 0;
        }

#if defined(PEGASUS_DEBUG) && !defined(PEGASUS_USE_SYSLOGS)
        // Leave this in until people get familiar with the logs.
        MessageLoaderParms parms("src.Server.cimserver.LOGS_DIRECTORY",
                                 "Logs Directory = ");
        cout << MessageLoader::getMessage(parms) << logsDirectory << endl;
#endif
    }
    catch (Exception& e)
    {
        MessageLoaderParms parms("src.Server.cimserver.SERVER_NOT_STARTED",
            "cimserver not started: $0", e.getMessage());
        Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
            parms);
        cerr << MessageLoader::getMessage(parms) << endl;

        return 1;
    }

#if defined(PEGASUS_OS_ZOS) 
#  if defined(PEGASUS_ZOS_SECURITY)
    startupCheckBPXServer(true);
    startupCheckProfileCIMSERVclassWBEM();
    startupEnableMSC();
#  endif
    startupWaitForTCPIP();
#endif

#if defined(PEGASUS_DEBUG)
    // Put out startup up message.
    cout << _cimServerProcess->getProductName() << " " <<
        _cimServerProcess->getCompleteVersion() << endl;
#endif

    // Force initialization of hostname and fullyQualifiedHostName through
    // retrieving current value from Configuration Manager
    // - this will run getCurrentValue() in DefaultPropertyOwner.cpp
    configManager->getCurrentValue("hostname");
    configManager->getCurrentValue("fullyQualifiedHostName");

    // reset message loading to NON-process locale
    MessageLoader::_useProcessLocale = false;

    // Get the parent's PID before forking
    _serverRunStatus.setParentPid(System::getPID());

    // Do not fork when using privilege separation (executor will daemonize
    // itself later).
    if (daemonOption)
    {
        if (-1 == _cimServerProcess->cimserver_fork())
            return -1;
    }

    // Now we are after the fork...
    // Create a dummy Thread object that can be used to store the
    // AcceptLanguageList object for CIM requests that are serviced
    // by this thread (initial thread of server).  Need to do this
    // because this thread is not in a ThreadPool, but is used
    // to service CIM requests.
    // The run function for the dummy Thread should never be called,
    dummyInitialThread = new Thread(dummyThreadFunc, NULL, false);
    Thread::setCurrent(dummyInitialThread);
    try
    {
        Thread::setLanguages(LanguageParser::getDefaultAcceptLanguages());
    }
    catch (InvalidAcceptLanguageHeader& e)
    {
        Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
            MessageLoaderParms(
                "src.Server.cimserver.FAILED_TO_SET_PROCESS_LOCALE",
                "Could not convert the system process locale into a valid "
                    "AcceptLanguage format."));
        Logger::put(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
            e.getMessage());
    }

#ifndef PEGASUS_OS_TYPE_WINDOWS
    umask(S_IRWXG|S_IRWXO);
#endif

    // Start up the CIM Server

    try
    {
#if defined(PEGASUS_OS_TYPE_UNIX)
        //
        // Lock the CIMSERVER_LOCK_FILE during CIM Server start-up to prevent
        // concurrent writes to this file by multiple cimserver processes
        // starting at the same time.
        //
        CString startupLockFileName = ConfigManager::getHomedPath(
            PEGASUS_CIMSERVER_START_LOCK_FILE).getCString();

        // Make sure the start-up lock file exists
        FILE* startupLockFile;
        if ((startupLockFile = fopen(startupLockFileName, "w")) != 0)
        {
            fclose(startupLockFile);
        }

        AutoFileLock fileLock(startupLockFileName);
#endif

#if defined(PEGASUS_OS_TYPE_UNIX) || defined(PEGASUS_OS_VMS)
        //
        // Check if a CIM Server is already running.  If so, print an error
        // message and notify the parent process (if there is one) to terminate
        //
        if (_serverRunStatus.isServerRunning())
        {
            MessageLoaderParms parms(
                "src.Server.cimserver.UNABLE_TO_START_SERVER_ALREADY_RUNNING",
                "Unable to start CIMServer. CIMServer is already running.");
            Logger::put_l(
                Logger::ERROR_LOG, System::CIMSERVER, Logger::INFORMATION,
                parms);
            cerr << MessageLoader::getMessage(parms) << endl;

            if (daemonOption)
            {
                _cimServerProcess->notify_parent(1);
            }

            return 1;
        }

        //
        // Declare ourselves as the running CIM Server process, and write our
        // PID to the PID file.
        //
        _serverRunStatus.setServerRunning();
#endif

        // Create and initialize the CIMServer object

        _cimServer = new CIMServer();

        Boolean enableHttpConnection = ConfigManager::parseBooleanValue(
            configManager->getCurrentValue("enableHttpConnection"));
        Boolean enableHttpsConnection = ConfigManager::parseBooleanValue(
            configManager->getCurrentValue("enableHttpsConnection"));

#ifdef PEGASUS_DISABLE_LOCAL_DOMAIN_SOCKET
        // Make sure at least one connection is enabled
        if (!enableHttpConnection && !enableHttpsConnection)
        {
            MessageLoaderParms parms(
                "src.Server.cimserver.HTTP_NOT_ENABLED_SERVER_NOT_STARTING",
                "Neither HTTP nor HTTPS connection is enabled.");
            throw Exception(parms);
        }
#endif

        Boolean addIP6Acceptor = false;
        Boolean addIP4Acceptor = false;

#ifdef PEGASUS_OS_TYPE_WINDOWS
        addIP4Acceptor = true;
#endif

#ifdef PEGASUS_ENABLE_IPV6
        // If IPv6 stack is disabled swicth to IPv4 stack.
        if (System::isIPv6StackActive())
        {
            addIP6Acceptor = true;
        }
        else
        {
            PEG_TRACE_CSTRING(TRC_SERVER,Tracer::LEVEL4,
                "IPv6 stack is not active, using IPv4 socket.");
        }
#endif
        if (!addIP6Acceptor)
        {
            addIP4Acceptor = true;
        }

        // The server HTTP and HTTPS ports are determined via this algorithm:
        // 1) If the user explicitly specified a port, use it.
        // 2) If the user did not specify a port, get the port from the
        //    services file.
        // 3) If no value is specified in the services file, use the IANA WBEM
        //    default port.
        // Note that 2 and 3 are done within the System::lookupPort method
        // An empty string from the ConfigManager implies that the user did not
        // specify a port.

        if (enableHttpConnection)
        {
            Uint32 portNumberHttp = 0;
            String httpPort = configManager->getCurrentValue("httpPort");
            if (httpPort.size() == 0)
            {
                //
                // Look up the WBEM-HTTP port number
                //
                portNumberHttp = System::lookupPort(
                    WBEM_HTTP_SERVICE_NAME, WBEM_DEFAULT_HTTP_PORT);
                _initConfigProperty("httpPort", portNumberHttp);
            }
            else
            {
                Uint64 longNumber;
                // use the current value which has been checked for validity at
                // load(fct. GetOptions), see DefaultPropertyOwner::isValid()
                StringConversion::decimalStringToUint64(
                    httpPort.getCString(),
                    longNumber);
                portNumberHttp = longNumber & 0xffff;
            }

            String listenOn = configManager->getCurrentValue("listenAddress");
            if(String::equalNoCase(listenOn, "All"))
            {
                if (addIP6Acceptor)
                {
                    _cimServer->addAcceptor(HTTPAcceptor::IPV6_CONNECTION,
                        portNumberHttp, false);
                }
                if (addIP4Acceptor)
                {
                    _cimServer->addAcceptor(HTTPAcceptor::IPV4_CONNECTION,
                        portNumberHttp, false);
                }
            }
            else // Restricted listening
            {
                _restrictListening(
                    configManager, listenOn, portNumberHttp, false);
            }

            // The port number is converted to a string to avoid the
            //  addition of localized characters (e.g., "5,988").
            char scratchBuffer[22];
            Uint32 n;
            const char * portNumberHttpStr = Uint32ToString(
                scratchBuffer, portNumberHttp, n);
            MessageLoaderParms parms(
                "src.Server.cimserver.LISTENING_ON_HTTP_PORT",
                "Listening on HTTP port $0.", portNumberHttpStr);
            Logger::put_l(
                Logger::STANDARD_LOG, System::CIMSERVER, Logger::INFORMATION,
                parms);
#if defined(PEGASUS_DEBUG)
            cout << MessageLoader::getMessage(parms) << endl;
#endif
        }

        if (enableHttpsConnection)
        {
            Uint32 portNumberHttps = 0;
            String httpsPort = configManager->getCurrentValue("httpsPort");
            if (httpsPort.size() == 0)
            {
                //
                // Look up the WBEM-HTTPS port number
                //
                portNumberHttps = System::lookupPort(
                    WBEM_HTTPS_SERVICE_NAME, WBEM_DEFAULT_HTTPS_PORT);
                _initConfigProperty("httpsPort", portNumberHttps);
            }
            else
            {
                Uint64 longNumber;
                // use the current value which has been checked for validity at
                // load(fct. GetOptions), see DefaultPropertyOwner::isValid()
                StringConversion::decimalStringToUint64(
                    httpsPort.getCString(),
                    longNumber);
                portNumberHttps = longNumber & 0xffff;
            }

            String listenOn = configManager->getCurrentValue("listenAddress");
            if(String::equalNoCase(listenOn, "All"))
            {
                if (addIP6Acceptor)
                {
                    _cimServer->addAcceptor(HTTPAcceptor::IPV6_CONNECTION,
                        portNumberHttps, true);
                }
                if (addIP4Acceptor)
                {
                    _cimServer->addAcceptor(HTTPAcceptor::IPV4_CONNECTION,
                        portNumberHttps, true);
                }
            }
            else //Restricted
            {
                _restrictListening(
                    configManager, listenOn, portNumberHttps, true);
            }

            // The port number is converted to a string to avoid the
            //  addition of localized characters (e.g., "5,989").
            char scratchBuffer[22];
            Uint32 n;
            const char * portNumberHttpsStr = Uint32ToString(
                scratchBuffer, portNumberHttps, n);
            MessageLoaderParms parms(
                "src.Server.cimserver.LISTENING_ON_HTTPS_PORT",
                "Listening on HTTPS port $0.", portNumberHttpsStr);
            Logger::put_l(
                Logger::STANDARD_LOG, System::CIMSERVER, Logger::INFORMATION,
                parms);
#if defined(PEGASUS_DEBUG)
            cout << MessageLoader::getMessage(parms) << endl;
#endif
        }

#ifndef PEGASUS_DISABLE_LOCAL_DOMAIN_SOCKET
        {
            _cimServer->addAcceptor(HTTPAcceptor::LOCAL_CONNECTION, 0, false);

            MessageLoaderParms parms(
                "src.Server.cimserver.LISTENING_ON_LOCAL",
                "Listening on local connection socket.");
            Logger::put_l(
                Logger::STANDARD_LOG, System::CIMSERVER, Logger::INFORMATION,
                parms);
# if defined(PEGASUS_DEBUG)
            cout << MessageLoader::getMessage(parms) << endl;
# endif
        }
#endif

        _cimServer->bind();

        // notify parent process (if there is a parent process) to terminate
        // so user knows that there is cimserver ready to serve CIM requests.
        if (daemonOption)
        {
            _cimServerProcess->notify_parent(0);
        }

#if defined(PEGASUS_DEBUG)
        cout << "Started. " << endl;
#endif

        // Put server started message to the logger
        Logger::put_l(Logger::STANDARD_LOG, System::CIMSERVER,
            Logger::INFORMATION,
            MessageLoaderParms(
                "src.Server.cimserver.STARTED_VERSION",
                "Started $0 version $1.",
                _cimServerProcess->getProductName(),
                _cimServerProcess->getCompleteVersion()));

#if defined(PEGASUS_OS_TYPE_UNIX) && !defined(PEGASUS_OS_ZOS)
        if (daemonOption && !debugOutputOption)
        {
            // Direct standard input, output, and error to /dev/null,
            // since we are running as a daemon.
            close(STDIN_FILENO);
            open("/dev/null", O_RDONLY);
            close(STDOUT_FILENO);
            open("/dev/null", O_RDWR);
            close(STDERR_FILENO);
            open("/dev/null", O_RDWR);
        }
#endif
    }
    catch (Exception& e)
    {
        MessageLoaderParms parms("src.Server.cimserver.SERVER_NOT_STARTED",
            "cimserver not started: $0", e.getMessage());
        Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
            parms);
        cerr << MessageLoader::getMessage(parms) << endl;

        deleteCIMServer();

        //
        // notify parent process (if there is a parent process) to terminate
        //
        if (daemonOption)
            _cimServerProcess->notify_parent(1);

        return 1;
    }

    // Run the main CIM Server loop

    try
    {
#if defined(PEGASUS_OS_ZOS)

        // ARM is a z/OS internal restart facility.
        // This is a z/OS specific change.

        // Instatiating the automatic restart manager for zOS
        ARM_zOS automaticRestartManager;

        // register to zOS ARM
        automaticRestartManager.Register();

#endif

#ifdef PEGASUS_ENABLE_SLP
        _cimServer->startSLPProvider();
#endif
        _cimServer->initComplete();

        //
        // Loop to call CIMServer's runForever() method until CIMServer
        // has been shutdown
        //
        while (!_cimServer->terminated())
        {
            _cimServer->runForever();
        }

        //
        // normal termination
        //

#if defined(PEGASUS_OS_ZOS)

        // ARM is a z/OS internal restart facility.
        // This is a z/OS specific change.

        // register to zOS ARM
        automaticRestartManager.DeRegister();

#endif

        // Put server shutdown message to the logger
        Logger::put_l(
            Logger::STANDARD_LOG, System::CIMSERVER, Logger::INFORMATION,
            MessageLoaderParms(
                "src.Server.cimserver.STOPPED",
                "$0 stopped.", _cimServerProcess->getProductName()));
    }
    catch (Exception& e)
    {
        MessageLoaderParms parms(
            "src.Server.cimserver.ERROR",
            "Error: $0",
            e.getMessage());
        Logger::put_l(Logger::STANDARD_LOG, System::CIMSERVER, Logger::WARNING,
            parms);
        cerr << MessageLoader::getMessage(parms) << endl;

        deleteCIMServer();
        return 1;
    }

    deleteCIMServer();
    return 0;
}