region Public API 
Generate website hook for android application.

@param {Object} cordovaContext - cordova context object
@param {Object} pluginPreferences - plugin preferences from config.xml file; already parsed
355596
function generateWebHook(cordovaContext, pluginPreferences) {
  var projectRoot = cordovaContext.opts.projectRoot;
  var configXmlHelper = new ConfigXmlHelper(cordovaContext);
  var packageName = configXmlHelper.getPackageName('android');
  var template = readTemplate(projectRoot);

  // if template was not found - exit
  if (template == null || template.length == 0) {
    return;
  }

  // generate hook content
  var linksToInsert = generateLinksSet(projectRoot, packageName, pluginPreferences);
  var hookContent = template.replace(LINK_PLACEHOLDER, linksToInsert);

  // save hook
  saveWebHook(projectRoot, hookContent);
}
928298
function plugin(options) {
    if (!options || typeof options !== 'object') {
        throw new Error('AjvMoment#plugin requires options');
    }
    if (!options.ajv) {
        throw new Error(`AjvMoment#plugin options requries an 'ajv' attribute (ajv instance)`);
    }
    if (!options.moment) {
        throw new Error(`AjvMoment#plugin options requries a 'moment' attribute (moment.js)`);
    }
    const { ajv, moment } = options;
    ajv.moment = moment;
    const keywordSettings = {
        type: 'string',
        statements: true,
        errors: true,
        inline
    };
    if (ajv) {
        ajv.addKeyword('moment', keywordSettings);
    }
    return keywordSettings;
}
1085110
protected void configureAndRefreshPortletApplicationContext(ConfigurablePortletApplicationContext pac, PortletContext pc) {
        if (ObjectUtils.identityToString(pac).equals(pac.getId())) {
            // The application context id is still set to its original default value
            // -> assign a more useful id based on available information
            String idParam = pc.getInitParameter(CONTEXT_ID_PARAM);
            if (idParam != null) {
                pac.setId(idParam);
            }
            else {
                // Generate default id...
                pac.setId(ConfigurablePortletApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                        ObjectUtils.getDisplayString(pc.getPortletContextName()));
            }
        }

        // Determine parent for root web application context, if any.
        ApplicationContext parent = loadParentContext(pc);

        pac.setParent(parent);
        pac.setPortletContext(pc);
        String initParameter = pc.getInitParameter(CONFIG_LOCATION_PARAM);
        if (initParameter != null) {
            pac.setConfigLocation(initParameter);
        }
        else {
            try {
                pac.setConfigLocation("/WEB-INF/portletApplicationContext.xml");
            }
            catch (UnsupportedOperationException e) {
                //Ignore, may get triggered if the context doesn't support config locations
            }
        }
        customizeContext(pc, pac);
        pac.refresh();
    }
979423
function parsePlatformPreferences(configData, platform) {
        var preferences = getPlatformPreferences(platform);
        switch(platform){
            case "ios":
                parseiOSPreferences(preferences, configData);
                break;
            case "android":
                parseAndroidPreferences(preferences, configData);
                break;
        }
    }
530489
function createNewAssociationFiles(pluginPreferences) {
  var teamId = pluginPreferences.iosTeamId;
  if (!teamId) {
    teamId = IOS_TEAM_ID;
  }

  pluginPreferences.hosts.forEach(function(host) {
    var content = generateFileContentForHost(host, teamId);
    saveContentToFile(host.name, content);
  });
}
234109
function generateEntitlements(cordovaContext, pluginPreferences) {
  context = cordovaContext;

  var currentEntitlements = getEntitlementsFileContent();
  var newEntitlements = injectPreferences(currentEntitlements, pluginPreferences);

  saveContentToEntitlementsFile(newEntitlements);
}
565099
function getBranchPreferences(context, configXml, branchXml) {
    return {
      projectRoot: getProjectRoot(context),
      projectName: getProjectName(configXml),
      branchKey: getBranchValue(branchXml, "branch-key"),
      linkDomain: getBranchLinkDomains(branchXml, "link-domain"),
      uriScheme: getBranchValue(branchXml, "uri-scheme"),
      iosBundleId: getBundleId(configXml, "ios"),
      iosProjectModule: getProjectModule(context),
      iosTeamRelease: getBranchValue(branchXml, "ios-team-release"), // optional
      iosTeamDebug: getBranchValue(branchXml, "ios-team-debug"), // optional
      androidBundleId: getBundleId(configXml, "android"), // optional
      androidPrefix: getBranchValue(branchXml, "android-prefix"), // optional
      androidTestMode: getBranchValue(branchXml, "android-testmode") // optional
    };
  }
1305356
function create(context) {
    const plugins = (context.options[0] || []).map(append("!"));

    return {
        CallExpression(node) {
            if (!isAmdCall(node)) return;

            getDependencyStringNodes(node)
                .filter(shouldBeChecked(plugins))
                .filter(hasJsExtension)
                .forEach(report(context));
        }
    };
}
1094184
function getPlatformPreferences(platform) {
        //init common config.xml prefs if we haven't already
        if(!preferencesData) {
            preferencesData = {
                common: configXml.findall('preference')
            };
        }

        var prefs = preferencesData.common || [];
        if(platform) {
            if(!preferencesData[platform]) {
                preferencesData[platform] = configXml.findall('platform[@name=\'' + platform + '\']/preference');
            }
            prefs = prefs.concat(preferencesData[platform]);
        }

        return prefs;
    }
245011
function _buildPreferencesContext(fullPath) {
        return PreferencesManager._buildContext(fullPath,
            fullPath ? LanguageManager.getLanguageForPath(fullPath).getId() : undefined);
    }
1187090
protected void createWebAppContext() {
    webapp = new WebAppContext();
    webapp.setThrowUnavailableOnStartupException(true);
    webapp.setServerClasses(getServerClasses());
    webapp.setContextPath(getContextPath());
    webapp.setTempDirectory(createTempDir("jetty-app-"));
    setSecureCookies();
  }
1009232
function readPreferences(cordovaContext) {
  // read data from projects root config.xml file
  var configXml = new ConfigXmlHelper(cordovaContext).read();
  if (configXml == null) {
    console.warn('config.xml not found! Please, check that it exist\'s in your project\'s root directory.');
    return null;
  }

  // look for data from the <universal-links> tag
  var ulXmlPreferences = configXml.widget['universal-links'];
  if (ulXmlPreferences == null || ulXmlPreferences.length == 0) {
    console.warn('<universal-links> tag is not set in the config.xml. Universal Links plugin is not going to work.');
    return null;
  }

  var xmlPreferences = ulXmlPreferences[0];

  // read hosts
  var hosts = constructHostsList(xmlPreferences);

  // read ios team ID
  var iosTeamId = getTeamIdPreference(xmlPreferences);

  return {
    'hosts': hosts,
    'iosTeamId': iosTeamId
  };
}
663812
private OnClickListener createPreferenceInitialFragmentButtonListener() {
        return new OnClickListener() {

            @Override
            public void onClick(final View v) {
                Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
                        BehaviorPreferenceFragment.class.getName());

                SharedPreferences sharedPreferences =
                        PreferenceManager.getDefaultSharedPreferences(MainActivity.this);

                boolean useAlternativeTitleDefaultValue =
                        Boolean.valueOf(getString(R.string.use_alternative_title_preference_key));
                String useAlternativeTitleKey =
                        getString(R.string.use_alternative_title_preference_key);

                if (sharedPreferences
                        .getBoolean(useAlternativeTitleKey, useAlternativeTitleDefaultValue)) {
                    String titleDefaultValue =
                            getString(R.string.alternative_title_preference_default_value);
                    String titleKey = getString(R.string.alternative_title_preference_key);
                    String title = sharedPreferences.getString(titleKey, titleDefaultValue);
                    intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
                }

                startActivity(intent);
            }

        };
    }
474871
function createPromptDialog (title, message, buttons, defaultText, callback) {

    var isPhone = cordova.platformId === 'windows' && WinJS.Utilities.isPhone;
    var isWindows = !!cordova.platformId.match(/windows/);

    createCSSElem('notification.css');

    var dlgWrap = document.createElement('div');
    dlgWrap.className = 'dlgWrap';

    var dlg = document.createElement('div');
    dlg.className = 'dlgContainer';

    if (isWindows) {
        dlg.className += ' dlgContainer-windows';
    } else if (isPhone) {
        dlg.className += ' dlgContainer-phone';
    }

    // dialog layout template
    dlg.innerHTML = _cleanHtml("<span id='lbl-title'></span><br/>" + // title
        "<span id='lbl-message'></span><br/>" + // message
        "<input id='prompt-input'/><br/>"); // input fields

    dlg.querySelector('#lbl-title').appendChild(document.createTextNode(title));
    dlg.querySelector('#lbl-message').appendChild(document.createTextNode(message));
    dlg.querySelector('#prompt-input').setAttribute('placeholder', defaultText);
    dlg.querySelector('#prompt-input').setAttribute('value', defaultText);

    function makeButtonCallback (idx) {
        return function () {
            var value = dlg.querySelector('#prompt-input').value || defaultText;
            dlgWrap.parentNode.removeChild(dlgWrap);

            if (callback) {
                callback({ input1: value, buttonIndex: idx }); // eslint-disable-line standard/no-callback-literal
            }
        };
    }

    function addButton (idx, label) {
        var button = document.createElement('button');
        button.className = 'dlgButton';
        button.tabIndex = idx;
        button.onclick = makeButtonCallback(idx + 1);
        if (idx === 0) {
            button.className += ' dlgButtonFirst';
        }
        button.appendChild(document.createTextNode(label));
        dlg.appendChild(button);
    }

    // reverse order is used since we align buttons to the right
    for (var idx = buttons.length - 1; idx >= 0; idx--) {
        addButton(idx, buttons[idx]);
    }

    dlgWrap.appendChild(dlg);
    document.body.appendChild(dlgWrap);

    // make sure input field is under focus
    dlg.querySelector('#prompt-input').select();
    // add Enter/Return key handling
    var defaultButton = dlg.querySelector('.dlgButtonFirst');
    dlg.addEventListener('keypress', function (e) {
        if (e.keyCode === 13) { // enter key
            if (defaultButton) {
                defaultButton.click();
            }
        }
    });

    return dlgWrap;
}
425956
function writeGoogleServiceCopyHook() {
  // Install after-prepare hook
  console.log("Install google-service.json after-prepare copy hook.");
  try {
    var afterPrepareScriptContent =
        `
var path = require("path");
var fs = require("fs");

module.exports = function($logger, $projectData, hookArgs) {

return new Promise(function(resolve, reject) {

        /* Decide whether to prepare for dev or prod environment */

        var isReleaseBuild = (hookArgs.appFilesUpdaterOptions && hookArgs.appFilesUpdaterOptions.release) ? true : false;
        var validProdEnvs = ['prod','production'];
        var isProdEnv = false; // building with --env.prod or --env.production flag

        if (hookArgs.platformSpecificData.env) {
            Object.keys(hookArgs.platformSpecificData.env).forEach((key) => {
                if (validProdEnvs.indexOf(key)>-1) { isProdEnv=true; }
            });
        }

        var buildType = isReleaseBuild || isProdEnv ? 'production' : 'development';

        /* Create info file in platforms dir so we can detect changes in environment and force prepare if needed */

        var npfInfoPath = path.join($projectData.platformsDir, hookArgs.platform.toLowerCase(), ".pluginfirebaseinfo");
        var npfInfo = {
            buildType: buildType,
        };

        try { fs.writeFileSync(npfInfoPath, JSON.stringify(npfInfo)); }
        catch (err) {
            $logger.info('nativescript-plugin-firebase: unable to create '+npfInfoPath+', prepare will be forced next time!');
        }


        /* Handle preparing of Google Services files */

        if (hookArgs.platform.toLowerCase() === 'android') {
            var destinationGoogleJson = path.join($projectData.platformsDir, "android", "app", "google-services.json");
            var destinationGoogleJsonAlt = path.join($projectData.platformsDir, "android", "google-services.json");
            var sourceGoogleJson = path.join($projectData.appResourcesDirectoryPath, "Android", "google-services.json");
            var sourceGoogleJsonProd = path.join($projectData.appResourcesDirectoryPath, "Android", "google-services.json.prod");
            var sourceGoogleJsonDev = path.join($projectData.appResourcesDirectoryPath, "Android", "google-services.json.dev");

            // ensure we have both dev/prod versions so we never overwrite singlular google-services.json
            if (fs.existsSync(sourceGoogleJsonProd) && fs.existsSync(sourceGoogleJsonDev)) {
                if (buildType==='production') { sourceGoogleJson = sourceGoogleJsonProd; } // use prod version
                else { sourceGoogleJson = sourceGoogleJsonDev; } // use dev version
            }

            // copy correct version to destination
            if (fs.existsSync(sourceGoogleJson) && fs.existsSync(path.dirname(destinationGoogleJson))) {
                $logger.out("Copy " + sourceGoogleJson + " to " + destinationGoogleJson + ".");
                fs.writeFileSync(destinationGoogleJson, fs.readFileSync(sourceGoogleJson));
                resolve();
            } else if (fs.existsSync(sourceGoogleJson) && fs.existsSync(path.dirname(destinationGoogleJsonAlt))) {
                // NativeScript < 4 doesn't have the 'app' folder
                $logger.out("Copy " + sourceGoogleJson + " to " + destinationGoogleJsonAlt + ".");
                fs.writeFileSync(destinationGoogleJsonAlt, fs.readFileSync(sourceGoogleJson));
                resolve();
            } else {
                $logger.warn("Unable to copy google-services.json.");
                reject();
            }
        } else if (hookArgs.platform.toLowerCase() === 'ios') {
            // we have copied our GoogleService-Info.plist during before-checkForChanges hook, here we delete it to avoid changes in git
            var destinationGooglePlist = path.join($projectData.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist");
            var sourceGooglePlistProd = path.join($projectData.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.prod");
            var sourceGooglePlistDev = path.join($projectData.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.dev");

            // if we have both dev/prod versions, let's remove GoogleService-Info.plist in destination dir
            if (fs.existsSync(sourceGooglePlistProd) && fs.existsSync(sourceGooglePlistDev)) {
                if (fs.existsSync(destinationGooglePlist)) { fs.unlinkSync(destinationGooglePlist); }
                resolve();
            } else { // single GoogleService-Info.plist modus
                resolve();
            }
        } else {
            resolve();
        }
    });
};
`;
    var scriptPath = path.join(appRoot, "hooks", "after-prepare", "firebase-copy-google-services.js");
    var afterPrepareDirPath = path.dirname(scriptPath);
    var hooksDirPath = path.dirname(afterPrepareDirPath);
    if (!fs.existsSync(afterPrepareDirPath)) {
      if (!fs.existsSync(hooksDirPath)) {
        fs.mkdirSync(hooksDirPath);
      }
      fs.mkdirSync(afterPrepareDirPath);
    }
    fs.writeFileSync(scriptPath, afterPrepareScriptContent);
  } catch (e) {
    console.log("Failed to install google-service.json after-prepare copy hook.");
    console.log(e);
  }

  /*
     Install before-checkForChanges hook
  */

  console.log("Install google-service.json before-checkForChanges copy hook.");
  try {
    var beforeCheckForChangesContent =
        `
var path = require("path");
var fs = require("fs");

module.exports = function($logger, $projectData, hookArgs) {
    return new Promise(function(resolve, reject) {

        /* Decide whether to prepare for dev or prod environment */

        var isReleaseBuild = hookArgs['checkForChangesOpts']['projectData']['$options']['argv']['release'] || false;
        var validProdEnvs = ['prod','production'];
        var isProdEnv = false; // building with --env.prod or --env.production flag

        var env = hookArgs['checkForChangesOpts']['projectData']['$options']['argv']['env'];
        if (env) {
            Object.keys(env).forEach((key) => {
                if (validProdEnvs.indexOf(key)>-1) { isProdEnv=true; }
            });
        }

        var buildType = isReleaseBuild || isProdEnv ? 'production' : 'development';

        /*
            Detect if we have nativescript-plugin-firebase temp file created during after-prepare hook, so we know
            for which environment {development|prod} the project was prepared. If needed, we delete the NS .nsprepareinfo
            file so we force a new prepare
        */
        var platform = hookArgs['checkForChangesOpts']['platform'].toLowerCase(); // ios | android
        var platformsDir = hookArgs['checkForChangesOpts']['projectData']['platformsDir'];
        var appResourcesDirectoryPath = hookArgs['checkForChangesOpts']['projectData']['appResourcesDirectoryPath'];
        var forcePrepare = true; // whether to force NS to run prepare, defaults to true
        var npfInfoPath = path.join(platformsDir, platform, ".pluginfirebaseinfo");
        var nsPrepareInfoPath = path.join(platformsDir, platform, ".nsprepareinfo");
        var copyPlistOpts = { platform, appResourcesDirectoryPath, buildType, $logger }

        if (fs.existsSync(npfInfoPath)) {
            var npfInfo = undefined;
            try { npfInfo = JSON.parse(fs.readFileSync(npfInfoPath, 'utf8')); }
            catch (e) { $logger.info('nativescript-plugin-firebase: error reading '+npfInfoPath); }

            if (npfInfo && npfInfo.hasOwnProperty('buildType') && npfInfo.buildType===buildType) {
                $logger.info('nativescript-plugin-firebase: building for same environment, not forcing prepare.');
                forcePrepare=false;
            }
        } else { $logger.info('nativescript-plugin-firebase: '+npfInfoPath+' not found, forcing prepare!'); }

        if (forcePrepare) {
            $logger.info('nativescript-plugin-firebase: running release build or change in environment detected, forcing prepare!');

            if (fs.existsSync(npfInfoPath)) { fs.unlinkSync(npfInfoPath); }
            if (fs.existsSync(nsPrepareInfoPath)) { fs.unlinkSync(nsPrepareInfoPath); }

            if (copyPlist(copyPlistOpts)) { resolve(); } else { reject(); }
        } else { resolve(); }
    });
};

/*
    Handle preparing of Google Services files for iOS
*/
var copyPlist = function(copyPlistOpts) {
    if (copyPlistOpts.platform === 'android') { return true; }
    else if (copyPlistOpts.platform === 'ios') {
        var sourceGooglePlistProd = path.join(copyPlistOpts.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.prod");
        var sourceGooglePlistDev = path.join(copyPlistOpts.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist.dev");
        var destinationGooglePlist = path.join(copyPlistOpts.appResourcesDirectoryPath, "iOS", "GoogleService-Info.plist");

        // if we have both dev/prod versions, we copy (or overwrite) GoogleService-Info.plist in destination dir
        if (fs.existsSync(sourceGooglePlistProd) && fs.existsSync(sourceGooglePlistDev)) {
            if (copyPlistOpts.buildType==='production') { // use prod version
                copyPlistOpts.$logger.out("nativescript-plugin-firebase: copy " + sourceGooglePlistProd + " to " + destinationGooglePlist + ".");
                fs.writeFileSync(destinationGooglePlist, fs.readFileSync(sourceGooglePlistProd));
                return true;
            } else { // use dev version
                copyPlistOpts.$logger.out("nativescript-plugin-firebase: copy " + sourceGooglePlistDev + " to " + destinationGooglePlist + ".");
                fs.writeFileSync(destinationGooglePlist, fs.readFileSync(sourceGooglePlistDev));
                return true;
            }
        } else if (!fs.existsSync(destinationGooglePlist)) { // single GoogleService-Info.plist modus but missing`;
    if (externalPushClientOnly) {
      beforeCheckForChangesContent += `
            return true; // this is a push-only project, so this is allowed`;
    } else {
      beforeCheckForChangesContent += `
            copyPlistOpts.$logger.warn("nativescript-plugin-firebase: " + destinationGooglePlist + " does not exist. Please follow the installation instructions from the documentation");
            return false;`;
    }
    beforeCheckForChangesContent += `
        } else {
            return true; // single GoogleService-Info.plist modus
        }
    } else { return true; }
}
`;
    var scriptPath = path.join(appRoot, "hooks", "before-checkForChanges", "firebase-copy-google-services.js");
    var afterPrepareDirPath = path.dirname(scriptPath);
    var hooksDirPath = path.dirname(afterPrepareDirPath);
    if (!fs.existsSync(afterPrepareDirPath)) {
      if (!fs.existsSync(hooksDirPath)) {
        fs.mkdirSync(hooksDirPath);
      }
      fs.mkdirSync(afterPrepareDirPath);
    }
    fs.writeFileSync(scriptPath, beforeCheckForChangesContent);
  } catch (e) {
    console.log("Failed to install google-service.json before-checkForChanges copy hook.");
    console.log(e);
  }
}
489934
function (framework) {
                var targetDir = framework.targetDir || '';
                var dest = path.join(cordovaProjectWindowsPlatformDir, 'plugins', dummyPluginInfo.id, targetDir, path.basename(framework.src));
                var copiedSuccessfully = fs.existsSync(path.resolve(dest));
                expect(copiedSuccessfully).toBe(true);
            }
628892
function () {
	    	var deferred = $q.defer();
	    	var promise = deferred.promise;
            
            function ok(value){
                deferred.resolve(value);
            }
            
            function errorCallback(error){
                deferred.reject(new Error(error));
            }
            
            if($window.plugins){
                $window.plugins.appPreferences.show()
                    .then(ok, errorCallback);
            } else {
                deferred.reject(new Error(this.pluginNotEnabledMessage));
            }
	    	
	    	this.decoratePromise(promise);
	    	return promise;
	    }