<commit_before>function sendSearch() {
	var query = searchEl.value;
	if (query.length > 0) {
		console.log("Sending search... " + encodeURI(query));
		location.href = "./search?q=" + query;
	}
}

var searchEl = document.getElementById("search-bar");
searchEl.addEventListener("keydown", function(evt) {
	if (evt.keyCode == 13) {
		sendSearch();
	}
});
document.getElementById("search-button").addEventListener("click", sendSearch);
searchEl.addEventListener("click", function() {
	this.value = "";
});<commit_msg>Search highlighting<commit_after>function sendSearch() {
	var query = searchEl.value;
	if (query.length > 0) {
		console.log("Sending search... " + encodeURI(query));
		location.href = "./search?q=" + query;
	}
}

var searchEl = document.getElementById("search-bar");
searchEl.addEventListener("keydown", function(evt) {
	if (evt.keyCode == 13) {
		sendSearch();
	}
});
document.getElementById("search-button").addEventListener("click", sendSearch);
searchEl.addEventListener("click", function() {
	this.value = "";
});

var url_obj = new URL(location.href);
var query = url_obj.searchParams.get("q").toLowerCase();
var cardTextList = document.querySelectorAll(".card .under p");

for (var i = 0; i < cardTextList.length; i++) {
	// https://stackoverflow.com/a/280824/2954591
	var reg = new RegExp("(" + query + ")", "gi");
	cardTextList[i].innerHTML = cardTextList[i].innerHTML.replace(reg, "$1");
}<|endoftext|>


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

/**
 * External dependencies
 */
import { withQuery } from '@storybook/addon-queryparams';

/**
 * Internal dependencies
 */
import SetupSuccessBannerNotification from './SetupSuccessBannerNotification';
import {
	createTestRegistry,
	WithTestRegistry,
	provideModules,
	provideModuleRegistrations,
} from '../../../../tests/js/utils';

function Template( { ...args } ) {
	return <SetupSuccessBannerNotification { ...args } />;
}

export const Site = Template.bind( {} );
Site.storyName = 'Authentication Success - Site';
Site.parameters = {
	query: {
		notification: 'authentication_success',
		slug: undefined,
	},
};

export const Module = Template.bind( {} );
Module.storyName = 'Authentication Success - Generic Module';
Module.parameters = {
	module: { slug: 'tagmanager' },
	query: {
		notification: 'authentication_success',
		slug: 'tagmanager',
	},
};

export const ModuleWithDescription = Template.bind( {} );
ModuleWithDescription.storyName =
	'Authentication Success - Module with description';
ModuleWithDescription.parameters = {
	module: { slug: 'analytics' },
	query: {
		notification: 'authentication_success',
		slug: 'analytics',
	},
};

export const PageSpeedInsights = Template.bind( {} );
PageSpeedInsights.storyName = 'Authentication Success - Page Speed Insights';
PageSpeedInsights.parameters = {
	module: { slug: 'pagespeed-insights' },
	query: {
		notification: 'authentication_success',
		slug: 'pagespeed-insights',
	},
};

export const IdeaHub = Template.bind( {} );
IdeaHub.storyName = 'Authentication Success - Idea Hub';
IdeaHub.parameters = {
	module: { slug: 'idea-hub', name: 'Idea Hub' },
	query: {
		notification: 'authentication_success',
		slug: 'idea-hub',
	},
};

export const UserInputSuccess = Template.bind( {} );
UserInputSuccess.storyName = 'User Input Success';
UserInputSuccess.parameters = {
	query: {
		notification: 'user_input_success',
	},
};

export const ThankWithGoogle = Template.bind( {} );
ThankWithGoogle.storyName = 'Authentication Success - Thank with Google';
ThankWithGoogle.parameters = {
	module: { slug: 'thank-with-google', name: 'Thank with Google' },
	query: {
		notification: 'authentication_success',
		slug: 'thank-with-google',
	},
};

export default {
	title: 'Components/SetupSuccessBannerNotification',
	component: SetupSuccessBannerNotification,
	decorators: [
		withQuery,
		( Story, { parameters } ) => {
			const registry = createTestRegistry();

			provideModules( registry, [
				{
					...( parameters.module || { slug: 'analytics' } ),
					active: true,
					connected: true,
				},
			] );
			provideModuleRegistrations( registry );

			return (
				<WithTestRegistry
					registry={ registry }
					features={ parameters.features || [] }
				>
					<Story />
				</WithTestRegistry>
			);
		},
	],
};
<commit_msg>Provide TwG settings to SetupSuccessBannerNotification.<commit_after>/**
 * SetupSuccessBannerNotification Component Stories.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import { withQuery } from '@storybook/addon-queryparams';

/**
 * Internal dependencies
 */
import SetupSuccessBannerNotification from './SetupSuccessBannerNotification';
import {
	createTestRegistry,
	WithTestRegistry,
	provideModules,
	provideModuleRegistrations,
} from '../../../../tests/js/utils';
import {
	CTA_PLACEMENT_STATIC_AUTO,
	MODULES_THANK_WITH_GOOGLE,
} from '../../modules/thank-with-google/datastore/constants';

function Template( { ...args } ) {
	return <SetupSuccessBannerNotification { ...args } />;
}

export const Site = Template.bind( {} );
Site.storyName = 'Authentication Success - Site';
Site.parameters = {
	query: {
		notification: 'authentication_success',
		slug: undefined,
	},
};

export const Module = Template.bind( {} );
Module.storyName = 'Authentication Success - Generic Module';
Module.parameters = {
	module: { slug: 'tagmanager' },
	query: {
		notification: 'authentication_success',
		slug: 'tagmanager',
	},
};

export const ModuleWithDescription = Template.bind( {} );
ModuleWithDescription.storyName =
	'Authentication Success - Module with description';
ModuleWithDescription.parameters = {
	module: { slug: 'analytics' },
	query: {
		notification: 'authentication_success',
		slug: 'analytics',
	},
};

export const PageSpeedInsights = Template.bind( {} );
PageSpeedInsights.storyName = 'Authentication Success - Page Speed Insights';
PageSpeedInsights.parameters = {
	module: { slug: 'pagespeed-insights' },
	query: {
		notification: 'authentication_success',
		slug: 'pagespeed-insights',
	},
};

export const IdeaHub = Template.bind( {} );
IdeaHub.storyName = 'Authentication Success - Idea Hub';
IdeaHub.parameters = {
	module: { slug: 'idea-hub', name: 'Idea Hub' },
	query: {
		notification: 'authentication_success',
		slug: 'idea-hub',
	},
};

export const UserInputSuccess = Template.bind( {} );
UserInputSuccess.storyName = 'User Input Success';
UserInputSuccess.parameters = {
	query: {
		notification: 'user_input_success',
	},
};

export const ThankWithGoogle = Template.bind( {} );
ThankWithGoogle.storyName = 'Authentication Success - Thank with Google';
ThankWithGoogle.parameters = {
	module: { slug: 'thank-with-google', name: 'Thank with Google' },
	query: {
		notification: 'authentication_success',
		slug: 'thank-with-google',
	},
};

export default {
	title: 'Components/SetupSuccessBannerNotification',
	component: SetupSuccessBannerNotification,
	decorators: [
		withQuery,
		( Story, { parameters } ) => {
			const registry = createTestRegistry();

			provideModules( registry, [
				{
					...( parameters.module || { slug: 'analytics' } ),
					active: true,
					connected: true,
				},
			] );
			provideModuleRegistrations( registry );

			registry.dispatch( MODULES_THANK_WITH_GOOGLE ).receiveGetSettings( {
				publicationID: 'example.com',
				ctaPlacement: CTA_PLACEMENT_STATIC_AUTO,
				colorTheme: 'purple',
				ctaPostTypes: [ 'post', 'page' ],
			} );

			return (
				<WithTestRegistry
					registry={ registry }
					features={ parameters.features || [] }
				>
					<Story />
				</WithTestRegistry>
			);
		},
	],
};
<|endoftext|>


<commit_before>var appEventsTest = {};

appEventsTest.ajax = function(url)
{
	var ajax = new XMLHttpRequest();
	//ajax.onreadystatechange = function () {} //Async call
	ajax.open("GET", url, false); //Sync Call
	ajax.send();
	return ajax.responseText;
};

appEventsTest.setCallback = function ()
{
    Rho.Application.setApplicationNotify( function(params)
    {
        event = params.applicationEvent;
        eventData = params.eventData;

        appEventsTest.lastEvent = event;
        appEventsTest.lastEventData = eventData;
        appEventsTest.eventList.push(event);
        appEventsTest.callbackFired = true;
    });
};

describe("Application JS API", function () {

    beforeEach(function(){
        var matchers = {
            isNotEmptyString: function () {
                return (typeof this.actual == 'string') && (this.actual.length != 0)
            }
        };

        this.addMatchers(
            matchers
        );

    });

	describe("Basic specs", function () {

	    it("Test appBundleFolder property", function () {
	        var result = Rho.Application.appBundleFolder;
			Rho.Log.info(" Rho.Application.appBundleFolder = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    it("Test appsBundleFolder proeprty", function () {
	        var result = Rho.Application.appsBundleFolder;
			Rho.Log.info(" Rho.Application.appsBundleFolder = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    it("Test userFolder property", function () {
	        var result = Rho.Application.userFolder;
			Rho.Log.info(" Rho.Application.userFolder = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    xit("Test configPath property", function () {
	        var result = Rho.Application.configPath;
			Rho.Log.info(" Rho.Application.configPath = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    it("Test modelsManifestPath property", function () {
	        var result = Rho.Application.modelsManifestPath;
			Rho.Log.info(" Rho.Application.modelsManifestPath = " + result, "App");
 			expect(result).isNotEmptyString(0);
	    });

	    it("Test databaseBlobFolder property", function () {
	        var result = Rho.Application.databaseBlobFolder;
			Rho.Log.info(" Rho.Application.databaseBlobFolder = " + result, "App");
 			expect(result).isNotEmptyString(0);
	    });

	    it("Test publicFolder property", function () {
	        var result = Rho.Application.publicFolder;
			Rho.Log.info(" Rho.Application.publicFolder = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    it("Test startURI property", function () {
	        Rho.Application.startURI = 'index.html';
	        var result = Rho.Application.startURI;
			Rho.Log.info(" Rho.Application.startURI = " + result, "App");
 			expect(result).toEqual('index.html');
            Rho.Application.startURI = '/app/index.html';
	    });

	    it("Test settingsPageURI property", function () {
	        Rho.Application.settingsPageURI = 'settings.html';
	        var result = Rho.Application.settingsPageURI;
			Rho.Log.info(" Rho.Application.settingsPageURI = " + result, "App");
 			expect(result).toEqual('settings.html');
	    });

	    it("Test splash property", function () {
	        var result = Rho.Application.splash;
			Rho.Log.info(" Rho.Application.splash = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    it("Test version property", function () {
	        var result = Rho.Application.version;
			Rho.Log.info(" Rho.Application.version = " + result, "App");
 			expect(result).toEqual("1.0");
	    });

	    it("Test name property", function () {
	    	var result = Rho.Application.appName;
			Rho.Log.info(" Rho.Application.appName = " + result, "App");
			expect(result).toEqual("auto_common_spec");
			var result2 = Rho.Application.getAppName();
	        expect(result2).toEqual("auto_common_spec");
	    });

	    //TODO: Implement Localization for Javascript app
	    //it("Current application locale.Like 'en', 'ru' etc", function(){
	    //	expect(Rho.Application.getLocale()).isNotEmptyString();
	    //});

	    //TODO: Implement Country for Javascript app
	    //it("Current application country code", function(){
	    //	expect(Rho.Application.getCountry()).isNotEmptyString();
	    //});

	    //TODO: implement modelFolderPath method

	    //TODO: implement databaseFilePath method

	    //TODO: implement expandDatabaseBlobFilePath method

	    //TODO: implement quit method

	    //TODO: implement modelFolderPath method

	    it("Test minimize method", function () {
	        expect(Rho.Application.minimize).not.toThrow();
	    });

	    it("Test restore method", function () {
	        expect(Rho.Application.restore).not.toThrow();
	    });

	    //TODO: implement spec for setActivationNotify with callback on all platforms

	    //TODO: implement spec for getRhoPlatformVersion with callback

	    if(isWindowsMobilePlatform()){
	        it("Bad link URI to navigate in browser", function () {
	            Rho.Application.badLinkURI = 'badLink.html';
	            expect(Rho.Application.badLinkURI).toEqual('badLink.html');
	        });
	    }

	    if (['WINDOWS_DESKTOP', 'WINDOWS'].indexOf(Rho.System.platform) != -1) {

	        it("Test title property", function () {
	            expect(Rho.Application.title).isNotEmptyString();

	            Rho.Application.title = 'Title';
	            expect(Rho.Application.title).toEqual('Title');
	        });

	    }

	});

	describe('Events specs', function() {
    if (isApplePlatform()) {
        beforeEach(function() {
            Rho.AppEvents.simulateEvent(Rho.AppEvents.APP_EVENT_ACTIVATED);
            Rho.AppEvents.simulateEvent(Rho.AppEvents.APP_EVENT_UICREATED);
            appEventsTest.callbackFired = false;
            appEventsTest.lastEvent = "";
            appEventsTest.lastEventData = {};
            appEventsTest.eventList = [];
        });

        it('Should fire callback', function(){
            runs(function ()
            {
                appEventsTest.setCallback();
                // state is "activated" should be changed
                Rho.AppEvents.simulateEvent(Rho.AppEvents.APP_EVENT_DEACTIVATED);
            });

            waitsFor(function ()
            {
                return appEventsTest.callbackFired;
            }, "the callback didnt fire", 750);

            runs(function ()
            {
                expect(appEventsTest.lastEvent).toEqual(Rho.AppEvents.APP_EVENT_DEACTIVATED);
            });
        });

        it('Should fire callback not once', function(){
            events = [
                Rho.AppEvents.APP_EVENT_DEACTIVATED,
                Rho.AppEvents.APP_EVENT_UIDESTROYED,
                Rho.AppEvents.APP_EVENT_UICREATED,
                Rho.AppEvents.APP_EVENT_ACTIVATED
            ];

            runs(function ()
            {
                appEventsTest.setCallback();
                for(var i = 0; i < events.length; i++)
                {
                    Rho.AppEvents.simulateEvent(events[i]);
                }
            });

            waitsFor(function ()
            {
                return appEventsTest.eventList.length == events.length;
            }, "the callback didnt fire", 750);

            runs(function ()
            {
                expect(appEventsTest.eventList).toEqual(events);
            });
        });

        it('Should not duplicate callbacks', function(){
            events = [
                Rho.AppEvents.APP_EVENT_DEACTIVATED,
                Rho.AppEvents.APP_EVENT_UIDESTROYED,
                Rho.AppEvents.APP_EVENT_ACTIVATED,
                Rho.AppEvents.APP_EVENT_UICREATED
            ];

            runs(function ()
            {
                appEventsTest.setCallback();
                for(var i = 0; i < events.length; i++)
                {
                    Rho.AppEvents.simulateEvent(events[i]);
                    Rho.AppEvents.simulateEvent(events[i]);
                }
            });

            waitsFor(function ()
            {
                return appEventsTest.eventList.length == events.length;
            }, "the callback didnt fire", 750);

            runs(function ()
            {
                expect(appEventsTest.eventList).toEqual(events);
            });
        });

        it('Should handle conflicts', function(){
            template = {
              "intProp" : ['128', '42'],
              "stringProp" : ["ohr","abc"]
            };

            runs(function ()
            {
                appEventsTest.setCallback();
                Rho.AppEvents.addConflictInt("intProp",64,128);
                Rho.AppEvents.addConflictString("stringProp","rho","ohr");
                Rho.AppEvents.simulateConflicts();
            });

            waitsFor(function ()
            {
                return appEventsTest.callbackFired;
            }, "the callback didnt fire", 750);

            runs(function ()
            {
                expect(appEventsTest.lastEventData).toEqual(template);
            });
        });
    }
	});

	describe("Migrated from manual comman spec", function(){

		it("Property 'appBundleFolder' should return path to folder of application bundle", function () {
			var path = Rho.Application.appBundleFolder;
			expect(path).toMatch(/\/app/);
			expect(Rho.RhoFile.isDir(path)).toBeTruthy();
    	});

		it("Property 'appsBundleFolder'", function () {
			var path = Rho.Application.appsBundleFolder
			//TODO: Need to add a check auto_common_spec should be the last in the path
			expect(path).toMatch(/auto_common_spec/);
			expect(Rho.RhoFile.isDir(path)).toBeTruthy();
    	});

    	if (isWindowsMobilePlatform()) {

	        it("Property 'badLinkURI'", function () {
	        	var badlink_uri = Rho.Application.badLinkURI;
				badlink_uri = badlink_uri.split("file://")[1];
				//alert(badlink_uri);
	        	expect(badlink_uri).toMatch(/BadLink.html/);
	        	expect(Rho.RhoFile.isFile(badlink_uri)).toBeTruthy();
	        });

    	}

    	it("Property \"configPath\"", function () {
        	var path = Rho.Application.configPath;
        	expect(path).toMatch(/rhoconfig.txt/);
        	expect(Rho.RhoFile.isFile(path)).toBeTruthy();
    	});

    	it("Property \"appName\"", function () {
    		expect( Rho.Application.appName).toEqual("auto_common_spec");
    	});

    	it("Property \"publicFolder\"", function () {
    		var path = Rho.Application.publicFolder;
    		expect(path).toMatch(/public/);
    		expect(Rho.RhoFile.isDir(path)).toBeTruthy();
    	});

    	it("Property \"settingsPageURI\"", function () {
			Rho.Application.settingsPageURI = 'settings.html';
    		var path = Rho.Application.settingsPageURI;
    		expect(path).toMatch(/settings.html/);
    	});

	    it("Property \"splash\"", function () {
	    	var splash_settings = Rho.Application.splash;
	    	expect(splash_settings).toMatch(/delay|center|hcenter|vcenter|vzoom|hzoom|zoom/);
    	});

    	it("Property \"startURI\"", function () {
    		var start_path = Rho.Application.startURI;
    		expect(start_path).toMatch(/\/app\/ApplicationTest\/specRunner.html|\/app\/index.html/)
    	});

    	it("Property \"userFolder\"", function () {
    		var path = Rho.Application.userFolder;
    		expect(path).toMatch(/auto_common_spec/);
    		expect(Rho.RhoFile.isDir(path)).toBeTruthy();
    	});

    	it("Property \"version\"", function () {
    		var version = Rho.Application.version;
	        expect(version).toEqual("1.0");
    	});

    	it("Property \"databaseBlobFolder\"", function () {
    		var path = Rho.Application.databaseBlobFolder;
    		expect(path).toMatch(/db\/db-files/);
    		expect(Rho.RhoFile.isDir(path)).toBeTruthy();
    	});

    	it("Property \"modelsManifestPath\"", function () {
    		var path = Rho.Application.modelsManifestPath;
    		expect(path).toMatch(/app_manifest.txt/);
    		expect(Rho.RhoFile.isFile(path)).toBeTruthy();
    	});

    	it("Property \"securityTokenNotPassed\" should return false if security token don't specified at build.yml", function () {
	        expect(Rho.Application.securityTokenNotPassed).toBeFalsy();
    	});

	});

});
<commit_msg>Added script fix for userFolder<commit_after>var appEventsTest = {};

appEventsTest.ajax = function(url)
{
	var ajax = new XMLHttpRequest();
	//ajax.onreadystatechange = function () {} //Async call
	ajax.open("GET", url, false); //Sync Call
	ajax.send();
	return ajax.responseText;
};

appEventsTest.setCallback = function ()
{
    Rho.Application.setApplicationNotify( function(params)
    {
        event = params.applicationEvent;
        eventData = params.eventData;

        appEventsTest.lastEvent = event;
        appEventsTest.lastEventData = eventData;
        appEventsTest.eventList.push(event);
        appEventsTest.callbackFired = true;
    });
};

describe("Application JS API", function () {

    beforeEach(function(){
        var matchers = {
            isNotEmptyString: function () {
                return (typeof this.actual == 'string') && (this.actual.length != 0)
            }
        };

        this.addMatchers(
            matchers
        );

    });

	describe("Basic specs", function () {

	    it("Test appBundleFolder property", function () {
	        var result = Rho.Application.appBundleFolder;
			Rho.Log.info(" Rho.Application.appBundleFolder = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    it("Test appsBundleFolder proeprty", function () {
	        var result = Rho.Application.appsBundleFolder;
			Rho.Log.info(" Rho.Application.appsBundleFolder = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    it("Test userFolder property", function () {
	        var result = Rho.Application.userFolder;
			Rho.Log.info(" Rho.Application.userFolder = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    xit("Test configPath property", function () {
	        var result = Rho.Application.configPath;
			Rho.Log.info(" Rho.Application.configPath = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    it("Test modelsManifestPath property", function () {
	        var result = Rho.Application.modelsManifestPath;
			Rho.Log.info(" Rho.Application.modelsManifestPath = " + result, "App");
 			expect(result).isNotEmptyString(0);
	    });

	    it("Test databaseBlobFolder property", function () {
	        var result = Rho.Application.databaseBlobFolder;
			Rho.Log.info(" Rho.Application.databaseBlobFolder = " + result, "App");
 			expect(result).isNotEmptyString(0);
	    });

	    it("Test publicFolder property", function () {
	        var result = Rho.Application.publicFolder;
			Rho.Log.info(" Rho.Application.publicFolder = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    it("Test startURI property", function () {
	        Rho.Application.startURI = 'index.html';
	        var result = Rho.Application.startURI;
			Rho.Log.info(" Rho.Application.startURI = " + result, "App");
 			expect(result).toEqual('index.html');
            Rho.Application.startURI = '/app/index.html';
	    });

	    it("Test settingsPageURI property", function () {
	        Rho.Application.settingsPageURI = 'settings.html';
	        var result = Rho.Application.settingsPageURI;
			Rho.Log.info(" Rho.Application.settingsPageURI = " + result, "App");
 			expect(result).toEqual('settings.html');
	    });

	    it("Test splash property", function () {
	        var result = Rho.Application.splash;
			Rho.Log.info(" Rho.Application.splash = " + result, "App");
 			expect(result).isNotEmptyString();
	    });

	    it("Test version property", function () {
	        var result = Rho.Application.version;
			Rho.Log.info(" Rho.Application.version = " + result, "App");
 			expect(result).toEqual("1.0");
	    });

	    it("Test name property", function () {
	    	var result = Rho.Application.appName;
			Rho.Log.info(" Rho.Application.appName = " + result, "App");
			expect(result).toEqual("auto_common_spec");
			var result2 = Rho.Application.getAppName();
	        expect(result2).toEqual("auto_common_spec");
	    });

	    //TODO: Implement Localization for Javascript app
	    //it("Current application locale.Like 'en', 'ru' etc", function(){
	    //	expect(Rho.Application.getLocale()).isNotEmptyString();
	    //});

	    //TODO: Implement Country for Javascript app
	    //it("Current application country code", function(){
	    //	expect(Rho.Application.getCountry()).isNotEmptyString();
	    //});

	    //TODO: implement modelFolderPath method

	    //TODO: implement databaseFilePath method

	    //TODO: implement expandDatabaseBlobFilePath method

	    //TODO: implement quit method

	    //TODO: implement modelFolderPath method

	    it("Test minimize method", function () {
	        expect(Rho.Application.minimize).not.toThrow();
	    });

	    it("Test restore method", function () {
	        expect(Rho.Application.restore).not.toThrow();
	    });

	    //TODO: implement spec for setActivationNotify with callback on all platforms

	    //TODO: implement spec for getRhoPlatformVersion with callback

	    if(isWindowsMobilePlatform()){
	        it("Bad link URI to navigate in browser", function () {
	            Rho.Application.badLinkURI = 'badLink.html';
	            expect(Rho.Application.badLinkURI).toEqual('badLink.html');
	        });
	    }

	    if (['WINDOWS_DESKTOP', 'WINDOWS'].indexOf(Rho.System.platform) != -1) {

	        it("Test title property", function () {
	            expect(Rho.Application.title).isNotEmptyString();

	            Rho.Application.title = 'Title';
	            expect(Rho.Application.title).toEqual('Title');
	        });

	    }

	});

	describe('Events specs', function() {
    if (isApplePlatform()) {
        beforeEach(function() {
            Rho.AppEvents.simulateEvent(Rho.AppEvents.APP_EVENT_ACTIVATED);
            Rho.AppEvents.simulateEvent(Rho.AppEvents.APP_EVENT_UICREATED);
            appEventsTest.callbackFired = false;
            appEventsTest.lastEvent = "";
            appEventsTest.lastEventData = {};
            appEventsTest.eventList = [];
        });

        it('Should fire callback', function(){
            runs(function ()
            {
                appEventsTest.setCallback();
                // state is "activated" should be changed
                Rho.AppEvents.simulateEvent(Rho.AppEvents.APP_EVENT_DEACTIVATED);
            });

            waitsFor(function ()
            {
                return appEventsTest.callbackFired;
            }, "the callback didnt fire", 750);

            runs(function ()
            {
                expect(appEventsTest.lastEvent).toEqual(Rho.AppEvents.APP_EVENT_DEACTIVATED);
            });
        });

        it('Should fire callback not once', function(){
            events = [
                Rho.AppEvents.APP_EVENT_DEACTIVATED,
                Rho.AppEvents.APP_EVENT_UIDESTROYED,
                Rho.AppEvents.APP_EVENT_UICREATED,
                Rho.AppEvents.APP_EVENT_ACTIVATED
            ];

            runs(function ()
            {
                appEventsTest.setCallback();
                for(var i = 0; i < events.length; i++)
                {
                    Rho.AppEvents.simulateEvent(events[i]);
                }
            });

            waitsFor(function ()
            {
                return appEventsTest.eventList.length == events.length;
            }, "the callback didnt fire", 750);

            runs(function ()
            {
                expect(appEventsTest.eventList).toEqual(events);
            });
        });

        it('Should not duplicate callbacks', function(){
            events = [
                Rho.AppEvents.APP_EVENT_DEACTIVATED,
                Rho.AppEvents.APP_EVENT_UIDESTROYED,
                Rho.AppEvents.APP_EVENT_ACTIVATED,
                Rho.AppEvents.APP_EVENT_UICREATED
            ];

            runs(function ()
            {
                appEventsTest.setCallback();
                for(var i = 0; i < events.length; i++)
                {
                    Rho.AppEvents.simulateEvent(events[i]);
                    Rho.AppEvents.simulateEvent(events[i]);
                }
            });

            waitsFor(function ()
            {
                return appEventsTest.eventList.length == events.length;
            }, "the callback didnt fire", 750);

            runs(function ()
            {
                expect(appEventsTest.eventList).toEqual(events);
            });
        });

        it('Should handle conflicts', function(){
            template = {
              "intProp" : ['128', '42'],
              "stringProp" : ["ohr","abc"]
            };

            runs(function ()
            {
                appEventsTest.setCallback();
                Rho.AppEvents.addConflictInt("intProp",64,128);
                Rho.AppEvents.addConflictString("stringProp","rho","ohr");
                Rho.AppEvents.simulateConflicts();
            });

            waitsFor(function ()
            {
                return appEventsTest.callbackFired;
            }, "the callback didnt fire", 750);

            runs(function ()
            {
                expect(appEventsTest.lastEventData).toEqual(template);
            });
        });
    }
	});

	describe("Migrated from manual comman spec", function(){

		it("Property 'appBundleFolder' should return path to folder of application bundle", function () {
			var path = Rho.Application.appBundleFolder;
			expect(path).toMatch(/\/app/);
			expect(Rho.RhoFile.isDir(path)).toBeTruthy();
    	});

		it("Property 'appsBundleFolder'", function () {
			var path = Rho.Application.appsBundleFolder
			//TODO: Need to add a check auto_common_spec should be the last in the path
			//expect(path).toMatch(/auto_common_spec/);
            if(isApplePlatform())
                expect(path).toMatch(/Library\/Caches\/Private Documents\/apps/);
            else
                expect(path).toMatch(/auto_common_spec/);
			expect(Rho.RhoFile.isDir(path)).toBeTruthy();
    	});

    	if (isWindowsMobilePlatform()) {

	        it("Property 'badLinkURI'", function () {
	        	var badlink_uri = Rho.Application.badLinkURI;
				badlink_uri = badlink_uri.split("file://")[1];
				//alert(badlink_uri);
	        	expect(badlink_uri).toMatch(/BadLink.html/);
	        	expect(Rho.RhoFile.isFile(badlink_uri)).toBeTruthy();
	        });

    	}

    	it("Property \"configPath\"", function () {
        	var path = Rho.Application.configPath;
        	expect(path).toMatch(/rhoconfig.txt/);
        	expect(Rho.RhoFile.isFile(path)).toBeTruthy();
    	});

    	it("Property \"appName\"", function () {
    		expect( Rho.Application.appName).toEqual("auto_common_spec");
    	});

    	it("Property \"publicFolder\"", function () {
    		var path = Rho.Application.publicFolder;
    		expect(path).toMatch(/public/);
    		expect(Rho.RhoFile.isDir(path)).toBeTruthy();
    	});

    	it("Property \"settingsPageURI\"", function () {
			Rho.Application.settingsPageURI = 'settings.html';
    		var path = Rho.Application.settingsPageURI;
    		expect(path).toMatch(/settings.html/);
    	});

	    it("Property \"splash\"", function () {
	    	var splash_settings = Rho.Application.splash;
	    	expect(splash_settings).toMatch(/delay|center|hcenter|vcenter|vzoom|hzoom|zoom/);
    	});

    	it("Property \"startURI\"", function () {
    		var start_path = Rho.Application.startURI;
    		expect(start_path).toMatch(/\/app\/ApplicationTest\/specRunner.html|\/app\/index.html/)
    	});

    	it("Property \"userFolder\"", function () {
    		var path = Rho.Application.userFolder;
    		//expect(path).toMatch(/auto_common_spec/);
            if(isApplePlatform())
                expect(path).toMatch(/Documents\/apps/);
            else
                expect(path).toMatch(/auto_common_spec/);
    		expect(Rho.RhoFile.isDir(path)).toBeTruthy();
    	});

    	it("Property \"version\"", function () {
    		var version = Rho.Application.version;
	        expect(version).toEqual("1.0");
    	});

    	it("Property \"databaseBlobFolder\"", function () {
    		var path = Rho.Application.databaseBlobFolder;
    		expect(path).toMatch(/db\/db-files/);
    		expect(Rho.RhoFile.isDir(path)).toBeTruthy();
    	});

    	it("Property \"modelsManifestPath\"", function () {
    		var path = Rho.Application.modelsManifestPath;
    		expect(path).toMatch(/app_manifest.txt/);
    		expect(Rho.RhoFile.isFile(path)).toBeTruthy();
    	});

    	it("Property \"securityTokenNotPassed\" should return false if security token don't specified at build.yml", function () {
	        expect(Rho.Application.securityTokenNotPassed).toBeFalsy();
    	});

	});

});
<|endoftext|>


<commit_before>import path from 'path';
import Service from './Service';

/**
 * Make it easier to write batch jobs by reusing service config without
 * a server. This function manages service startup and shutdown, and runs
 * asyncFn between those two. Supported options:
 *   name: The service name, taken from package.json if not specified
 *   serviceClass: The constructor for your service, defaults to @gasbuddy/service#Service
 *   srcRoot: The root directory of your source files,
 *      defaults to cwd()+/src or cwd()+/build in prod
 */
export async function runWithService(asyncFn, options) {
  const opts = options || {};

  if (!opts.name) {
    // eslint-disable-next-line global-require, import/no-dynamic-require
    const pkg = require(path.join(process.cwd(), 'package.json'));
    opts.name = pkg.name.replace(/^@[^/]+\//, '');
  }

  if (!opts.srcRoot) {
    if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
      opts.srcRoot = path.join(process.cwd(), 'build');
    } else {
      opts.srcRoot = path.join(process.cwd(), 'src');
    }
  }

  const ServiceClass = opts.serviceClass || Service;
  const service = new ServiceClass(opts.name);
  if (opts.onConfigurationLoaded) {
    service.onConfigurationLoaded(opts.onConfigurationLoaded);
  }

  return service.configure(opts.srcRoot)
    .then(asyncFn)
    .then(() => service.destroy())
    .catch((e) => {
      if (service.logger) {
        service.logger.error('Failed to complete service cleanup', service.wrapError(e));
        service.destroy();
      } else {
        // eslint-disable-next-line
        console.error('Service configuration failed', e);
      }
      process.exitCode = -1;
    });
}
<commit_msg>Safer error printing<commit_after>import path from 'path';
import Service from './Service';

/**
 * Make it easier to write batch jobs by reusing service config without
 * a server. This function manages service startup and shutdown, and runs
 * asyncFn between those two. Supported options:
 *   name: The service name, taken from package.json if not specified
 *   serviceClass: The constructor for your service, defaults to @gasbuddy/service#Service
 *   srcRoot: The root directory of your source files,
 *      defaults to cwd()+/src or cwd()+/build in prod
 */
export async function runWithService(asyncFn, options) {
  const opts = options || {};

  if (!opts.name) {
    // eslint-disable-next-line global-require, import/no-dynamic-require
    const pkg = require(path.join(process.cwd(), 'package.json'));
    opts.name = pkg.name.replace(/^@[^/]+\//, '');
  }

  if (!opts.srcRoot) {
    if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
      opts.srcRoot = path.join(process.cwd(), 'build');
    } else {
      opts.srcRoot = path.join(process.cwd(), 'src');
    }
  }

  const ServiceClass = opts.serviceClass || Service;
  const service = new ServiceClass(opts.name);
  if (opts.onConfigurationLoaded) {
    service.onConfigurationLoaded(opts.onConfigurationLoaded);
  }

  return service.configure(opts.srcRoot)
    .then(asyncFn)
    .then(() => service.destroy())
    .catch((e) => {
      if (service.logger && service.logger.error) {
        service.logger.error('Failed to complete service cleanup', service.wrapError(e));
        service.destroy();
      } else {
        // eslint-disable-next-line
        console.error('Service configuration failed', e);
      }
      process.exitCode = -1;
    });
}
<|endoftext|>


<commit_before>/*************************************************
 * Copyright (c) 2015 Ansible, Inc.
 *
 * All Rights Reserved
 *************************************************/

/* jshint unused: vars */
export default ['addPermissionsTeamsList', 'addPermissionsUsersList', 'TemplateList', 'ProjectList',
    'InventoryList', 'CredentialList', '$compile', 'generateList',
    'OrganizationList', '$window',
    function(addPermissionsTeamsList, addPermissionsUsersList, TemplateList, ProjectList,
    InventoryList, CredentialList, $compile, generateList,
    OrganizationList, $window) {
    return {
        restrict: 'E',
        scope: {
            allSelected: '=',
            view: '@',
            dataset: '='
        },
        template: "

",
        link: function(scope, element, attrs, ctrl) {
            let listMap, list, list_html;

            listMap = {
                Teams: addPermissionsTeamsList,
                Users: addPermissionsUsersList,
                Projects: ProjectList,
                JobTemplates: TemplateList,
                WorkflowTemplates: TemplateList,
                Inventories: InventoryList,
                Credentials: CredentialList,
                Organizations: OrganizationList
            };
            list = _.cloneDeep(listMap[scope.view]);
            list.multiSelect = true;
            list.multiSelectExtended = true;
            list.listTitleBadge = false;
            delete list.actions;
            delete list.fieldActions;

            switch(scope.view){

                case 'Projects':
                    list.fields = {
                        name: list.fields.name,
                        scm_type: list.fields.scm_type
                    };
                    list.fields.name.ngClick = 'linkoutResource("project", project)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.scm_type.columnClass = 'col-md-5 col-sm-5 hidden-xs';
                    break;

                case 'Inventories':
                    list.fields = {
                        name: list.fields.name,
                        organization: list.fields.organization
                    };
                    list.fields.name.ngClick = 'linkoutResource("inventory", inventory)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.organization.columnClass = 'col-md-5 col-sm-5 hidden-xs';
                    break;

                case 'JobTemplates':
                    list.name = 'job_templates';
                    list.iterator = 'job_template';
                    list.basePath = 'job_templates';
                    list.fields = {
                        name: list.fields.name
                    };
                    list.fields.name.ngClick = 'linkoutResource("job_template", job_template)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.name.ngHref = '#/templates/job_template/{{job_template.id}}';
                    break;

                case 'WorkflowTemplates':
                    list.name = 'workflow_templates';
                    list.iterator = 'workflow_template';
                    list.basePath = 'workflow_job_templates';
                    list.fields = {
                        name: list.fields.name
                    };
                    list.fields.name.ngClick = 'linkoutResource("workflow_job_template", workflow_template)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.name.ngHref = '#/templates/workflow_job_template/{{workflow_template.id}}';
                    break;
                case 'Users':
                    list.fields = {
                        username: list.fields.username,
                        first_name: list.fields.first_name,
                        last_name: list.fields.last_name
                    };
                    list.fields.username.ngClick = 'linkoutResource("user", user)';
                    list.fields.username.columnClass = 'col-md-5 col-sm-5 col-xs-11';
                    list.fields.first_name.columnClass = 'col-md-3 col-sm-3 hidden-xs';
                    list.fields.last_name.columnClass = 'col-md-3 col-sm-3 hidden-xs';
                    break;
                case 'Teams':
                    list.fields = {
                        name: list.fields.name,
                        organization: list.fields.organization,
                    };
                    list.fields.name.ngClick = 'linkoutResource("team", team)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.organization.columnClass = 'col-md-5 col-sm-5 hidden-xs';
                    break;
                case 'Organizations':
                    list.fields = {
                        name: list.fields.name
                    };
                    list.fields.name.ngClick = 'linkoutResource("organization", organization)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    break;
                case 'Credentials':
                    list.fields = {
                        name: list.fields.name
                    };
                    list.fields.name.ngClick = 'linkoutResource("credential", credential)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    break;
                default:
                    list.fields = {
                        name: list.fields.name,
                        description: list.fields.description
                    };
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.description.columnClass = 'col-md-5 col-sm-5 hidden-xs';
            }

            list_html = generateList.build({
                mode: 'edit',
                list: list,
                related: false,
                title: false,
                hideViewPerPage: true
            });

            scope.list = list;
            scope[`${list.iterator}_dataset`] = scope.dataset.data;
            scope[`${list.name}`] = scope[`${list.iterator}_dataset`].results;

            scope.$watch(list.name, function(){
                _.forEach(scope[`${list.name}`], isSelected);
                optionsRequestDataProcessing();
            });

            scope.$on(`${list.iterator}_options`, function(event, data){
                scope.options = data.data.actions.GET;
                optionsRequestDataProcessing();
            });

            // iterate over the list and add fields like type label, after the
            // OPTIONS request returns, or the list is sorted/paginated/searched
            function optionsRequestDataProcessing(){
                if(scope.list.name === 'projects'){
                    if (scope[list.name] !== undefined) {
                        scope[list.name].forEach(function(item, item_idx) {
                            var itm = scope[list.name][item_idx];

                            // Set the item type label
                            if (list.fields.scm_type && scope.options &&
                                scope.options.hasOwnProperty('scm_type')) {
                                    scope.options.scm_type.choices.forEach(function(choice) {
                                        if (choice[0] === item.scm_type) {
                                            itm.type_label = choice[1];
                                        }
                                    });
                            }

                        });
                    }
                }
            }

            function isSelected(item){
                if(_.find(scope.allSelected, {id: item.id, type: item.type})){
                    item.isSelected = true;
                }
                return item;
            }
            element.append(list_html);
            $compile(element.contents())(scope);

            scope.linkoutResource = function(type, resource) {

                let url;

                switch(type){
                    case 'project':
                        url = "/#/projects/" + resource.id;
                        break;
                    case 'inventory':
                        url = resource.kind && resource.kind === "smart" ? "/#/inventories/smart/" + resource.id : "/#/inventories/inventory/" + resource.id;
                        break;
                    case 'job_template':
                        url = "/#/templates/job_template/" + resource.id;
                        break;
                    case 'workflow_job_template':
                        url = "/#/templates/workflow_job_template/" + resource.id;
                        break;
                    case 'user':
                        url = "/#/users/" + resource.id;
                        break;
                    case 'team':
                        url = "/#/teams/" + resource.id;
                        break;
                    case 'organization':
                        url = "/#/organizations/" + resource.id;
                        break;
                    case 'credential':
                        url = "/#/credentials/" + resource.id;
                        break;
                }

                $window.open(url,'_blank');
            };
        }
    };

}];
<commit_msg>Fixed inv permissions checkbox bug<commit_after>/*************************************************
 * Copyright (c) 2015 Ansible, Inc.
 *
 * All Rights Reserved
 *************************************************/

/* jshint unused: vars */
export default ['addPermissionsTeamsList', 'addPermissionsUsersList', 'TemplateList', 'ProjectList',
    'InventoryList', 'CredentialList', '$compile', 'generateList',
    'OrganizationList', '$window',
    function(addPermissionsTeamsList, addPermissionsUsersList, TemplateList, ProjectList,
    InventoryList, CredentialList, $compile, generateList,
    OrganizationList, $window) {
    return {
        restrict: 'E',
        scope: {
            allSelected: '=',
            view: '@',
            dataset: '='
        },
        template: "

",
        link: function(scope, element, attrs, ctrl) {
            let listMap, list, list_html;

            listMap = {
                Teams: addPermissionsTeamsList,
                Users: addPermissionsUsersList,
                Projects: ProjectList,
                JobTemplates: TemplateList,
                WorkflowTemplates: TemplateList,
                Inventories: InventoryList,
                Credentials: CredentialList,
                Organizations: OrganizationList
            };
            list = _.cloneDeep(listMap[scope.view]);
            list.multiSelect = true;
            list.multiSelectExtended = true;
            list.listTitleBadge = false;
            delete list.actions;
            delete list.fieldActions;

            switch(scope.view){

                case 'Projects':
                    list.fields = {
                        name: list.fields.name,
                        scm_type: list.fields.scm_type
                    };
                    list.fields.name.ngClick = 'linkoutResource("project", project)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.scm_type.columnClass = 'col-md-5 col-sm-5 hidden-xs';
                    break;

                case 'Inventories':
                    list.fields = {
                        name: list.fields.name,
                        organization: list.fields.organization
                    };
                    list.fields.name.ngClick = 'linkoutResource("inventory", inventory)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.organization.columnClass = 'col-md-5 col-sm-5 hidden-xs';
                    delete list.disableRow;
                    break;

                case 'JobTemplates':
                    list.name = 'job_templates';
                    list.iterator = 'job_template';
                    list.basePath = 'job_templates';
                    list.fields = {
                        name: list.fields.name
                    };
                    list.fields.name.ngClick = 'linkoutResource("job_template", job_template)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.name.ngHref = '#/templates/job_template/{{job_template.id}}';
                    break;

                case 'WorkflowTemplates':
                    list.name = 'workflow_templates';
                    list.iterator = 'workflow_template';
                    list.basePath = 'workflow_job_templates';
                    list.fields = {
                        name: list.fields.name
                    };
                    list.fields.name.ngClick = 'linkoutResource("workflow_job_template", workflow_template)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.name.ngHref = '#/templates/workflow_job_template/{{workflow_template.id}}';
                    break;
                case 'Users':
                    list.fields = {
                        username: list.fields.username,
                        first_name: list.fields.first_name,
                        last_name: list.fields.last_name
                    };
                    list.fields.username.ngClick = 'linkoutResource("user", user)';
                    list.fields.username.columnClass = 'col-md-5 col-sm-5 col-xs-11';
                    list.fields.first_name.columnClass = 'col-md-3 col-sm-3 hidden-xs';
                    list.fields.last_name.columnClass = 'col-md-3 col-sm-3 hidden-xs';
                    break;
                case 'Teams':
                    list.fields = {
                        name: list.fields.name,
                        organization: list.fields.organization,
                    };
                    list.fields.name.ngClick = 'linkoutResource("team", team)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.organization.columnClass = 'col-md-5 col-sm-5 hidden-xs';
                    break;
                case 'Organizations':
                    list.fields = {
                        name: list.fields.name
                    };
                    list.fields.name.ngClick = 'linkoutResource("organization", organization)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    break;
                case 'Credentials':
                    list.fields = {
                        name: list.fields.name
                    };
                    list.fields.name.ngClick = 'linkoutResource("credential", credential)';
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    break;
                default:
                    list.fields = {
                        name: list.fields.name,
                        description: list.fields.description
                    };
                    list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11';
                    list.fields.description.columnClass = 'col-md-5 col-sm-5 hidden-xs';
            }

            list_html = generateList.build({
                mode: 'edit',
                list: list,
                related: false,
                title: false,
                hideViewPerPage: true
            });

            scope.list = list;
            scope[`${list.iterator}_dataset`] = scope.dataset.data;
            scope[`${list.name}`] = scope[`${list.iterator}_dataset`].results;

            scope.$watch(list.name, function(){
                _.forEach(scope[`${list.name}`], isSelected);
                optionsRequestDataProcessing();
            });

            scope.$on(`${list.iterator}_options`, function(event, data){
                scope.options = data.data.actions.GET;
                optionsRequestDataProcessing();
            });

            // iterate over the list and add fields like type label, after the
            // OPTIONS request returns, or the list is sorted/paginated/searched
            function optionsRequestDataProcessing(){
                if(scope.list.name === 'projects'){
                    if (scope[list.name] !== undefined) {
                        scope[list.name].forEach(function(item, item_idx) {
                            var itm = scope[list.name][item_idx];

                            // Set the item type label
                            if (list.fields.scm_type && scope.options &&
                                scope.options.hasOwnProperty('scm_type')) {
                                    scope.options.scm_type.choices.forEach(function(choice) {
                                        if (choice[0] === item.scm_type) {
                                            itm.type_label = choice[1];
                                        }
                                    });
                            }

                        });
                    }
                }
            }

            function isSelected(item){
                if(_.find(scope.allSelected, {id: item.id, type: item.type})){
                    item.isSelected = true;
                }
                return item;
            }
            element.append(list_html);
            $compile(element.contents())(scope);

            scope.linkoutResource = function(type, resource) {

                let url;

                switch(type){
                    case 'project':
                        url = "/#/projects/" + resource.id;
                        break;
                    case 'inventory':
                        url = resource.kind && resource.kind === "smart" ? "/#/inventories/smart/" + resource.id : "/#/inventories/inventory/" + resource.id;
                        break;
                    case 'job_template':
                        url = "/#/templates/job_template/" + resource.id;
                        break;
                    case 'workflow_job_template':
                        url = "/#/templates/workflow_job_template/" + resource.id;
                        break;
                    case 'user':
                        url = "/#/users/" + resource.id;
                        break;
                    case 'team':
                        url = "/#/teams/" + resource.id;
                        break;
                    case 'organization':
                        url = "/#/organizations/" + resource.id;
                        break;
                    case 'credential':
                        url = "/#/credentials/" + resource.id;
                        break;
                }

                $window.open(url,'_blank');
            };
        }
    };

}];
<|endoftext|>


<commit_before>// HTTP protocol, based on S4A's

IDE_Morph.prototype.originalInit = IDE_Morph.prototype.init;
IDE_Morph.prototype.init = function (globals) {
    this.originalInit(globals);

    var myself = this;

    if (this.httpServer) { this.httpServer.close() };
    this.httpServer = require('http').createServer(function(request, response) { myself.handleHTTPRequest(request, response) });
    this.httpServer.setTimeout(500);

    this.isServerOn = false;
};

IDE_Morph.prototype.toggleServer = function () {
    if (this.isServerOn) {
        this.stopServer();
    } else {
        this.startServer();
    }
};

IDE_Morph.prototype.startServer = function () {
    var myself = this,
        ifaces = require('os').networkInterfaces(),
        iips = '',
        eips = '';

    Object.keys(ifaces).forEach(function (ifname) {
        ifaces[ifname].forEach(function (iface) {
            if (iface.family =='IPv4') {
                if (iface.internal) {
                    iips += 'http://' + iface.address + ':42001\n';
                } else {
                    eips += 'http://' + iface.address + ':42001\n';
                }
            }
        });
    });

    this.httpServer.listen(
            42001,
            function() {
                myself.isServerOn = true;
                myself.inform(
                        'HTTP server',
                        'This Snap4Arduino instance can be remotely\n'
                        + 'controlled from the following addresses:\n\n'
                        + 'Internal URLs:\n'
                        + iips
                        + '\nExternal URLs:\n'
                        + eips)
            });
};

IDE_Morph.prototype.stopServer = function () {
    var myself = this;
    myself.isServerOn = false;
    this.httpServer.close(
            function () {
                myself.inform('HTTP server', 'HTTP server connection closed');
            });
};

IDE_Morph.prototype.handleHTTPRequest = function (request, response) {
    if (!this.isServerOn) { return; };

    var myself = this;

    response.setHeader('Access-Control-Allow-Origin', '*');
    function parse(message) {

        if (message.length > 0) {

            // If the command came inside a POST body, it needs to be split by spaces,
            // otherwise it came in a GET URL and it needs to be split by "="

            var command = message.indexOf('=') > 0 ? message.split('=') : message.split(' ');

            switch (command[0]) {
                case 'broadcast':
                    var bcMessage = typeof command[1] !== 'undefined' ? message.slice(10) : '',
                        stage = myself.stage,
                        rcvrs = stage.children.concat(stage);

                    if (bcMessage.length > 0) {

                        stage.lastMessage = bcMessage;

                        rcvrs.forEach(function (morph) {
                            if (morph instanceof SpriteMorph || morph instanceof StageMorph) {
                                morph.allHatBlocksFor(bcMessage).forEach(function (block) {
                                    stage.threads.startProcess(
                                        block,
                                        morph,
                                        stage.isThreadSafe
                                )});
                            }
                        });

                        response.end('broadcast ' + bcMessage);

                    } else {
                        response.end('no message provided');
                    }
                    break;

                case 'vars-update':
                    var varName = command[1],
                        value = command[2],
                        stage = myself.stage;

                    if (Object.keys(stage.globalVariables().vars).indexOf(varName) == -1) {
                        response.end('variable ' + varName + ' does not exist');
                    } else {
                        stage.globalVariables().setVar(varName, value, stage);
                        response.end('updating variable ' + command[1] + ' to value ' + command[2]);
                    }
                    break;

                case 'send-messages':
                    var contents = 'broadcast',
                        stage = myself.stage;

                    stage.children.concat(stage).forEach(function (morph) {
                        if (morph instanceof SpriteMorph || morph instanceof StageMorph) {
                            morph.allMessageNames().forEach(function (message) {
                                contents += ' "' + message + '"';
                            });
                        }
                    });

                    response.end(contents);
                    break;

                case 'send-vars':
                    var contents = 'sensor-update',
                        stage = myself.stage;

                    Object.keys(stage.globalVariables().vars).forEach(function (varName) {
                        contents += ' "' + varName + '" ' + stage.globalVariables().vars[varName].value.toString();
                    });

                    response.end(contents);
                    break;

                case 'send-var':
                    var stage = myself.stage,
                        varName = command[1];

                    response.end(stage.globalVariables().vars[varName].value.toString());
                    break;

                case 'stage':
                    var contents = '';
                    response.end(contents);
                    break;

                case 'stageimg':
                    response.setHeader('Cache-Control', 'no-cache');
                    response.end(myself.stage.fullImageClassic().toDataURL());
                    break;

                case 'push':
                    response.end('Pushing project to file system');
                    var str = myself.serializer.serialize(myself.stage);
                    require('fs').writeFile(homePath() + 'autorun.xml', str);
                    break;
            }
        }
    }

    if (request.method === 'POST') {

        var body = '';

        request.addListener('data', function(chunk) {
            body += chunk;
        });

        request.addListener('end', function(chunk){
            if (chunk) {
                body += chunk;
            }
            parse(body);
        });

    } else if (request.method === 'GET') {
        parse(request.url.slice(1));
    }

    response.end('Unknown command');
};

<commit_msg>Fixing some issues in httpserver feature (avoiding problems with some requests) and enabling POST to update multiple vars<commit_after>// HTTP protocol, based on S4A's

IDE_Morph.prototype.originalInit = IDE_Morph.prototype.init;
IDE_Morph.prototype.init = function (globals) {
    this.originalInit(globals);

    var myself = this;

    if (this.httpServer) { this.httpServer.close() };
    this.httpServer = require('http').createServer(function(request, response) { myself.handleHTTPRequest(request, response) });
    this.httpServer.setTimeout(500);

    this.isServerOn = false;
};

IDE_Morph.prototype.toggleServer = function () {
    if (this.isServerOn) {
        this.stopServer();
    } else {
        this.startServer();
    }
};

IDE_Morph.prototype.startServer = function () {
    var myself = this,
        ifaces = require('os').networkInterfaces(),
        iips = '',
        eips = '';

    Object.keys(ifaces).forEach(function (ifname) {
        ifaces[ifname].forEach(function (iface) {
            if (iface.family =='IPv4') {
                if (iface.internal) {
                    iips += 'http://' + iface.address + ':42001\n';
                } else {
                    eips += 'http://' + iface.address + ':42001\n';
                }
            }
        });
    });

    this.httpServer.listen(
            42001,
            function() {
                myself.isServerOn = true;
                myself.inform(
                        'HTTP server',
                        'This Snap4Arduino instance can be remotely\n'
                        + 'controlled from the following addresses:\n\n'
                        + 'Internal URLs:\n'
                        + iips
                        + '\nExternal URLs:\n'
                        + eips)
            });
};

IDE_Morph.prototype.stopServer = function () {
    var myself = this;
    myself.isServerOn = false;
    this.httpServer.close(
            function () {
                myself.inform('HTTP server', 'HTTP server connection closed');
            });
};

IDE_Morph.prototype.handleHTTPRequest = function (request, response) {
    if (!this.isServerOn) { return; };

    var myself = this;

    response.setHeader('Access-Control-Allow-Origin', '*');
    function parse(message) {

        if (message.length > 0) {

            // If the command came inside a POST body, it needs to be split by spaces,
            // otherwise it came in a GET URL and it needs to be split by "="

            var command = message.indexOf('=') > 0 ? message.split('=') : message.split(' ');

            switch (command[0]) {
                case 'broadcast':
                    var bcMessage = typeof command[1] !== 'undefined' ? message.slice(10) : '',
                        stage = myself.stage,
                        rcvrs = stage.children.concat(stage);

                    if (bcMessage.length > 0) {

                        stage.lastMessage = bcMessage;

                        rcvrs.forEach(function (morph) {
                            if (morph instanceof SpriteMorph || morph instanceof StageMorph) {
                                morph.allHatBlocksFor(bcMessage).forEach(function (block) {
                                    stage.threads.startProcess(
                                        block,
                                        morph,
                                        stage.isThreadSafe
                                )});
                            }
                        });

                        response.write('broadcast ' + bcMessage);

                    } else {
                        response.write('No message provided');
                    }
                    break;

                case 'vars-update':
                    if (typeof command[1] == 'undefined' || command[1] == '') {
                        response.write('No variable provided');
                    } else {
                        var varName = command[1],
                            value = message.slice(command[0].length+command[1].length+2),
                            stage = myself.stage;

                        if (Object.keys(stage.globalVariables().vars).indexOf(varName) == -1) {
                            response.write('Variable ' + varName + ' does not exist');
                        } else {
                            stage.globalVariables().setVar(varName, value, stage);
                            response.write('Updating variable ' + command[1] + ' to value ' + value);
                        }
                    }
                    break;

                case 'send-messages':
                    var contents = 'broadcast',
                        stage = myself.stage;

                    stage.children.concat(stage).forEach(function (morph) {
                        if (morph instanceof SpriteMorph || morph instanceof StageMorph) {
                            morph.allMessageNames().forEach(function (message) {
                                contents += ' "' + message + '"';
                            });
                        }
                    });

                    response.write(contents);
                    break;

                case 'send-vars':
                    var contents = 'sensor-update',
                        stage = myself.stage;

                    Object.keys(stage.globalVariables().vars).forEach(function (varName) {
                        contents += ' "' + varName + '" ' + stage.globalVariables().vars[varName].value.toString();
                    });

                    response.write(contents);
                    break;

                case 'send-var':
                    var stage = myself.stage,
                        varName = command[1];
                    if (Object.keys(stage.globalVariables().vars).indexOf(varName) == -1) {
                        response.write('Variable ' + varName + ' does not exist');
                    } else {
                        response.write(stage.globalVariables().vars[varName].value.toString());
                    }
                    break;

                case 'stage':
                    var contents = '';
                    response.write(contents);
                    break;

                case 'stageimg':
                    response.setHeader('Cache-Control', 'no-cache');
                    response.write(myself.stage.fullImageClassic().toDataURL());
                    break;

                case 'push':
                    response.write('Pushing project to file system');
                    var str = myself.serializer.serialize(myself.stage);
                    require('fs').writeFile(homePath() + 'autorun.xml', str);
                    break;

                default:
                    response.write('Unknown command');

            }
        } else {
            response.write('No command provided');
        }
    }

    if (request.method === 'POST') {

        var body = '',
            bodys = [];

        request.addListener('data', function(chunk) {
            body += chunk;
        });

        request.addListener('end', function(chunk){
            if (chunk) {
                body += chunk;
            }
            bodys = body.split("&");
            response.write('POST processing...\n');
            bodys.forEach(function (item) {
                response.write('\n');
                parse('vars-update=' + item);
            });
            response.end('\n\nPOST completed');
        });

    } else if (request.method === 'GET') {
        parse(request.url.slice(1));
        response.end();

    } else {
        response.end('Unknown request');
    }
};
<|endoftext|>


<commit_before>import { timestamp, files, shell, routes } from '@sapper/service-worker';

const ASSETS = `cache${timestamp}`;

// `shell` is an array of all the files generated by the bundler,
// `files` is an array of everything in the `static` directory
console.log(files.filter((file) => {
	return ['.', '_', 'admin', 'sitemap'].reduce((result, string) => {
		result = !file.startsWith(string)
		return result
	}, false)
}))
const to_cache = shell.concat(files);
const cached = new Set(to_cache);

self.addEventListener('install', event => {
	event.waitUntil(
		caches
			.open(ASSETS)
			.then(cache => cache.addAll(to_cache))
			.then(() => {
				self.skipWaiting();
			})
	);
});

self.addEventListener('activate', event => {
	event.waitUntil(
		caches.keys().then(async keys => {
			// delete old caches
			for (const key of keys) {
				if (key !== ASSETS) await caches.delete(key);
			}

			self.clients.claim();
		})
	);
});

self.addEventListener('fetch', event => {
	if (event.request.method !== 'GET' || event.request.headers.has('range')) return;

	const url = new URL(event.request.url);

	// don't try to handle e.g. data: URIs
	if (!url.protocol.startsWith('http')) return;

	// ignore dev server requests
	if (url.hostname === self.location.hostname && url.port !== self.location.port) return;

	// always serve static files and bundler-generated assets from cache
	if (url.host === self.location.host && cached.has(url.pathname)) {
		event.respondWith(caches.match(event.request));
		return;
	}

	// for pages, you might want to serve a shell `service-worker-index.html` file,
	// which Sapper has generated for you. It's not right for every
	// app, but if it's right for yours then uncomment this section
	/*
	if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {
		event.respondWith(caches.match('/service-worker-index.html'));
		return;
	}
	*/

	if (event.request.cache === 'only-if-cached') return;

	// for everything else, try the network first, falling back to
	// cache if the user is offline. (If the pages never change, you
	// might prefer a cache-first approach to a network-first one.)
	event.respondWith(
		caches
			.open(`offline${timestamp}`)
			.then(async cache => {
				try {
					const response = await fetch(event.request);
					cache.put(event.request, response.clone());
					return response;
				} catch(err) {
					const response = await cache.match(event.request);
					if (response) return response;

					throw err;
				}
			})
	);
});
<commit_msg>[#139] remove extranous files from cache hopefully this resolves those errors on the _redirects file<commit_after>import { timestamp, files, shell, routes } from '@sapper/service-worker';

const ASSETS = `cache${timestamp}`;

// `shell` is an array of all the files generated by the bundler,
// `files` is an array of everything in the `static` directory
const to_cache = shell.concat(files.filter((file) => {
	// remove extraneous files like _redirects, sitemap, and system files
	return !file.startsWith('_')
		&& !file.startsWith('.')
		&& !file.startsWith('admin')
		&& !file.startsWith('sitemap')
}));
const cached = new Set(to_cache);

self.addEventListener('install', event => {
	event.waitUntil(
		caches
			.open(ASSETS)
			.then(cache => cache.addAll(to_cache))
			.then(() => {
				self.skipWaiting();
			})
	);
});

self.addEventListener('activate', event => {
	event.waitUntil(
		caches.keys().then(async keys => {
			// delete old caches
			for (const key of keys) {
				if (key !== ASSETS) await caches.delete(key);
			}

			self.clients.claim();
		})
	);
});

self.addEventListener('fetch', event => {
	if (event.request.method !== 'GET' || event.request.headers.has('range')) return;

	const url = new URL(event.request.url);

	// don't try to handle e.g. data: URIs
	if (!url.protocol.startsWith('http')) return;

	// ignore dev server requests
	if (url.hostname === self.location.hostname && url.port !== self.location.port) return;

	// always serve static files and bundler-generated assets from cache
	if (url.host === self.location.host && cached.has(url.pathname)) {
		event.respondWith(caches.match(event.request));
		return;
	}

	// for pages, you might want to serve a shell `service-worker-index.html` file,
	// which Sapper has generated for you. It's not right for every
	// app, but if it's right for yours then uncomment this section
	/*
	if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {
		event.respondWith(caches.match('/service-worker-index.html'));
		return;
	}
	*/

	if (event.request.cache === 'only-if-cached') return;

	// for everything else, try the network first, falling back to
	// cache if the user is offline. (If the pages never change, you
	// might prefer a cache-first approach to a network-first one.)
	event.respondWith(
		caches
			.open(`offline${timestamp}`)
			.then(async cache => {
				try {
					const response = await fetch(event.request);
					cache.put(event.request, response.clone());
					return response;
				} catch(err) {
					const response = await cache.match(event.request);
					if (response) return response;

					throw err;
				}
			})
	);
});
<|endoftext|>


<commit_before>import LOG_LEVEL from '../enum/logLevel';
import { hasAllKeys } from '../utils';

const requiredConfig = [
  'project',
  'environment',
];

const baseConfig = {
  // default minimum log level when it's not specified
  minLogLevel: LOG_LEVEL.ERROR,
};

// abstract base class for different logging services
class Logger {
  constructor(config) {
    this.config = Object.assign({}, baseConfig, config);
  }

  IsConfigValid() {
    return hasAllKeys(this.config, requiredConfig);
  }

  ShouldLog(logLevel) {
    return logLevel >= this.config.minLogLevel;
  }

  // this function must be implemented by individual service
  // Log(logLevel, logMessage, label) {
  // }
}

export default Logger;
<commit_msg>change default minimum log level<commit_after>import LOG_LEVEL from '../enum/logLevel';
import { hasAllKeys } from '../utils';

const requiredConfig = [
  'project',
  'environment',
];

const baseConfig = {
  // default minimum log level when it's not specified
  minLogLevel: LOG_LEVEL.INFO,
};

// abstract base class for different logging services
class Logger {
  constructor(config) {
    this.config = Object.assign({}, baseConfig, config);
  }

  IsConfigValid() {
    return hasAllKeys(this.config, requiredConfig);
  }

  ShouldLog(logLevel) {
    return logLevel >= this.config.minLogLevel;
  }

  // this function must be implemented by individual service
  // Log(logLevel, logMessage, label) {
  // }
}

export default Logger;
<|endoftext|>


<commit_before>export class SWAPI {

  getPlanetsAmount() {
    return fetch("http://swapi.co/api/planets/")
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.count;
    })
    .catch((error) => {
      console.warn(error);
    });
  }

  getPlanet(planetId) {
    return fetch("http://swapi.co/api/planets/"+planetId+"/")
    .then((response) => response.json())
    .then((responseJson) => {
      responseJson.filmsLength = responseJson.films.length+ " " + ((responseJson.films.length === 1) ? "film": "films");
      return responseJson;
    })
    .catch((error) => {
      console.warn(error);
    });
  }
}<commit_msg>add new calls in SWAPI<commit_after>export class SWAPI {

  getPlanetsAmount() {
    return fetch("http://swapi.co/api/planets/")
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.count;
    })
    .catch((error) => {
      console.warn(error);
    });
  }

  getPlanet(planetId) {
    return fetch("http://swapi.co/api/planets/"+planetId+"/")
    .then((response) => response.json())
    .then((responseJson) => {
      responseJson.filmsLength = responseJson.films.length+ " " + ((responseJson.films.length === 1) ? "film": "films");
      return responseJson;
    })
    .catch((error) => {
      console.warn(error);
    });
  }

  getFilm(filmId) {
    return fetch("http://swapi.co/api/films/"+filmId+"/")
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson;
    })
    .catch((error) => {
      console.warn(error);
    });
  }

  getPerson(personId) {
    return fetch("http://swapi.co/api/people/"+personId+"/")
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson;
    })
    .catch((error) => {
      console.warn(error);
    });
  }

  getSpecie(specieId) {
    return fetch("http://swapi.co/api/species/"+specieId+"/")
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson;
    })
    .catch((error) => {
      console.warn(error);
    });
  }

  getStarship(starshipId) {
    return fetch("http://swapi.co/api/starships/"+starshipId+"/")
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson;
    })
    .catch((error) => {
      console.warn(error);
    });
  }

  getVehicle(vehicleId) {
    return fetch("http://swapi.co/api/vehicles/"+vehicleId+"/")
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson;
    })
    .catch((error) => {
      console.warn(error);
    });
  }
}<|endoftext|>


<commit_before>/*
 * Orange angular-swagger-ui - v0.3.0
 *
 * (C) 2015 Orange, all right reserved
 * MIT Licensed
 */
'use strict';

angular
    .module('swaggerUi')
    .factory('swaggerModel', function ($log) {
        /**
         * sample object cache to avoid generating the same one multiple times
         */
        var objCache = {};

        /**
         * model cache to avoid generating the same one multiple times
         */
        var modelCache = {};

        /**
         * inline model counter
         */
        var countInLine = 0;

        return {
            generateModel: generateModel,
            getType: getType,
            resolveReference: resolveReference,
            generateSampleJson: generateSampleJson,
            clearCache: clearCache
        };

        /**
         * clears generated models cache
         */
        function clearCache () {
            objCache = {};
            modelCache = {};
        }

        /**
         * retrieves object definition
         */
        function resolveReference (swagger, object) {
            if (object.$ref) {
                var parts = object.$ref.replace('#/', '').split('/');
                object = swagger;
                for (var i = 0, j = parts.length; i < j; i++) {
                    object = object[parts[i]];
                }
            }
            return object;
        }

        /**
         * determines a property type
         */
        function getType (item) {
            var format = item.format;
            switch (format) {
                case 'int32':
                    format = item.type;
                    break;
                case 'int64':
                    format = 'long';
                    break;
            }
            return format || item.type;
        }

        /**
         * retrieves object class name based on $ref
         */
        function getClassName (item) {
            var parts = item.$ref.split('/');
            return parts[parts.length - 1];
        }

        /**
         * generates a sample object (request body or response body)
         */
        function getSampleObj (swagger, schema, currentGenerated) {
            var sample;
            currentGenerated = currentGenerated || {}; // used to handle circular references
            if (schema.default || schema.example) {
                sample = schema.default || schema.example;
            } else if (schema.properties) {
                sample = {};

                angular.forEach(schema.properties, function (v, name) {
                    sample[name] = getSampleObj(swagger, v, currentGenerated);
                });
            } else if (schema.$ref) {
                // complex object
                var def = resolveReference(swagger, schema);

                if (def) {
                    if (!objCache[schema.$ref] && !currentGenerated[schema.$ref]) {
                        // object not in cache
                        currentGenerated[schema.$ref] = true;
                        objCache[schema.$ref] = getSampleObj(swagger, def, currentGenerated);
                    }

                    sample = objCache[schema.$ref] || {};
                } else {
                    $log.warn('schema not found', schema.$ref);
                }
            } else if (schema.type === 'array') {
                sample = [getSampleObj(swagger, schema.items, currentGenerated)];
            } else if (schema.type === 'object') {
                sample = {};
            } else {
                sample = schema.defaultValue || schema.example || getSampleValue(getType(schema));
            }
            return sample;
        }

        /**
         * generates a sample value for a basic type
         */
        function getSampleValue (type) {
            var result;
            switch (type) {
                case 'long':
                case 'integer':
                    result = 0;
                    break;
                case 'boolean':
                    result = false;
                    break;
                case 'double':
                case 'number':
                    result = 0.0;
                    break;
                case 'string':
                    result = 'string';
                    break;
                case 'date':
                    result = (new Date()).toISOString().split('T')[0];
                    break;
                case 'date-time':
                    result = (new Date()).toISOString();
                    break;
            }
            return result;
        }

        /**
         * generates a sample JSON string (request body or response body)
         */
        function generateSampleJson (swagger, schema) {
            var json;
            var obj = getSampleObj(swagger, schema);

            if (obj) {
                json = angular.toJson(obj, true);
            }
            return json;
        }

        /**
         * generates object's model
         */
        function generateModel (swagger, schema, modelName, currentGenerated) {
            var model = '';
            var buffer;
            var subModels;
            var propertyName;
            var property;
            var hasProperties = false;
            var name;
            var className;
            var def;
            var sub;

            currentGenerated = currentGenerated || {}; // used to handle circular references

            function isRequired (item, name) {
                return item.required && item.required.indexOf(name) !== -1;
            }

            if (schema.properties) {
                modelName = modelName || ('Inline Model' + countInLine++);
                currentGenerated[modelName] = true;
                buffer = ['
' + modelName + ' {'];
                subModels = [];

                angular.forEach(schema.properties, function (property, propertyName) {
                    hasProperties = true;
                    buffer.push('
', propertyName, ' (');

                    // build type
                    if (property.properties) {
                        name = 'Inline Model' + countInLine++;
                        buffer.push(name);
                        subModels.push(generateModel(swagger, property, name, currentGenerated));
                    } else if (property.$ref) {
                        buffer.push(getClassName(property));
                        subModels.push(generateModel(swagger, property, null, currentGenerated));
                    } else if (property.type === 'array') {
                        buffer.push('Array[');
                        if (property.items.properties) {
                            name = 'Inline Model' + countInLine++;
                            buffer.push(name);
                            subModels.push(generateModel(swagger, property, name, currentGenerated));
                        } else if (property.items.$ref) {
                            buffer.push(getClassName(property.items));
                            subModels.push(generateModel(swagger, property.items, null, currentGenerated));
                        } else {
                            buffer.push(getType(property.items));
                        }
                        buffer.push(']');
                    } else {
                        buffer.push(getType(property));
                    }

                    buffer.push('');

                    // is required ?
                    if (!isRequired(schema, propertyName)) {
                        buffer.push(', ', 'optional');
                    }

                    buffer.push(')');

                    // has description
                    if (property.description) {
                        buffer.push(': ', property.description);
                    }

                    // is enum
                    if (property.enum) {
                        buffer.push(' = ', angular.toJson(property.enum).replace(/,/g, ' or '));
                    }

                    buffer.push(',
');
                });

                if (hasProperties) {
                    buffer.pop();
                    buffer.push('
');
                }

                buffer.push('
}
');
                buffer.push(subModels.join(''), '
');
                model = buffer.join('');
            } else if (schema.$ref) {
                className = getClassName(schema);
                def = resolveReference(swagger, schema);

                if (currentGenerated[className]) {
                    return ''; // already generated
                }

                if (def) {
                    if (!modelCache[schema.$ref]) {
                        // cache generated object
                        modelCache[schema.$ref] = generateModel(swagger, def, className, currentGenerated);
                    }
                    currentGenerated[className] = true;
                    model = modelCache[schema.$ref];
                }
            } else if (schema.type === 'array') {
                buffer = ['Array ['];
                sub = '';

                if (schema.items.properties) {
                    name = 'Inline Model' + countInLine++;
                    buffer.push(name);
                    sub = generateModel(swagger, schema.items, name, currentGenerated);
                } else if (schema.items.$ref) {
                    buffer.push(getClassName(schema.items));
                    sub = generateModel(swagger, schema.items, null, currentGenerated);
                } else {
                    buffer.push(getType(schema.items));
                }

                buffer.push(']

', sub);
                model = buffer.join('');
            } else if (schema.type === 'object') {
                model = 'Inline Model {
}';
            }

            return model;
        }
    });
<commit_msg>(ref) unused<commit_after>/*
 * Orange angular-swagger-ui - v0.3.0
 *
 * (C) 2015 Orange, all right reserved
 * MIT Licensed
 */
'use strict';

angular
    .module('swaggerUi')
    .factory('swaggerModel', function ($log) {
        /**
         * sample object cache to avoid generating the same one multiple times
         */
        var objCache = {};

        /**
         * model cache to avoid generating the same one multiple times
         */
        var modelCache = {};

        /**
         * inline model counter
         */
        var countInLine = 0;

        return {
            generateModel: generateModel,
            getType: getType,
            resolveReference: resolveReference,
            generateSampleJson: generateSampleJson,
            clearCache: clearCache
        };

        /**
         * clears generated models cache
         */
        function clearCache () {
            objCache = {};
            modelCache = {};
        }

        /**
         * retrieves object definition
         */
        function resolveReference (swagger, object) {
            if (object.$ref) {
                var parts = object.$ref.replace('#/', '').split('/');
                object = swagger;
                for (var i = 0, j = parts.length; i < j; i++) {
                    object = object[parts[i]];
                }
            }
            return object;
        }

        /**
         * determines a property type
         */
        function getType (item) {
            var format = item.format;
            switch (format) {
                case 'int32':
                    format = item.type;
                    break;
                case 'int64':
                    format = 'long';
                    break;
            }
            return format || item.type;
        }

        /**
         * retrieves object class name based on $ref
         */
        function getClassName (item) {
            var parts = item.$ref.split('/');
            return parts[parts.length - 1];
        }

        /**
         * generates a sample object (request body or response body)
         */
        function getSampleObj (swagger, schema, currentGenerated) {
            var sample;
            currentGenerated = currentGenerated || {}; // used to handle circular references
            if (schema.default || schema.example) {
                sample = schema.default || schema.example;
            } else if (schema.properties) {
                sample = {};

                angular.forEach(schema.properties, function (v, name) {
                    sample[name] = getSampleObj(swagger, v, currentGenerated);
                });
            } else if (schema.$ref) {
                // complex object
                var def = resolveReference(swagger, schema);

                if (def) {
                    if (!objCache[schema.$ref] && !currentGenerated[schema.$ref]) {
                        // object not in cache
                        currentGenerated[schema.$ref] = true;
                        objCache[schema.$ref] = getSampleObj(swagger, def, currentGenerated);
                    }

                    sample = objCache[schema.$ref] || {};
                } else {
                    $log.warn('schema not found', schema.$ref);
                }
            } else if (schema.type === 'array') {
                sample = [getSampleObj(swagger, schema.items, currentGenerated)];
            } else if (schema.type === 'object') {
                sample = {};
            } else {
                sample = schema.defaultValue || schema.example || getSampleValue(getType(schema));
            }
            return sample;
        }

        /**
         * generates a sample value for a basic type
         */
        function getSampleValue (type) {
            var result;
            switch (type) {
                case 'long':
                case 'integer':
                    result = 0;
                    break;
                case 'boolean':
                    result = false;
                    break;
                case 'double':
                case 'number':
                    result = 0.0;
                    break;
                case 'string':
                    result = 'string';
                    break;
                case 'date':
                    result = (new Date()).toISOString().split('T')[0];
                    break;
                case 'date-time':
                    result = (new Date()).toISOString();
                    break;
            }
            return result;
        }

        /**
         * generates a sample JSON string (request body or response body)
         */
        function generateSampleJson (swagger, schema) {
            var json;
            var obj = getSampleObj(swagger, schema);

            if (obj) {
                json = angular.toJson(obj, true);
            }
            return json;
        }

        /**
         * generates object's model
         */
        function generateModel (swagger, schema, modelName, currentGenerated) {
            var model = '';
            var buffer;
            var subModels;
            var hasProperties = false;
            var name;
            var className;
            var def;
            var sub;

            currentGenerated = currentGenerated || {}; // used to handle circular references

            function isRequired (item, name) {
                return item.required && item.required.indexOf(name) !== -1;
            }

            if (schema.properties) {
                modelName = modelName || ('Inline Model' + countInLine++);
                currentGenerated[modelName] = true;
                buffer = ['
' + modelName + ' {'];
                subModels = [];

                angular.forEach(schema.properties, function (property, propertyName) {
                    hasProperties = true;
                    buffer.push('
', propertyName, ' (');

                    // build type
                    if (property.properties) {
                        name = 'Inline Model' + countInLine++;
                        buffer.push(name);
                        subModels.push(generateModel(swagger, property, name, currentGenerated));
                    } else if (property.$ref) {
                        buffer.push(getClassName(property));
                        subModels.push(generateModel(swagger, property, null, currentGenerated));
                    } else if (property.type === 'array') {
                        buffer.push('Array[');
                        if (property.items.properties) {
                            name = 'Inline Model' + countInLine++;
                            buffer.push(name);
                            subModels.push(generateModel(swagger, property, name, currentGenerated));
                        } else if (property.items.$ref) {
                            buffer.push(getClassName(property.items));
                            subModels.push(generateModel(swagger, property.items, null, currentGenerated));
                        } else {
                            buffer.push(getType(property.items));
                        }
                        buffer.push(']');
                    } else {
                        buffer.push(getType(property));
                    }

                    buffer.push('');

                    // is required ?
                    if (!isRequired(schema, propertyName)) {
                        buffer.push(', ', 'optional');
                    }

                    buffer.push(')');

                    // has description
                    if (property.description) {
                        buffer.push(': ', property.description);
                    }

                    // is enum
                    if (property.enum) {
                        buffer.push(' = ', angular.toJson(property.enum).replace(/,/g, ' or '));
                    }

                    buffer.push(',
');
                });

                if (hasProperties) {
                    buffer.pop();
                    buffer.push('
');
                }

                buffer.push('
}
');
                buffer.push(subModels.join(''), '
');
                model = buffer.join('');
            } else if (schema.$ref) {
                className = getClassName(schema);
                def = resolveReference(swagger, schema);

                if (currentGenerated[className]) {
                    return ''; // already generated
                }

                if (def) {
                    if (!modelCache[schema.$ref]) {
                        // cache generated object
                        modelCache[schema.$ref] = generateModel(swagger, def, className, currentGenerated);
                    }
                    currentGenerated[className] = true;
                    model = modelCache[schema.$ref];
                }
            } else if (schema.type === 'array') {
                buffer = ['Array ['];
                sub = '';

                if (schema.items.properties) {
                    name = 'Inline Model' + countInLine++;
                    buffer.push(name);
                    sub = generateModel(swagger, schema.items, name, currentGenerated);
                } else if (schema.items.$ref) {
                    buffer.push(getClassName(schema.items));
                    sub = generateModel(swagger, schema.items, null, currentGenerated);
                } else {
                    buffer.push(getType(schema.items));
                }

                buffer.push(']

', sub);
                model = buffer.join('');
            } else if (schema.type === 'object') {
                model = 'Inline Model {
}';
            }

            return model;
        }
    });
<|endoftext|>