<commit_before>/*global joynrTestRequire: true */
/*jslint es5: true */

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2015 BMW Car IT GmbH
 * %%
 * 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
 *
 *      http://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.
 * #L%
 */

//TODO: some of this relies on the dummy implementation, change accordingly when implementating
joynrTestRequire(
        "joynr/capabilities/TestCapabilitiesRegistrar",
        [
            "global/Promise",
            "joynr/capabilities/CapabilitiesRegistrar",
            "joynr/types/ProviderQos",
            "joynr/types/GlobalDiscoveryEntry",
            "joynr/provider/ProviderAttributeNotifyReadWrite",
            "joynr/types/DiscoveryEntry",
            "joynr/types/ProviderScope",
            "joynr/types/Version",
            "uuid",
        ],
        function(
                Promise,
                CapabilitiesRegistrar,
                ProviderQos,
                GlobalDiscoveryEntry,
                ProviderAttributeNotifyReadWrite,
                DiscoveryEntry,
                ProviderScope,
                Version,
                uuid) {
            describe(
                    "libjoynr-js.joynr.capabilities.CapabilitiesRegistrar",
                    function() {
                        var capabilitiesRegistrar;
                        var requestReplyManagerSpy;
                        var publicationManagerSpy;
                        var participantId;
                        var domain;
                        var authToken;
                        var participantIdStorageSpy;
                        var discoveryStubSpy;
                        var messageRouterSpy;
                        var loggingManagerSpy;
                        var libjoynrMessagingAddress;
                        var provider;
                        var capability;
                        var localChannelId;
                        var providerQos;
                        var address;
                        var checkImplementation;

                        beforeEach(function() {

                            // default checkImplemenation, can be overwritten by individual tests as
                            // needed
                            checkImplementation = function checkImplementationDefault() {
                                return [];
                            };

                            publicationManagerSpy = jasmine.createSpyObj("PublicationManager", [
                                "addPublicationProvider",
                                "registerOnChangedProvider"
                            ]);

                            provider = {
                                id : uuid(),
                                interfaceName : "myInterfaceName",
                                checkImplementation : checkImplementation
                            };

                            spyOn(provider, "checkImplementation").andCallThrough();

                            providerQos =
                                    new ProviderQos([], 1, Date.now(), ProviderScope.GLOBAL, true);

                            provider.myAttribute = new ProviderAttributeNotifyReadWrite(provider, {
                                dependencies : {
                                    publicationManager : publicationManagerSpy
                                }
                            }, "myAttribute", "Boolean");

                            localChannelId = "localChannelId";
                            domain = "testdomain";
                            address = "address";
                            authToken = "authToken";
                            participantId = "myParticipantId";
                            participantIdStorageSpy =
                                    jasmine.createSpyObj(
                                            "participantIdStorage",
                                            [ "getParticipantId"
                                            ]);
                            participantIdStorageSpy.getParticipantId.andReturn(participantId);
                            requestReplyManagerSpy =
                                    jasmine.createSpyObj(
                                            "RequestReplyManager",
                                            [ "addRequestCaller"
                                            ]);
                            discoveryStubSpy = jasmine.createSpyObj("discoveryStub", [ "add"
                            ]);
                            discoveryStubSpy.add.andReturn(Promise.resolve());
                            messageRouterSpy = jasmine.createSpyObj("messageRouter", [ "addNextHop"
                            ]);

                            messageRouterSpy.addNextHop.andReturn(Promise.resolve());
                            libjoynrMessagingAddress = {
                                "someKey" : "someValue",
                                "toBe" : "a",
                                "object" : {}
                            };
                            loggingManagerSpy =
                                    jasmine.createSpyObj("loggingManager", [ "setLoggingContext"
                                    ]);

                            capabilitiesRegistrar = new CapabilitiesRegistrar({
                                discoveryStub : discoveryStubSpy,
                                messageRouter : messageRouterSpy,
                                participantIdStorage : participantIdStorageSpy,
                                libjoynrMessagingAddress : libjoynrMessagingAddress,
                                requestReplyManager : requestReplyManagerSpy,
                                publicationManager : publicationManagerSpy,
                                loggingManager : loggingManagerSpy
                            });

                            capability = new GlobalDiscoveryEntry({
                                providerVersion : new Version({ majorVersion: 47, minorVersion: 11}),
                                domain : domain,
                                interfaceName : provider.interfaceName,
                                qos : providerQos,
                                channelId : localChannelId,
                                participantId : participantId,
                                publicKeyId: "",
                                address : address
                            });
                        });

                        it("is instantiable", function() {
                            expect(capabilitiesRegistrar).toBeDefined();
                            expect(capabilitiesRegistrar instanceof CapabilitiesRegistrar)
                                    .toBeTruthy();
                        });

                        it("is has all members", function() {
                            expect(capabilitiesRegistrar.registerProvider).toBeDefined();
                            expect(typeof capabilitiesRegistrar.registerProvider === "function")
                                    .toBeTruthy();
                        });

                        it("is checks the provider's implementation", function() {
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos);
                            expect(provider.checkImplementation).toHaveBeenCalled();
                        });

                        it(
                                "is checks the provider's implementation, and throws if incomplete",
                                function() {
                                    provider.checkImplementation = function() {
                                        return [ "Operation:addFavoriteStation"
                                        ];
                                    };

                                    expect(
                                            function() {
                                                capabilitiesRegistrar.registerProvider(
                                                        domain,
                                                        provider,
                                                        providerQos);
                                            }).toThrow(
                                            new Error("provider: "
                                                + domain
                                                + "/"
                                                + provider.interfaceName
                                                + " is missing: Operation:addFavoriteStation"));

                                });

                        it("fetches participantId from the participantIdStorage", function() {
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos);
                            expect(participantIdStorageSpy.getParticipantId).toHaveBeenCalled();
                            expect(participantIdStorageSpy.getParticipantId).toHaveBeenCalledWith(
                                    domain,
                                    provider);
                        });

                        it("registers next hop with routing table", function() {
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos);
                            expect(messageRouterSpy.addNextHop).toHaveBeenCalled();
                            expect(messageRouterSpy.addNextHop).toHaveBeenCalledWith(
                                    participantId,
                                    libjoynrMessagingAddress);
                        });

                        it("registers provider at RequestReplyManager", function() {
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos);
                            expect(requestReplyManagerSpy.addRequestCaller).toHaveBeenCalled();
                            expect(requestReplyManagerSpy.addRequestCaller).toHaveBeenCalledWith(
                                    participantId,
                                    provider);
                        });

                        it(
                                "registers a provider with PublicationManager if it has an attribute",
                                function() {
                                    capabilitiesRegistrar.registerProvider(
                                            domain,
                                            provider,
                                            providerQos);
                                    expect(publicationManagerSpy.addPublicationProvider)
                                            .toHaveBeenCalled();
                                    expect(publicationManagerSpy.addPublicationProvider)
                                            .toHaveBeenCalledWith(participantId, provider);
                                });

                        it("registers capability at capabilities stub", function() {
                            var actualDiscoveryEntry;
                            var upperBound;
                            var lowerBound = Date.now();
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos);
                            upperBound = Date.now();
                            expect(discoveryStubSpy.add).toHaveBeenCalled();
                            actualDiscoveryEntry = discoveryStubSpy.add.calls[0].args[0];
                            expect(actualDiscoveryEntry.domain).toEqual(domain);
                            expect(actualDiscoveryEntry.interfaceName).toEqual(provider.interfaceName);
                            expect(actualDiscoveryEntry.participantId).toEqual(participantId);
                            expect(actualDiscoveryEntry.qos).toEqual(providerQos);
                            expect(actualDiscoveryEntry.lastSeenDateMs).not.toBeLessThan(lowerBound);
                            expect(actualDiscoveryEntry.lastSeenDateMs).not.toBeGreaterThan(upperBound);
                        });

                        it("registers logging context with the ContextManager", function() {
                            var loggingContext = {
                                myContext : "myContext"
                            };
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos,
                                    loggingContext);
                            expect(loggingManagerSpy.setLoggingContext).toHaveBeenCalled();
                            expect(loggingManagerSpy.setLoggingContext).toHaveBeenCalledWith(
                                    participantId,
                                    loggingContext);
                        });

                        it("returns the promise success from capabilites stub", function() {
                            var spy = jasmine.createSpyObj("spy", [
                                "onFulfilled",
                                "onRejected"
                            ]);

                            runs(function() {
                                capabilitiesRegistrar.registerProvider(
                                        domain,
                                        provider,
                                        providerQos).then(spy.onFulfilled).catch(spy.onRejected);
                            });

                            waitsFor(function() {
                                return spy.onFulfilled.callCount > 0;
                            }, "onFulfilled spy to be invoked", 100);

                            runs(function() {
                                expect(spy.onFulfilled).toHaveBeenCalled();
                                expect(spy.onFulfilled).toHaveBeenCalledWith([
                                    undefined,
                                    undefined
                                ]);
                                expect(spy.onRejected).not.toHaveBeenCalled();
                            });
                        });

                        it(
                                "returns the promise onRejected from capabilites stub",
                                function() {
                                    var spy = jasmine.createSpyObj("spy", [
                                        "onFulfilled",
                                        "onRejected"
                                    ]);
                                    discoveryStubSpy.add.andReturn(Promise.reject(new Error("Some error.")));

                                    runs(function() {
                                        capabilitiesRegistrar.registerProvider(
                                                domain,
                                                provider,
                                                providerQos).then(spy.onFulfilled).catch(spy.onRejected);
                                    });

                                    waitsFor(function() {
                                        return spy.onRejected.callCount > 0;
                                    }, "onRejected spy to be called", 100);

                                    runs(function() {
                                        expect(spy.onFulfilled).not.toHaveBeenCalled();
                                        expect(spy.onRejected).toHaveBeenCalled();
                                        expect(
                                                Object.prototype.toString
                                                        .call(spy.onRejected.mostRecentCall.args[0]) === "[object Error]")
                                                .toBeTruthy();
                                    });
                                });

                        it("passes calls to deprecated registerCapabilitiy to registerProvider without authToken", function() {
                            spyOn(capabilitiesRegistrar, "registerProvider");
                            capabilitiesRegistrar.registerCapability(
                                    authToken,
                                    domain,
                                    provider,
                                    providerQos);
                            expect(capabilitiesRegistrar.registerProvider).toHaveBeenCalledWith(domain, provider, providerQos);
                        });
                    });

        }); // require
<commit_msg>[JS] Added test for DiscoveryEntry<commit_after>/*global joynrTestRequire: true */
/*jslint es5: true */

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2015 BMW Car IT GmbH
 * %%
 * 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
 *
 *      http://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.
 * #L%
 */

//TODO: some of this relies on the dummy implementation, change accordingly when implementating
joynrTestRequire(
        "joynr/capabilities/TestCapabilitiesRegistrar",
        [
            "global/Promise",
            "joynr/capabilities/CapabilitiesRegistrar",
            "joynr/types/ProviderQos",
            "joynr/types/GlobalDiscoveryEntry",
            "joynr/provider/ProviderAttributeNotifyReadWrite",
            "joynr/types/DiscoveryEntry",
            "joynr/types/ProviderScope",
            "joynr/types/Version",
            "uuid",
        ],
        function(
                Promise,
                CapabilitiesRegistrar,
                ProviderQos,
                GlobalDiscoveryEntry,
                ProviderAttributeNotifyReadWrite,
                DiscoveryEntry,
                ProviderScope,
                Version,
                uuid) {
            describe(
                    "libjoynr-js.joynr.capabilities.CapabilitiesRegistrar",
                    function() {
                        var capabilitiesRegistrar;
                        var requestReplyManagerSpy;
                        var publicationManagerSpy;
                        var participantId;
                        var domain;
                        var authToken;
                        var participantIdStorageSpy;
                        var discoveryStubSpy;
                        var messageRouterSpy;
                        var loggingManagerSpy;
                        var libjoynrMessagingAddress;
                        var provider;
                        var capability;
                        var localChannelId;
                        var providerQos;
                        var address;
                        var checkImplementation;
                        var TestProvider;

                        beforeEach(function() {

                            // default checkImplemenation, can be overwritten by individual tests as
                            // needed
                            checkImplementation = function checkImplementationDefault() {
                                return [];
                            };

                            publicationManagerSpy = jasmine.createSpyObj("PublicationManager", [
                                "addPublicationProvider",
                                "registerOnChangedProvider"
                            ]);

                            TestProvider = function() {
                                this.id = uuid();
                                this.interfaceName = "myInterfaceName";
                                this.checkImplementation = checkImplementation;
                            };

                            TestProvider.MAJOR_VERSION = 47;
                            TestProvider.MINOR_VERSION = 11;
                            provider = new TestProvider();

                            spyOn(provider, "checkImplementation").andCallThrough();

                            providerQos =
                                    new ProviderQos([], 1, Date.now(), ProviderScope.GLOBAL, true);

                            provider.myAttribute = new ProviderAttributeNotifyReadWrite(provider, {
                                dependencies : {
                                    publicationManager : publicationManagerSpy
                                }
                            }, "myAttribute", "Boolean");

                            localChannelId = "localChannelId";
                            domain = "testdomain";
                            address = "address";
                            authToken = "authToken";
                            participantId = "myParticipantId";
                            participantIdStorageSpy =
                                    jasmine.createSpyObj(
                                            "participantIdStorage",
                                            [ "getParticipantId"
                                            ]);
                            participantIdStorageSpy.getParticipantId.andReturn(participantId);
                            requestReplyManagerSpy =
                                    jasmine.createSpyObj(
                                            "RequestReplyManager",
                                            [ "addRequestCaller"
                                            ]);
                            discoveryStubSpy = jasmine.createSpyObj("discoveryStub", [ "add"
                            ]);
                            discoveryStubSpy.add.andReturn(Promise.resolve());
                            messageRouterSpy = jasmine.createSpyObj("messageRouter", [ "addNextHop"
                            ]);

                            messageRouterSpy.addNextHop.andReturn(Promise.resolve());
                            libjoynrMessagingAddress = {
                                "someKey" : "someValue",
                                "toBe" : "a",
                                "object" : {}
                            };
                            loggingManagerSpy =
                                    jasmine.createSpyObj("loggingManager", [ "setLoggingContext"
                                    ]);

                            capabilitiesRegistrar = new CapabilitiesRegistrar({
                                discoveryStub : discoveryStubSpy,
                                messageRouter : messageRouterSpy,
                                participantIdStorage : participantIdStorageSpy,
                                libjoynrMessagingAddress : libjoynrMessagingAddress,
                                requestReplyManager : requestReplyManagerSpy,
                                publicationManager : publicationManagerSpy,
                                loggingManager : loggingManagerSpy
                            });

                            capability = new GlobalDiscoveryEntry({
                                providerVersion : new Version({ majorVersion: 47, minorVersion: 11}),
                                domain : domain,
                                interfaceName : provider.interfaceName,
                                qos : providerQos,
                                channelId : localChannelId,
                                participantId : participantId,
                                publicKeyId: "",
                                address : address
                            });
                        });

                        it("is instantiable", function() {
                            expect(capabilitiesRegistrar).toBeDefined();
                            expect(capabilitiesRegistrar instanceof CapabilitiesRegistrar)
                                    .toBeTruthy();
                        });

                        it("is has all members", function() {
                            expect(capabilitiesRegistrar.registerProvider).toBeDefined();
                            expect(typeof capabilitiesRegistrar.registerProvider === "function")
                                    .toBeTruthy();
                        });

                        it("is checks the provider's implementation", function() {
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos);
                            expect(provider.checkImplementation).toHaveBeenCalled();
                        });

                        it(
                                "is checks the provider's implementation, and throws if incomplete",
                                function() {
                                    provider.checkImplementation = function() {
                                        return [ "Operation:addFavoriteStation"
                                        ];
                                    };

                                    expect(
                                            function() {
                                                capabilitiesRegistrar.registerProvider(
                                                        domain,
                                                        provider,
                                                        providerQos);
                                            }).toThrow(
                                            new Error("provider: "
                                                + domain
                                                + "/"
                                                + provider.interfaceName
                                                + " is missing: Operation:addFavoriteStation"));

                                });

                        it("fetches participantId from the participantIdStorage", function() {
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos);
                            expect(participantIdStorageSpy.getParticipantId).toHaveBeenCalled();
                            expect(participantIdStorageSpy.getParticipantId).toHaveBeenCalledWith(
                                    domain,
                                    provider);
                        });

                        it("registers next hop with routing table", function() {
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos);
                            expect(messageRouterSpy.addNextHop).toHaveBeenCalled();
                            expect(messageRouterSpy.addNextHop).toHaveBeenCalledWith(
                                    participantId,
                                    libjoynrMessagingAddress);
                        });

                        it("registers provider at RequestReplyManager", function() {
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos);
                            expect(requestReplyManagerSpy.addRequestCaller).toHaveBeenCalled();
                            expect(requestReplyManagerSpy.addRequestCaller).toHaveBeenCalledWith(
                                    participantId,
                                    provider);
                        });

                        it(
                                "registers a provider with PublicationManager if it has an attribute",
                                function() {
                                    capabilitiesRegistrar.registerProvider(
                                            domain,
                                            provider,
                                            providerQos);
                                    expect(publicationManagerSpy.addPublicationProvider)
                                            .toHaveBeenCalled();
                                    expect(publicationManagerSpy.addPublicationProvider)
                                            .toHaveBeenCalledWith(participantId, provider);
                                });

                        it("registers capability at capabilities stub", function() {
                            var actualDiscoveryEntry;
                            var upperBound;
                            var lowerBound = Date.now();
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos);
                            upperBound = Date.now();
                            expect(discoveryStubSpy.add).toHaveBeenCalled();
                            actualDiscoveryEntry = discoveryStubSpy.add.calls[0].args[0];
                            expect(actualDiscoveryEntry.domain).toEqual(domain);
                            expect(actualDiscoveryEntry.interfaceName).toEqual(provider.interfaceName);
                            expect(actualDiscoveryEntry.participantId).toEqual(participantId);
                            expect(actualDiscoveryEntry.qos).toEqual(providerQos);
                            expect(actualDiscoveryEntry.lastSeenDateMs).not.toBeLessThan(lowerBound);
                            expect(actualDiscoveryEntry.lastSeenDateMs).not.toBeGreaterThan(upperBound);
                            expect(actualDiscoveryEntry.providerVersion.majorVersion).toEqual(provider.constructor.MAJOR_VERSION);
                            expect(actualDiscoveryEntry.providerVersion.minorVersion).toEqual(provider.constructor.MINOR_VERSION);
                        });

                        it("registers logging context with the ContextManager", function() {
                            var loggingContext = {
                                myContext : "myContext"
                            };
                            capabilitiesRegistrar.registerProvider(
                                    domain,
                                    provider,
                                    providerQos,
                                    loggingContext);
                            expect(loggingManagerSpy.setLoggingContext).toHaveBeenCalled();
                            expect(loggingManagerSpy.setLoggingContext).toHaveBeenCalledWith(
                                    participantId,
                                    loggingContext);
                        });

                        it("returns the promise success from capabilites stub", function() {
                            var spy = jasmine.createSpyObj("spy", [
                                "onFulfilled",
                                "onRejected"
                            ]);

                            runs(function() {
                                capabilitiesRegistrar.registerProvider(
                                        domain,
                                        provider,
                                        providerQos).then(spy.onFulfilled).catch(spy.onRejected);
                            });

                            waitsFor(function() {
                                return spy.onFulfilled.callCount > 0;
                            }, "onFulfilled spy to be invoked", 100);

                            runs(function() {
                                expect(spy.onFulfilled).toHaveBeenCalled();
                                expect(spy.onFulfilled).toHaveBeenCalledWith([
                                    undefined,
                                    undefined
                                ]);
                                expect(spy.onRejected).not.toHaveBeenCalled();
                            });
                        });

                        it(
                                "returns the promise onRejected from capabilites stub",
                                function() {
                                    var spy = jasmine.createSpyObj("spy", [
                                        "onFulfilled",
                                        "onRejected"
                                    ]);
                                    discoveryStubSpy.add.andReturn(Promise.reject(new Error("Some error.")));

                                    runs(function() {
                                        capabilitiesRegistrar.registerProvider(
                                                domain,
                                                provider,
                                                providerQos).then(spy.onFulfilled).catch(spy.onRejected);
                                    });

                                    waitsFor(function() {
                                        return spy.onRejected.callCount > 0;
                                    }, "onRejected spy to be called", 100);

                                    runs(function() {
                                        expect(spy.onFulfilled).not.toHaveBeenCalled();
                                        expect(spy.onRejected).toHaveBeenCalled();
                                        expect(
                                                Object.prototype.toString
                                                        .call(spy.onRejected.mostRecentCall.args[0]) === "[object Error]")
                                                .toBeTruthy();
                                    });
                                });

                        it("passes calls to deprecated registerCapabilitiy to registerProvider without authToken", function() {
                            spyOn(capabilitiesRegistrar, "registerProvider");
                            capabilitiesRegistrar.registerCapability(
                                    authToken,
                                    domain,
                                    provider,
                                    providerQos);
                            expect(capabilitiesRegistrar.registerProvider).toHaveBeenCalledWith(domain, provider, providerQos);
                        });
                    });

        }); // require
<|endoftext|>


<commit_before>define('providers/twitter/tab', ['providers'], function(providers) {
	providers.twitter = {
		className: 'big-icon-twitter',
		init: function() {
			require(['providers','providers/twitter'], function(providers) {
				providers.twitter.init();
			});
		},

		// aop on timeline view
		timeline:
		{
		    preData: function()
		    {
		        // TODO add meta to another member which can be fed...
		        // need to change Meta to object to use in template
		        try{
		            this.model.data.Meta = JSON.parse(this.model.get('Meta'));
		        }
		        catch(e){}
		        var a = this.model.data.Meta.annotation;
		        this.model.data.Meta.annotation = {before: a[0], after: a[1]};
		    },
		    init: function()
		    {
		        var self = this;
		        // TODO move to set for cleanness
		        $(this.el).on('click', '.btn.publish', function()
		        {
		            var data = {Content: '', Meta: self.model.get('Meta')};
		            //data.Content = $('.twitter-full-content .result-text', self.el).html();
	                data.Meta.annotation = [$('.twitter-full-content .annotation:eq(0)', self.el).html(),
	                    $('.twitter-full-content .annotation:eq(1)', self.el).html()];
	                data.Meta = JSON.stringify(data.Meta);
	                self.model.set(data).sync();
	                self.el.find('.actions').addClass('hide');
		        });
		        $(this.el).on('click', '.btn.cancel', function()
                {
		            self.el.find('actions').hide()
                });
		    },
		    edit: function()
		    {
		        this.el.find('.actions').removeClass('hide');
		    },
		    save: function()
		    {
		        return false;
		    }
		}
	};
	return providers;
});<commit_msg>NR-250 : Latest fixes for 1.0 beta release<commit_after>define('providers/twitter/tab', ['providers'], function(providers) {
	providers.twitter = {
		className: 'big-icon-twitter',
		init: function() {
			require(['providers','providers/twitter'], function(providers) {
				providers.twitter.init();
			});
		},

		// aop on timeline view
		timeline:
		{
		    preData: function()
		    {
		        // TODO add meta to another member which can be fed...
		        // need to change Meta to object to use in template
		        try{
		            this.model.data.Meta = JSON.parse(this.model.get('Meta'));
		        }
		        catch(e){}
		        var a = this.model.data.Meta.annotation;
		        this.model.data.Meta.annotation = {before: a[0], after: a[1]};
		    },
		    init: function()
		    {
		        var self = this;
		        // TODO move to set for cleanness
		        $(this.el).on('click', '.btn.publish', function()
		        {
		            var data = {Content: '', Meta: self.model.get('Meta')};
		            //data.Content = $('.twitter-full-content .result-text', self.el).html();
	                data.Meta.annotation = [$('.twitter-full-content .annotation:eq(0)', self.el).html(),
	                    $('.twitter-full-content .annotation:eq(1)', self.el).html()];
	                data.Meta = JSON.stringify(data.Meta);
	                self.model.set(data).sync();
	                self.el.find('.actions').addClass('hide');
		        });
		        $(this.el).on('click', '.btn.cancel', function()
                {
		            self.el.find('.actions').addClass('hide');
                });
		    },
		    edit: function()
		    {
		        this.el.find('.actions').removeClass('hide');
		    },
		    save: function()
		    {
		        return false;
		    }
		}
	};
	return providers;
});<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var abs = require( '@stdlib/math/base/special/abs' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
var EPS = require( '@stdlib/math/constants/float64-eps' );
var factory = require( './../lib/factory.js' );

// FIXTURES //

var smallRange = require( './fixtures/julia/small_range.json' );
var mediumRange = require( './fixtures/julia/medium_range.json' );
var largeRange = require( './fixtures/julia/large_range.json' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof factory, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns a function', function test( t ) {
	var mgf = factory( 0.0, 1.0 );
	t.equal( typeof mgf, 'function', 'returns a function' );
	t.end();
});

tape( 'if provided a non-integer value for `a` or `b`, the created function returns `NaN`', function test( t ) {
	var mgf;
	var y;

	mgf = factory( 0.5, 2 );
	y = mgf( NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( -2, 5.5 );
	y = mgf( NaN );
	t.equal( isnan( y ), true, 'returns NaN' );
});

tape( 'if provided `NaN` for any parameter, the created function returns `NaN`', function test( t ) {
	var mgf;
	var y;

	mgf = factory( 0, 1 );
	y = mgf( NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( NaN, 1 );
	y = mgf( 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( 1, NaN );
	y = mgf( 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( NaN, NaN );
	y = mgf( 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( NaN, NaN );
	y = mgf( NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'if provided `a > b`, the created function always returns `NaN`', function test( t ) {
	var mgf;
	var y;

	mgf = factory( 0, -1 );

	y = mgf( 2.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = mgf( 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( 0.0, NINF );
	y = mgf( 2.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( PINF, NINF );
	y = mgf( 2.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( NaN, NINF );
	y = mgf( 2.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'if provided valid parameters `a` and `b`, the created function returns `1` for `t = 0`', function test( t ) {
	var mgf;
	var y;

	mgf = factory( -4, 4 );
	y = mgf( 0.0 );
	t.equal( y, 1.0, 'returns 1' );

	mgf = factory( 0, 10 );
	y = mgf( 0.0 );
	t.equal( y, 1.0, 'returns 1' );

	t.end();
});

tape( 'the created function evaluates the MGF for `x` given small range `b - a`', function test( t ) {
	var expected;
	var delta;
	var mgf;
	var tol;
	var a;
	var b;
	var i;
	var x;
	var y;

	expected = smallRange.expected;
	x = smallRange.x;
	a = smallRange.a;
	b = smallRange.b;
	for ( i = 0; i < x.length; i++ ) {
		mgf = factory( a[i], b[i] );
		y = mgf( x[i] );
		if ( expected[i] !== null ) {
			if ( y === expected[i] ) {
				t.equal( y, expected[i], 'x: '+x[i]+', a: '+a[i]+', b: '+b[i]+', y: '+y+', expected: '+expected[i] );
			} else {
				delta = abs( y - expected[ i ] );
				tol = 1.0 * EPS * abs( expected[ i ] );
				t.ok( delta <= tol, 'within tolerance. x: '+x[ i ]+'. a: '+a[i]+'. b: '+b[i]+'. y: '+y+'. E: '+expected[ i ]+'. Δ: '+delta+'. tol: '+tol+'.' );
			}
		}
	}
	t.end();
});

tape( 'the created function evaluates the MGF for `x` given a medium range `b - a`', function test( t ) {
	var expected;
	var delta;
	var mgf;
	var tol;
	var a;
	var b;
	var i;
	var x;
	var y;

	expected = mediumRange.expected;
	x = mediumRange.x;
	a = mediumRange.a;
	b = mediumRange.b;
	for ( i = 0; i < x.length; i++ ) {
		mgf = factory( a[i], b[i] );
		y = mgf( x[i] );
		if ( expected[i] !== null ) {
			if ( y === expected[i] ) {
				t.equal( y, expected[i], 'x: '+x[i]+', a: '+a[i]+', b: '+b[i]+', y: '+y+', expected: '+expected[i] );
			} else {
				delta = abs( y - expected[ i ] );
				tol = 1.0 * EPS * abs( expected[ i ] );
				t.ok( delta <= tol, 'within tolerance. x: '+x[ i ]+'. a: '+a[i]+'. b: '+b[i]+'. y: '+y+'. E: '+expected[ i ]+'. Δ: '+delta+'. tol: '+tol+'.' );
			}
		}
	}
	t.end();
});

tape( 'the created function evaluates the MGF for `x` given a large range `b - a`', function test( t ) {
	var expected;
	var delta;
	var mgf;
	var tol;
	var a;
	var b;
	var i;
	var x;
	var y;

	expected = largeRange.expected;
	x = largeRange.x;
	a = largeRange.a;
	b = largeRange.b;
	for ( i = 0; i < x.length; i++ ) {
		mgf = factory( a[i], b[i] );
		y = mgf( x[i] );
		if ( expected[i] !== null ) {
			if ( y === expected[i] ) {
				t.equal( y, expected[i], 'x: '+x[i]+', a: '+a[i]+', b: '+b[i]+', y: '+y+', expected: '+expected[i] );
			} else {
				delta = abs( y - expected[ i ] );
				tol = 1.0 * EPS * abs( expected[ i ] );
				t.ok( delta <= tol, 'within tolerance. x: '+x[ i ]+'. a: '+a[i]+'. b: '+b[i]+'. y: '+y+'. E: '+expected[ i ]+'. Δ: '+delta+'. tol: '+tol+'.' );
			}
		}
	}
	t.end();
});
<commit_msg>Add missing end directive for tests<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var abs = require( '@stdlib/math/base/special/abs' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
var EPS = require( '@stdlib/math/constants/float64-eps' );
var factory = require( './../lib/factory.js' );

// FIXTURES //

var smallRange = require( './fixtures/julia/small_range.json' );
var mediumRange = require( './fixtures/julia/medium_range.json' );
var largeRange = require( './fixtures/julia/large_range.json' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof factory, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns a function', function test( t ) {
	var mgf = factory( 0.0, 1.0 );
	t.equal( typeof mgf, 'function', 'returns a function' );
	t.end();
});

tape( 'if provided a non-integer value for `a` or `b`, the created function returns `NaN`', function test( t ) {
	var mgf;
	var y;

	mgf = factory( 0.5, 2 );
	y = mgf( NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( -2, 5.5 );
	y = mgf( NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'if provided `NaN` for any parameter, the created function returns `NaN`', function test( t ) {
	var mgf;
	var y;

	mgf = factory( 0, 1 );
	y = mgf( NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( NaN, 1 );
	y = mgf( 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( 1, NaN );
	y = mgf( 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( NaN, NaN );
	y = mgf( 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( NaN, NaN );
	y = mgf( NaN );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'if provided `a > b`, the created function always returns `NaN`', function test( t ) {
	var mgf;
	var y;

	mgf = factory( 0, -1 );

	y = mgf( 2.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = mgf( 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( 0.0, NINF );
	y = mgf( 2.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( PINF, NINF );
	y = mgf( 2.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	mgf = factory( NaN, NINF );
	y = mgf( 2.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'if provided valid parameters `a` and `b`, the created function returns `1` for `t = 0`', function test( t ) {
	var mgf;
	var y;

	mgf = factory( -4, 4 );
	y = mgf( 0.0 );
	t.equal( y, 1.0, 'returns 1' );

	mgf = factory( 0, 10 );
	y = mgf( 0.0 );
	t.equal( y, 1.0, 'returns 1' );

	t.end();
});

tape( 'the created function evaluates the MGF for `x` given small range `b - a`', function test( t ) {
	var expected;
	var delta;
	var mgf;
	var tol;
	var a;
	var b;
	var i;
	var x;
	var y;

	expected = smallRange.expected;
	x = smallRange.x;
	a = smallRange.a;
	b = smallRange.b;
	for ( i = 0; i < x.length; i++ ) {
		mgf = factory( a[i], b[i] );
		y = mgf( x[i] );
		if ( expected[i] !== null ) {
			if ( y === expected[i] ) {
				t.equal( y, expected[i], 'x: '+x[i]+', a: '+a[i]+', b: '+b[i]+', y: '+y+', expected: '+expected[i] );
			} else {
				delta = abs( y - expected[ i ] );
				tol = 1.0 * EPS * abs( expected[ i ] );
				t.ok( delta <= tol, 'within tolerance. x: '+x[ i ]+'. a: '+a[i]+'. b: '+b[i]+'. y: '+y+'. E: '+expected[ i ]+'. Δ: '+delta+'. tol: '+tol+'.' );
			}
		}
	}
	t.end();
});

tape( 'the created function evaluates the MGF for `x` given a medium range `b - a`', function test( t ) {
	var expected;
	var delta;
	var mgf;
	var tol;
	var a;
	var b;
	var i;
	var x;
	var y;

	expected = mediumRange.expected;
	x = mediumRange.x;
	a = mediumRange.a;
	b = mediumRange.b;
	for ( i = 0; i < x.length; i++ ) {
		mgf = factory( a[i], b[i] );
		y = mgf( x[i] );
		if ( expected[i] !== null ) {
			if ( y === expected[i] ) {
				t.equal( y, expected[i], 'x: '+x[i]+', a: '+a[i]+', b: '+b[i]+', y: '+y+', expected: '+expected[i] );
			} else {
				delta = abs( y - expected[ i ] );
				tol = 1.0 * EPS * abs( expected[ i ] );
				t.ok( delta <= tol, 'within tolerance. x: '+x[ i ]+'. a: '+a[i]+'. b: '+b[i]+'. y: '+y+'. E: '+expected[ i ]+'. Δ: '+delta+'. tol: '+tol+'.' );
			}
		}
	}
	t.end();
});

tape( 'the created function evaluates the MGF for `x` given a large range `b - a`', function test( t ) {
	var expected;
	var delta;
	var mgf;
	var tol;
	var a;
	var b;
	var i;
	var x;
	var y;

	expected = largeRange.expected;
	x = largeRange.x;
	a = largeRange.a;
	b = largeRange.b;
	for ( i = 0; i < x.length; i++ ) {
		mgf = factory( a[i], b[i] );
		y = mgf( x[i] );
		if ( expected[i] !== null ) {
			if ( y === expected[i] ) {
				t.equal( y, expected[i], 'x: '+x[i]+', a: '+a[i]+', b: '+b[i]+', y: '+y+', expected: '+expected[i] );
			} else {
				delta = abs( y - expected[ i ] );
				tol = 1.0 * EPS * abs( expected[ i ] );
				t.ok( delta <= tol, 'within tolerance. x: '+x[ i ]+'. a: '+a[i]+'. b: '+b[i]+'. y: '+y+'. E: '+expected[ i ]+'. Δ: '+delta+'. tol: '+tol+'.' );
			}
		}
	}
	t.end();
});
<|endoftext|>


<commit_before>;(function($, window, document) {
    'use strict';

    /**
     * Get the value of a cookie with the given name
     * @param name
     * @returns {string|undefined}
     */
    $.getCookie = function(name) {
        var value = "; " + document.cookie,
            parts = value.split("; " + name + "=");

        if (parts.length == 2) {
            return parts.pop().split(";").shift();
        }
        return undefined;
    };

    /**
     * Remove a cookie with the provided name
     * @param name
     */
    $.removeCookie = function(name) {
        var basePath = window.csrfConfig.basePath || "/";
        document.cookie = name + '=; path=' + basePath + '; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    };

    var CSRF = {

        /**
         * Key including subshop and -path
         */
        storageKey: '__csrf_token-' + window.csrfConfig.shopId,

        /**
         * Temporary request callback store
         */
        pendingRequests: {},

        /**
         * Returns the token
         * @returns {string}
         */
        getToken: function() {
            return $.getCookie(this.storageKey);
        },

        /**
         * Checks if the token needs to be requested
         * @returns {boolean}
         */
        checkToken: function() {
            return $.getCookie('invalidate-xcsrf-token') === undefined && this.getToken() !== undefined;
        },

        /**
         * Creates a hidden input fields which holds the csrf information
         * @returns {HTMLElement}
         */
        createTokenField: function() {
            var me = this;

            return $('<input>', {
                'type': 'hidden',
                'name': '__csrf_token',
                'value': me.getToken()
            });
        },

        /**
         * Adds the token field to the given form
         * @param {HTMLElement} formElement
         */
        addTokenField: function(formElement) {
            formElement.append(CSRF.createTokenField());
        },

        /**
         *
         * @returns {HTMLElement[]}
         */
        getFormElements: function() {
            return $('form[method="post"]');
        },

        /**
         * Search all forms on the page and create or update their csrf input fields
         */
        updateForms: function() {
            var me = this,
                formElements = me.getFormElements();

            $.each(formElements, function(index, formElement) {
                var csrfInput;

                formElement = $(formElement);
                csrfInput = formElement.find('input[name="__csrf_token"]');

                if (csrfInput.length > 0) {
                    csrfInput.val(me.getToken());
                } else {
                    me.addTokenField(formElement);
                }
            });
        },

        /**
         * Modify every ajax request to add the X-CSRF-Token header
         */
        setupAjax: function() {
            var me = this,
                afterAjaxRequest = function() {
                    if (me.pendingRequests[this.url]) {
                        var request = me.pendingRequests[this.url];
                        request.callback.apply(request.context, arguments);
                    }

                    // to prevent timing issues, delay the update
                    window.setTimeout(function() {
                        me.updateForms();
                    }, 1);
                };

            $.ajaxSetup({
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-CSRF-Token', me.getToken());

                    if (typeof this.complete === 'function') {
                        me.pendingRequests[this.url] = {
                            context: this,
                            callback: this.complete
                        };
                    }

                    this.complete = afterAjaxRequest;
                }
            });
        },

        /**
         * Calls the frontend to retrieve a new csrf token and executes the afterInit on success
         */
        requestToken: function() {
            var me = this;

            $.ajax({
                url: window.csrfConfig.generateUrl,
                success: function(response, status, xhr) {
                    me.saveToken(xhr.getResponseHeader('x-csrf-token'));
                    $.removeCookie('invalidate-xcsrf-token');
                    me.afterInit();
                }
            });
        },

        /**
         * Save token into a cookie
         * @param token
         */
        saveToken: function(token) {
            var me = this,
                basePath = window.csrfConfig.basePath || "/";

            document.cookie = me.storageKey + "=" + token + "; path=" + basePath;
        },

        /**
         * Initialize the CSRF protection
         */
        init: function() {
            var me = this;

            if (me.checkToken()) {
                me.afterInit();
                return;
            }

            me.requestToken();
        },

        /**
         * Runs after a valid token is set
         */
        afterInit: function() {
            var me = this;

            me.updateForms();
            me.setupAjax();
        }

    };

    $(function() {
        CSRF.init();
    });

    window.CSRF = CSRF;

})(jQuery, window, document);<commit_msg>SW-15838 - Add events for CSRF jQuery plugin<commit_after>;(function($, window, document) {
    'use strict';

    /**
     * Get the value of a cookie with the given name
     * @param name
     * @returns {string|undefined}
     */
    $.getCookie = function(name) {
        var value = "; " + document.cookie,
            parts = value.split("; " + name + "=");

        if (parts.length == 2) {
            return parts.pop().split(";").shift();
        }
        return undefined;
    };

    /**
     * Remove a cookie with the provided name
     * @param name
     */
    $.removeCookie = function(name) {
        var basePath = window.csrfConfig.basePath || "/";
        document.cookie = name + '=; path=' + basePath + '; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    };

    var CSRF = {

        /**
         * Key including subshop and -path
         */
        storageKey: '__csrf_token-' + window.csrfConfig.shopId,

        /**
         * Temporary request callback store
         */
        pendingRequests: {},

        /**
         * Returns the token
         * @returns {string}
         */
        getToken: function() {
            return $.getCookie(this.storageKey);
        },

        /**
         * Checks if the token needs to be requested
         * @returns {boolean}
         */
        checkToken: function() {
            return $.getCookie('invalidate-xcsrf-token') === undefined && this.getToken() !== undefined;
        },

        /**
         * Creates a hidden input fields which holds the csrf information
         * @returns {HTMLElement}
         */
        createTokenField: function() {
            var me = this;

            return $('<input>', {
                'type': 'hidden',
                'name': '__csrf_token',
                'value': me.getToken()
            });
        },

        /**
         * Adds the token field to the given form
         * @param {HTMLElement} formElement
         */
        addTokenField: function(formElement) {
            formElement.append(CSRF.createTokenField());
            $.publish('plugin/swCsrfProtection/addTokenField', [ this, formElement ]);
        },

        /**
         *
         * @returns {HTMLElement[]}
         */
        getFormElements: function() {
            return $('form[method="post"]');
        },

        /**
         * Search all forms on the page and create or update their csrf input fields
         */
        updateForms: function() {
            var me = this,
                formElements = me.getFormElements();

            $.each(formElements, function(index, formElement) {
                var csrfInput;

                formElement = $(formElement);
                csrfInput = formElement.find('input[name="__csrf_token"]');

                if (csrfInput.length > 0) {
                    csrfInput.val(me.getToken());
                } else {
                    me.addTokenField(formElement);
                }
            });

            $.publish('plugin/swCsrfProtection/updateForms', [ this, formElements ]);
        },

        /**
         * Modify every ajax request to add the X-CSRF-Token header
         */
        setupAjax: function() {
            var me = this,
                token = me.getToken();

            $.ajaxSettings.headers = $.ajaxSettings.headers || {};
            $.ajaxSettings.headers['X-CSRF-Token'] = token;

            $.publish('plugin/swCsrfProtection/setupAjax', [ this, token ]);
        },

        /**
         * Calls the frontend to retrieve a new csrf token and executes the afterInit on success
         */
        requestToken: function() {
            var me = this;

            $.ajax({
                url: window.csrfConfig.generateUrl,
                success: function(response, status, xhr) {
                    me.saveToken(xhr.getResponseHeader('x-csrf-token'));
                    $.removeCookie('invalidate-xcsrf-token');
                    $.publish('plugin/swCsrfProtection/requestToken', [ me, me.getToken() ]);
                    me.afterInit();
                }
            });
        },

        /**
         * Save token into a cookie
         * @param token
         */
        saveToken: function(token) {
            var me = this,
                basePath = window.csrfConfig.basePath || "/";

            document.cookie = me.storageKey + "=" + token + "; path=" + basePath;
        },

        /**
         * Initialize the CSRF protection
         */
        init: function() {
            var me = this;

            if (me.checkToken()) {
                me.afterInit();
                return;
            }

            me.requestToken();
        },

        /**
         * Runs after a valid token is set
         */
        afterInit: function() {
            var me = this;

            me.updateForms();
            me.setupAjax();

            $.publish('plugin/swCsrfProtection/init', [ me ]);
        }

    };

    $(function() {
        CSRF.init();
    });

    window.CSRF = CSRF;

})(jQuery, window, document);<|endoftext|>


<commit_before>angular.module('CrudApp', []).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
        when('/', {templateUrl: '/tpl/lists.html', controller: ListCtrl}).
        when('/add-user', {templateUrl: '/tpl/add-new.html', controller: AddCtrl}).
        when('/edit/:id', {templateUrl: '/tpl/edit.html', controller: EditCtrl}).
        otherwise({redirectTo: '/'});
}]);

function ListCtrl($scope, $http) {
    $http.get('/api/users').success(function (data) {
        $scope.users = data;
    });
}

function AddCtrl($scope, $http, $location) {
    $scope.master = {};
    $scope.activePath = null;

    $scope.add_new = function (user, AddNewForm) {

        $http.post('/api/users', user).success(function () {
            $scope.reset();
            $scope.activePath = $location.path('/');
        });

        $scope.reset = function () {
            $scope.user = angular.copy($scope.master);
        };

        $scope.reset();

    };
}

function EditCtrl($scope, $http, $location, $routeParams) {
    var id = $routeParams.id;
    $scope.activePath = null;

    $http.get('/api/users/' + id).success(function (data) {
        $scope.user = data;
    });

    $scope.update = function (user) {
        $http.put('/api/users/' + id, user).success(function (data) {
            $scope.user = data;
            $scope.activePath = $location.path('/');
        });
    };

    $scope.delete = function (user) {
        var deleteUser = confirm('Are you absolutely sure you want to delete '+ user.id +' ?');
        if (deleteUser) {
            $http.delete('/api/users/' + id, user);
            $scope.activePath = $location.path('/');
        }
    };
}<commit_msg>Add method success error<commit_after>angular.module('CrudApp', []).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
        when('/', {templateUrl: '/tpl/lists.html', controller: ListCtrl}).
        when('/add-user', {templateUrl: '/tpl/add-new.html', controller: AddCtrl}).
        when('/edit/:id', {templateUrl: '/tpl/edit.html', controller: EditCtrl}).
        otherwise({redirectTo: '/'});
}]);

function ListCtrl($scope, $http) {
    $http.get('/api/users').success(function (data) {
        $scope.users = data;
    });
}

function AddCtrl($scope, $http, $location) {
    $scope.master = {};
    $scope.activePath = null;

    $scope.add_new = function (user, AddNewForm) {

        $http.post('/api/users', user).success(function () {
            $scope.reset();
            $scope.activePath = $location.path('/');
        });

        $scope.reset = function () {
            $scope.user = angular.copy($scope.master);
        };

        $scope.reset();

    };
}

function EditCtrl($scope, $http, $location, $routeParams) {
    var id = $routeParams.id;
    $scope.activePath = null;

    $http.get('/api/users/' + id).success(function (data) {
        $scope.user = data;
    });

    $scope.update = function (user) {
        $http.put('/api/users/' + id, user).success(function (data) {
            $scope.user = data;
            $scope.activePath = $location.path('/');
        });
    };

    $scope.delete = function (user) {
        var deleteUser = confirm('Are you absolutely sure you want to delete ?');
        if (deleteUser) {
            $http.delete('/api/users/' + id, user)
                .success(function(data, status, headers, config) {
                    console.log("success");
                    $scope.activePath = $location.path('/');
                }).
                error(function(data, status, headers, config) {
                    console.log("error");
                    // handle error
                });

        }
    };
}<|endoftext|>


<commit_before>/**
 * Created by quasarchimaere on 29.11.2018.
 */
import { actionTypes } from "../actions/actions.js";
import Immutable from "immutable";
import { getIn } from "../utils.js";

const initialState = Immutable.fromJS({
  processingInitialLoad: true,
  processingPublish: false,
  processingLogout: false,
  processingLogin: false,
  processingLoginForEmail: undefined,
  processingAcceptTermsOfService: false,
});

export default function(processState = initialState, action = {}) {
  switch (action.type) {
    case actionTypes.personas.create:
    case actionTypes.needs.create:
    case actionTypes.needs.whatsNew:
    case actionTypes.needs.whatsAround:
      return processState.set("processingPublish", true);

    case actionTypes.failedToGetLocation:
    case actionTypes.personas.createSuccessful:
    case actionTypes.needs.createSuccessful:
      return processState.set("processingPublish", false);

    case actionTypes.account.logoutStarted:
      return processState.set("processingLogout", true);

    case actionTypes.account.logout:
      return processState.set("processingLogout", false);

    case actionTypes.account.loginStarted:
      return processState
        .set("processingLogin", true)
        .set("processingLoginForEmail", getIn(action, ["payload", "email"]));

    case actionTypes.account.acceptTermsOfServiceStarted:
      return processState.set("processingAcceptTermsOfService", true);

    case actionTypes.account.acceptTermsOfServiceSuccess:
    case actionTypes.account.acceptTermsOfServiceFailed:
      return processState.set("processingAcceptTermsOfService", false);

    case actionTypes.account.login: {
      if (getIn(action, ["payload", "loginFinished"])) {
        return processState
          .set("processingLogin", false)
          .set("processingLoginForEmail", undefined);
      }
      return processState;
    }

    case actionTypes.account.loginFailed:
      return processState
        .set("processingLogin", false)
        .set("processingLoginForEmail", undefined);

    case actionTypes.initialPageLoad: {
      if (!processState.get("processingInitialLoad")) {
        return processState;
      } else {
        const initialLoadFinished = getIn(action, [
          "payload",
          "initialLoadFinished",
        ]);
        return processState.set("processingInitialLoad", !initialLoadFinished);
      }
    }

    default:
      return processState;
  }
}
<commit_msg>Adds process state processingVerifyEmailAddress<commit_after>/**
 * Created by quasarchimaere on 29.11.2018.
 */
import { actionTypes } from "../actions/actions.js";
import Immutable from "immutable";
import { getIn } from "../utils.js";

const initialState = Immutable.fromJS({
  processingInitialLoad: true,
  processingPublish: false,
  processingLogout: false,
  processingLogin: false,
  processingLoginForEmail: undefined,
  processingAcceptTermsOfService: false,
  processingVerifyEmailAddress: false,
});

export default function(processState = initialState, action = {}) {
  switch (action.type) {
    case actionTypes.personas.create:
    case actionTypes.needs.create:
    case actionTypes.needs.whatsNew:
    case actionTypes.needs.whatsAround:
      return processState.set("processingPublish", true);

    case actionTypes.failedToGetLocation:
    case actionTypes.personas.createSuccessful:
    case actionTypes.needs.createSuccessful:
      return processState.set("processingPublish", false);

    case actionTypes.account.logoutStarted:
      return processState.set("processingLogout", true);

    case actionTypes.account.logout:
      return processState.set("processingLogout", false);

    case actionTypes.account.loginStarted:
      return processState
        .set("processingLogin", true)
        .set("processingLoginForEmail", getIn(action, ["payload", "email"]));

    case actionTypes.account.acceptTermsOfServiceStarted:
      return processState.set("processingAcceptTermsOfService", true);

    case actionTypes.account.verifyEmailAddressStarted:
      return processState.set("processingVerifyEmailAddress", true);

    case actionTypes.account.verifyEmailAddressSuccess:
    case actionTypes.account.verifyEmailAddressFailed:
      return processState.set("processingVerifyEmailAddress", false);

    case actionTypes.account.acceptTermsOfServiceSuccess:
    case actionTypes.account.acceptTermsOfServiceFailed:
      return processState.set("processingAcceptTermsOfService", false);

    case actionTypes.account.login: {
      if (getIn(action, ["payload", "loginFinished"])) {
        return processState
          .set("processingLogin", false)
          .set("processingLoginForEmail", undefined);
      }
      return processState;
    }

    case actionTypes.account.loginFailed:
      return processState
        .set("processingLogin", false)
        .set("processingLoginForEmail", undefined);

    case actionTypes.initialPageLoad: {
      if (!processState.get("processingInitialLoad")) {
        return processState;
      } else {
        const initialLoadFinished = getIn(action, [
          "payload",
          "initialLoadFinished",
        ]);
        return processState.set("processingInitialLoad", !initialLoadFinished);
      }
    }

    default:
      return processState;
  }
}
<|endoftext|>


<commit_before><commit_msg>Update server.js<commit_after><|endoftext|>


<commit_before>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Creates Dropdown Menu
//------------------------------------------------------------------------------
d3plus.forms.drop = function(vars,styles,timing) {

  d3.select("html").on(d3plus.evt.click+"."+vars.id,function(){
    var element = d3.event.toElement.id,
        id = "d3plus_button_"+vars.id,
        child = id+"_"

    if (element != id && element.indexOf(child) < 0) {
      vars.ui.disable()
    }

  })

  if (styles.icon.indexOf("fa-") == 0) {
    var icon = {
      "class": "d3plus_drop_icon fa "+styles.icon,
      "content": ""
    }
  }
  else {
    var icon = {
      "class": "d3plus_drop_icon",
      "content": styles.icon
    }
  }

  function check_value(obj,arr) {

    if (typeof obj == "object" && arr) {
      var ret = false
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] in obj) {
          ret = obj[arr[i]]
          break;
        }
      }
      if (ret) {
        return ret
      }
    }
    else if (typeof obj != "object") {
      return obj
    }
    else {
      return false
    }

  }

  var drop_width = check_value(styles.width,["drop","button"])
  if (!drop_width || typeof drop_width != "number") {

    drop_width = 0

    vars.data.forEach(function(o,i){
      var data = d3plus.utils.merge(styles,o)
      data.icon = icon
      data.display = "inline-block"
      data.border = "none"
      data.width = false
      var text = check_value(vars.text,["drop","button"])
      if (!text) {
       text = "text"
      }
      var button = d3plus.ui(data)
        .type("button")
        .text(text)
        .parent(vars.tester)
        .id("tester"+i)
        .timing(0)
        .draw()
      var w = button.width()
      if (w > drop_width) drop_width = w
      button.remove()
    })

    drop_width += d3plus.scrollbar()

  }

  var button_width = check_value(styles.width,["button","drop"])
  if (!button_width || typeof button_width != "number") {
    button_width = drop_width
  }

  var data = d3plus.utils.merge(styles,vars.focus)
  data.icon = icon
  data.width = button_width
  var text = check_value(vars.text,["button","drop"])
  if (!text) {
   text = "text"
  }
  var button = d3plus.ui(data)
    .type("button")
    .text(text)
    .parent(vars.container)
    .id(vars.id)
    .timing(timing)
    .callback(vars.ui.toggle)
    .enable()
    .draw()

  var opposite = styles.icon.content == "^"
  if (vars.enabled != opposite) {
    var rotate = "rotate(-180deg)"
  }
  else {
    var rotate = "rotate(0deg)"
  }
  button.select("div#d3plus_button_"+vars.id+"_icon")
    .data(["icon"])
    .style("transition",(timing/1000)+"s")
    .style("-webkit-transition",(timing/1000)+"s")
    .style("transform",rotate)
    .style("-ms-transform",rotate)
    .style("-webkit-transform",rotate)
    .style("opacity",function(){
      return vars.enabled ? 0.5 : 1
    })

  var selector = vars.container.selectAll("div.d3plus_drop_selector")
    .data(["selector"])

  selector.enter().append("div")
    .attr("class","d3plus_drop_selector")
    .style("position","absolute")
    .style("overflow","scroll")
    .style("top","0px")
    .style("z-index","-1")
    .style("border-style","solid")

  vars.data.forEach(function(o,i){

    var data = d3plus.utils.merge(styles,o)
    data.icon = false
    data.display = "block"
    data.border = "none"
    data.width = drop_width - (styles.stroke*2)
    var text = check_value(vars.text,["drop","button"])
    if (!text) {
     text = "text"
    }
    var option = d3plus.ui(data)
      .type("button")
      .text(text)
      .parent(selector)
      .id(vars.id+"_option"+i)
      .timing(timing)
      .callback(vars.ui.value)

    if (o.value == vars.focus.value) {
      option.highlight(true)
    }

    option.draw()

  })

  var position = vars.container.node().getBoundingClientRect()

  selector.transition().duration(timing)
    .each("start",function(){
      if (vars.enabled) {
        d3.select(this).style("display","block")
      }
    })
    .style("left",function(){
      if (styles.align == "left") {
        return "0px"
      }
      else if (styles.align == "center") {
        return -((drop_width-button_width)/2)+"px"
      }
      else {
        return "auto"
      }
    })
    .style("right",function(){
      return styles.align == "right" ? "0px" : "auto"
    })
    .style("border-width",styles.stroke+"px")
    .style("border-color",styles.color)
    .style("width",(drop_width+(styles.padding*2))+"px")
    .style("max-height",function(){
      var max = window.innerHeight-position.top
      max -= vars.enabled ? button.height() : 0
      max -= styles.padding
      return max < vars["max-height"] ? max+"px" : vars["max-height"]+"px"
    })
    .style("top",function(){
      return vars.enabled ? button.height()+"px" : "0px"
    })
    .style("opacity",function(){
      return vars.enabled ? 1 : 0
    })
    .each("end",function(){
      if (!vars.enabled) {
        d3.select(this).style("display","none")
      }
      else {
        d3.select(this).transition().duration(timing)
          .style("top",function(){
            return vars.enabled ? button.height()+"px" : "0px"
          })
      }
    })

}
<commit_msg>fixed drop margins<commit_after>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Creates Dropdown Menu
//------------------------------------------------------------------------------
d3plus.forms.drop = function(vars,styles,timing) {

  d3.select("html").on(d3plus.evt.click+"."+vars.id,function(){
    var element = d3.event.toElement.id,
        id = "d3plus_button_"+vars.id,
        child = id+"_"

    if (element != id && element.indexOf(child) < 0) {
      vars.ui.disable()
    }

  })

  if (styles.icon.indexOf("fa-") == 0) {
    var icon = {
      "class": "d3plus_drop_icon fa "+styles.icon,
      "content": ""
    }
  }
  else {
    var icon = {
      "class": "d3plus_drop_icon",
      "content": styles.icon
    }
  }

  function check_value(obj,arr) {

    if (typeof obj == "object" && arr) {
      var ret = false
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] in obj) {
          ret = obj[arr[i]]
          break;
        }
      }
      if (ret) {
        return ret
      }
    }
    else if (typeof obj != "object") {
      return obj
    }
    else {
      return false
    }

  }

  var drop_width = check_value(styles.width,["drop","button"])
  if (!drop_width || typeof drop_width != "number") {

    drop_width = 0

    vars.data.forEach(function(o,i){
      var data = d3plus.utils.merge(styles,o)
      data.icon = icon
      data.display = "inline-block"
      data.border = "none"
      data.width = false
      data.margin = 0
      var text = check_value(vars.text,["drop","button"])
      if (!text) {
       text = "text"
      }
      var button = d3plus.ui(data)
        .type("button")
        .text(text)
        .parent(vars.tester)
        .id("tester"+i)
        .timing(0)
        .draw()
      var w = button.width()
      if (w > drop_width) drop_width = w
      button.remove()
    })

    drop_width += d3plus.scrollbar()

  }

  var button_width = check_value(styles.width,["button","drop"])
  if (!button_width || typeof button_width != "number") {
    button_width = drop_width
  }

  var data = d3plus.utils.merge(styles,vars.focus)
  data.icon = icon
  data.width = button_width
  data.margin = 0
  var text = check_value(vars.text,["button","drop"])
  if (!text) {
   text = "text"
  }
  var button = d3plus.ui(data)
    .type("button")
    .text(text)
    .parent(vars.container)
    .id(vars.id)
    .timing(timing)
    .callback(vars.ui.toggle)
    .enable()
    .draw()

  var opposite = styles.icon.content == "^"
  if (vars.enabled != opposite) {
    var rotate = "rotate(-180deg)"
  }
  else {
    var rotate = "rotate(0deg)"
  }
  button.select("div#d3plus_button_"+vars.id+"_icon")
    .data(["icon"])
    .style("transition",(timing/1000)+"s")
    .style("-webkit-transition",(timing/1000)+"s")
    .style("transform",rotate)
    .style("-ms-transform",rotate)
    .style("-webkit-transform",rotate)
    .style("opacity",function(){
      return vars.enabled ? 0.5 : 1
    })

  var selector = vars.container.selectAll("div.d3plus_drop_selector")
    .data(["selector"])

  selector.enter().append("div")
    .attr("class","d3plus_drop_selector")
    .style("position","absolute")
    .style("overflow","scroll")
    .style("top","0px")
    .style("z-index","-1")
    .style("border-style","solid")

  vars.data.forEach(function(o,i){

    var data = d3plus.utils.merge(styles,o)
    data.icon = false
    data.display = "block"
    data.border = "none"
    data.width = drop_width - (styles.stroke*2)
    data.margin = 0
    var text = check_value(vars.text,["drop","button"])
    if (!text) {
     text = "text"
    }
    var option = d3plus.ui(data)
      .type("button")
      .text(text)
      .parent(selector)
      .id(vars.id+"_option"+i)
      .timing(timing)
      .callback(vars.ui.value)

    if (o.value == vars.focus.value) {
      option.highlight(true)
    }

    option.draw()

  })

  var position = vars.container.node().getBoundingClientRect()

  selector.transition().duration(timing)
    .each("start",function(){
      if (vars.enabled) {
        d3.select(this).style("display","block")
      }
    })
    .style("left",function(){
      if (styles.align == "left") {
        return "0px"
      }
      else if (styles.align == "center") {
        return -((drop_width-button_width)/2)+"px"
      }
      else {
        return "auto"
      }
    })
    .style("right",function(){
      return styles.align == "right" ? "0px" : "auto"
    })
    .style("border-width",styles.stroke+"px")
    .style("border-color",styles.color)
    .style("width",(drop_width+(styles.padding*2))+"px")
    .style("max-height",function(){
      var max = window.innerHeight-position.top
      max -= vars.enabled ? button.height() : 0
      max -= styles.padding
      return max < vars["max-height"] ? max+"px" : vars["max-height"]+"px"
    })
    .style("top",function(){
      return vars.enabled ? button.height()+"px" : "0px"
    })
    .style("opacity",function(){
      return vars.enabled ? 1 : 0
    })
    .each("end",function(){
      if (!vars.enabled) {
        d3.select(this).style("display","none")
      }
      else {
        d3.select(this).transition().duration(timing)
          .style("top",function(){
            return vars.enabled ? button.height()+"px" : "0px"
          })
      }
    })

}
<|endoftext|>


<commit_before>/**
 * @file WScript specific File System implementation
 * @since 0.1.9
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_FS_OPENFOR*/ // File system stream opening mode
/*global _GPF_FS_TYPES*/ // File system types constants
/*global _GPF_HOST*/ // Host types
/*global _GpfWscriptBaseStream*/ // gpf.wscript.BaseStream
/*global _GpfWscriptReadableStream*/ // gpf.wscript.ReadableStream
/*global _GpfWscriptWritableStream*/ // gpf.wscript.WritableStream
/*global _gpfDefine*/ // Shortcut for gpf.define
/*global _gpfDefine*/ // Shortcut for gpf.define
/*global _gpfFsExploreEnumerator*/ // IFileStorage.explore helper
/*global _gpfMsFSO*/ // Scripting.FileSystemObject activeX
/*global _gpfPathDecompose*/ // Normalize path and returns an array of parts
/*global _gpfPathNormalize*/ // Normalize path
/*global _gpfPathNormalize*/ // Normalize path
/*global _gpfFileStorageByHost*/ // gpf.interfaces.IFileStorage per host
/*#endif*/

/*jshint wsh:true*/
/*eslint-env wsh*/
/*eslint-disable new-cap*/ // FileSystem object APIs are uppercased
/*global Enumerator*/ // Enumerator helper

/**
 * Translate WScript file object into a {@link gpf.typedef.fileStorageInfo}
 *
 * @param {Object} obj WScript file object
 * @param {gpf.fs.types} type Object type
 * @return {gpf.typedef.fileStorageInfo} Information about the object
 * @since 0.1.9
 */
function _gpfFsWScriptObjToFileStorageInfo (obj, type) {
    return {
        type: type,
        fileName: obj.Name.toLowerCase(),
        filePath: _gpfPathNormalize(obj.Path),
        size: obj.Size,
        createdDateTime: new Date(obj.DateCreated),
        modifiedDateTime: new Date(obj.DateLastModified)
    };
}

/* istanbuk ignore next */ // Because tested with NodeJS
function _gpfFsWscriptFSOCallWithArg (name, path) {
    return new Promise(function (resolve) {
        _gpfMsFSO[name](_gpfPathDecompose(path).join("\\"));
        resolve();
    });
}

/* istanbuk ignore next */ // Because tested with NodeJS
function _gpfFsWscriptFSOCallWithArgAndTrue (name, path) {
    return new Promise(function (resolve) {
        _gpfMsFSO[name](_gpfPathDecompose(path).join("\\"), true);
        resolve();
    });
}

/* istanbuk ignore next */ // Because tested with NodeJS
function _gpfFsWscriptGetFileInfo (path) {
    if (_gpfMsFSO.FileExists(path)) {
        return _gpfFsWScriptObjToFileStorageInfo(_gpfMsFSO.GetFile(path), _GPF_FS_TYPES.FILE);
    }
    return {
        type: _GPF_FS_TYPES.NOT_FOUND
    };
}

/* istanbuk ignore next */ // Because tested with NodeJS
function _gpfFsWscriptGetInfo (path) {
    if (_gpfMsFSO.FolderExists(path)) {
        return _gpfFsWScriptObjToFileStorageInfo(_gpfMsFSO.GetFolder(path), _GPF_FS_TYPES.DIRECTORY);
    }
    return _gpfFsWscriptGetFileInfo(path);
}

/* istanbuk ignore next */ // Because tested with NodeJS
function _gpfFsWScriptExploreList (collection) {
    var fsoEnum = new Enumerator(collection),
        results = [];
    for (; !fsoEnum.atEnd(); fsoEnum.moveNext()) {
        results.push(fsoEnum.item().Path);
    }
    return results;
}

/* istanbuk ignore next */ // Because tested with NodeJS
function _gpfFsWScriptExplore (path) {
    var folder;
    if (_gpfMsFSO.FolderExists(path)) {
        folder = _gpfMsFSO.GetFolder(path);
        return _gpfFsWScriptExploreList(folder.SubFolders)
            .concat(_gpfFsWScriptExploreList(folder.Files));
    }
    return [];
}

/**
 * WScript specific IFileStorage implementation
 *
 * @class gpf.wscript.FileStorage
 * @implements {gpf.interfaces.IFileStorage}
 * @private
 * @since 0.1.9
 */
var _GpfWScriptFileStorage = _gpfDefine(/** @lends gpf.wscript.FileStorage */ {
    $class: "gpf.wscript.FileStorage",

    //region gpf.interfaces.IFileStorage

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#getInfo
     * @since 0.1.9
     */
    getInfo: function (path) {
        return Promise.resolve(_gpfFsWscriptGetInfo(_gpfPathDecompose(path).join("\\")));
    },

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#openTextStream
     * @since 0.1.9
     */
    openTextStream: function (path, mode) {
        path = _gpfPathDecompose(path).join("\\");
        return new Promise(function (resolve) {
            var stream;
            if (_GPF_FS_OPENFOR.READING === mode) {
                stream = new _GpfWscriptReadableStream(_gpfMsFSO.OpenTextFile(path, 1, false));
            } else {
                stream = new _GpfWscriptWritableStream(_gpfMsFSO.OpenTextFile(path, 8, true));
            }
            resolve(stream);
        });
    },

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#close
     * @since 0.1.9
     */
    close: function (stream) {
        if (stream instanceof _GpfWscriptBaseStream) {
            return stream.close();
        }
        return Promise.reject(new gpf.Error.IncompatibleStream());
    },

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#explore
     * @since 0.1.9
     */
    explore: function (path) {
        return Promise.resolve(_gpfFsExploreEnumerator(this, _gpfFsWScriptExplore(_gpfPathDecompose(path).join("\\"))));
    },

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#createDirectory
     * @since 0.1.9
     */
    createDirectory: _gpfFsWscriptFSOCallWithArg.bind(null, "CreateFolder"),

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#deleteFile
     * @since 0.1.9
     */
    deleteFile: _gpfFsWscriptFSOCallWithArgAndTrue.bind(null, "DeleteFile"),

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#deleteDirectory
     * @since 0.1.9
     */
    deleteDirectory: _gpfFsWscriptFSOCallWithArgAndTrue.bind(null, "DeleteFolder")

    //endregion

});

_gpfFileStorageByHost[_GPF_HOST.WSCRIPT] = new _GpfWScriptFileStorage();
<commit_msg>Explore error management<commit_after>/**
 * @file WScript specific File System implementation
 * @since 0.1.9
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_FS_OPENFOR*/ // File system stream opening mode
/*global _GPF_FS_TYPES*/ // File system types constants
/*global _GPF_HOST*/ // Host types
/*global _GpfWscriptBaseStream*/ // gpf.wscript.BaseStream
/*global _GpfWscriptReadableStream*/ // gpf.wscript.ReadableStream
/*global _GpfWscriptWritableStream*/ // gpf.wscript.WritableStream
/*global _gpfDefine*/ // Shortcut for gpf.define
/*global _gpfDefine*/ // Shortcut for gpf.define
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*global _gpfFsExploreEnumerator*/ // IFileStorage.explore helper
/*global _gpfMsFSO*/ // Scripting.FileSystemObject activeX
/*global _gpfPathDecompose*/ // Normalize path and returns an array of parts
/*global _gpfPathNormalize*/ // Normalize path
/*global _gpfPathNormalize*/ // Normalize path
/*global _gpfFileStorageByHost*/ // gpf.interfaces.IFileStorage per host
/*#endif*/

/*jshint wsh:true*/
/*eslint-env wsh*/
/*eslint-disable new-cap*/ // FileSystem object APIs are uppercased
/*global Enumerator*/ // Enumerator helper

_gpfErrorDeclare("fs/wscript", {

    /**
     * ### Summary
     *
     * Path not explorable
     *
     * ### Description
     *
     * This error is used when explore is used with a path that does not point to a folder.
     */
    pathNotExplorable: "Path not explorable"

});

/**
 * Translate WScript file object into a {@link gpf.typedef.fileStorageInfo}
 *
 * @param {Object} obj WScript file object
 * @param {gpf.fs.types} type Object type
 * @return {gpf.typedef.fileStorageInfo} Information about the object
 * @since 0.1.9
 */
function _gpfFsWScriptObjToFileStorageInfo (obj, type) {
    return {
        type: type,
        fileName: obj.Name.toLowerCase(),
        filePath: _gpfPathNormalize(obj.Path),
        size: obj.Size,
        createdDateTime: new Date(obj.DateCreated),
        modifiedDateTime: new Date(obj.DateLastModified)
    };
}

function _gpfFsWscriptFSOCallWithArg (name, path) {
    return new Promise(function (resolve) {
        _gpfMsFSO[name](_gpfPathDecompose(path).join("\\"));
        resolve();
    });
}

function _gpfFsWscriptFSOCallWithArgAndTrue (name, path) {
    return new Promise(function (resolve) {
        _gpfMsFSO[name](_gpfPathDecompose(path).join("\\"), true);
        resolve();
    });
}

function _gpfFsWscriptGetFileInfo (path) {
    if (_gpfMsFSO.FileExists(path)) {
        return _gpfFsWScriptObjToFileStorageInfo(_gpfMsFSO.GetFile(path), _GPF_FS_TYPES.FILE);
    }
    return {
        type: _GPF_FS_TYPES.NOT_FOUND
    };
}

function _gpfFsWscriptGetInfo (path) {
    if (_gpfMsFSO.FolderExists(path)) {
        return _gpfFsWScriptObjToFileStorageInfo(_gpfMsFSO.GetFolder(path), _GPF_FS_TYPES.DIRECTORY);
    }
    return _gpfFsWscriptGetFileInfo(path);
}

function _gpfFsWScriptExploreList (collection) {
    var fsoEnum = new Enumerator(collection),
        results = [];
    for (; !fsoEnum.atEnd(); fsoEnum.moveNext()) {
        results.push(fsoEnum.item().Path);
    }
    return results;
}

function _gpfFsWScriptExplore (path) {
    var folder;
    if (_gpfMsFSO.FolderExists(path)) {
        folder = _gpfMsFSO.GetFolder(path);
        return _gpfFsWScriptExploreList(folder.SubFolders)
            .concat(_gpfFsWScriptExploreList(folder.Files));
    }
    gpf.Error.pathNotExplorable();
}

/**
 * WScript specific IFileStorage implementation
 *
 * @class gpf.wscript.FileStorage
 * @implements {gpf.interfaces.IFileStorage}
 * @private
 * @since 0.1.9
 */
var _GpfWScriptFileStorage = _gpfDefine(/** @lends gpf.wscript.FileStorage */ {
    $class: "gpf.wscript.FileStorage",

    //region gpf.interfaces.IFileStorage

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#getInfo
     * @since 0.1.9
     */
    getInfo: function (path) {
        return Promise.resolve(_gpfFsWscriptGetInfo(_gpfPathDecompose(path).join("\\")));
    },

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#openTextStream
     * @since 0.1.9
     */
    openTextStream: function (path, mode) {
        path = _gpfPathDecompose(path).join("\\");
        return new Promise(function (resolve) {
            var stream;
            if (_GPF_FS_OPENFOR.READING === mode) {
                stream = new _GpfWscriptReadableStream(_gpfMsFSO.OpenTextFile(path, 1, false));
            } else {
                stream = new _GpfWscriptWritableStream(_gpfMsFSO.OpenTextFile(path, 8, true));
            }
            resolve(stream);
        });
    },

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#close
     * @since 0.1.9
     */
    close: function (stream) {
        if (stream instanceof _GpfWscriptBaseStream) {
            return stream.close();
        }
        return Promise.reject(new gpf.Error.IncompatibleStream());
    },

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#explore
     * @since 0.1.9
     */
    explore: function (path) {
        var me = this;
        return new Promise(function (resolve) {
            resolve(_gpfFsExploreEnumerator(me, _gpfFsWScriptExplore(_gpfPathDecompose(path).join("\\"))));
        });
    },

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#createDirectory
     * @since 0.1.9
     */
    createDirectory: _gpfFsWscriptFSOCallWithArg.bind(null, "CreateFolder"),

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#deleteFile
     * @since 0.1.9
     */
    deleteFile: _gpfFsWscriptFSOCallWithArgAndTrue.bind(null, "DeleteFile"),

    /**
     * @gpf:sameas gpf.interfaces.IFileStorage#deleteDirectory
     * @since 0.1.9
     */
    deleteDirectory: _gpfFsWscriptFSOCallWithArgAndTrue.bind(null, "DeleteFolder")

    //endregion

});

_gpfFileStorageByHost[_GPF_HOST.WSCRIPT] = new _GpfWScriptFileStorage();
<|endoftext|>