Loads mock project data

@param {SwaggerServer} server
@param {function} next
438824
function loadMockData(server, next) {
  // Create REST resources for each project
  var resources = data.projects.map(function(project) {
    return new swagger.Resource('/projects', project.id, project);
  });

  // Save the resources to the mock data store
  server.dataStore.save(resources, next);
}
1161294
function deploy(req, res, next) {
  var dataSource = req.body;

  dataSource._id = req.params.id;

  forms.dataSources.deploy(req.connectionOptions, dataSource, dataSourcesHandler(constants.resultTypes.dataSources, req, next));
}
415535
function (next) {
    if (this.cancelled) return;

    debug('Running phase', this.phase);

    var tasks = [];
    var started = new Date();
    var self = this;
    var path = [];
    var env = _.cloneDeep(this.config.env);

    // need to clone the repo first
    if (this.phase === 'prepare') {
      tasks.push(this.provider.fetch.bind(this.provider, self.pluginContext(this.provider.id, env, path)));
    }

    this.plugins.forEach(function (plugin) {
      debug('Running plugin', plugin.id);
      // all plugins will get the final, fully populated env object
      _.extend(env, ('function' === typeof plugin.env) ? plugin.env(self.phase) : plugin.env);

      if ('string' === typeof plugin.path) {
        path.push(plugin.path);
      } else {
        path = path.concat('function' === typeof plugin.path ? plugin.path(self.phase) : plugin.path);
      }

      tasks.push(function (next) {
        utils.runPlugin(self.phase, plugin, self.pluginContext(plugin.id, env, path), next);
      });
    });

    async.series(tasks, this.phaseDone.bind(this, next, started));
  }
740658
function loadMock (mockData, options) {
    // make sure options is object
    options = requireValidOptionalObject(options)
    // load mock data from either array or object
    Array.isArray(mockData)
        // if data is array then load each mock in array
        ? _.each(mockData, mockData => _loadMock(mockData, options))
        // load mock data object
        : _loadMock(mockData, options)
}
336000
function (context, next) {
        if (context.options.force || !context.cached.template) {
            this._tasksQueue.push(Processor._models.task(
                context.cached._id, context.pathname, context.cached, !context.options.wait ? null :
                    function (err, cached) {
                        if (err) return next(err);
                        context.cached = cached;
                        next(null);
                    }
            ));
            if (!context.options.wait)
                next(null);
        }
        else next(null);
    }
552840
function (app, next) {

      if (hasDebug) {
        app.use(morgan(''
          + 'req:'.magenta + '\\n'
          + '  method : '.cyan + ':method HTTP/:http-version\\n'
          + '  path   : '.cyan + ':url', {
          immediate: true
        }));
      }

      next(null, app);
    }
827817
function addTemplateRoute(server, scaffold) {
        server.get(scaffold.path, function (req, res, next) {
            const transomTemplate = server.registry.get(scaffold.templateHandler);
            const contentType = scaffold.contentType || 'text/html';

            const p = new Promise(function (resolve, reject) {
                // Push request headers and params into the data going to the template.
                const data = scaffold.data || {};
                data.headers = req.headers;
                data.params = req.params;

                resolve(transomTemplate.renderHtmlTemplate(scaffold.templateName, data));
            }).then(function (pageData) {
                res.setHeader('content-type', contentType);
                res.end(pageData);
                next(false); // false stops the chain.
            }).catch(function (err) {
                next(err);
            });
        });
    }
631004
function load(data, site) {
  let promiseComponentsOps, promisePagesOps, promiseUrisOps, promiseListsOps, promiseUsersOps,
    prefix = site.prefix,
    compData = applyPrefix(data, site);

  promiseListsOps = saveObjects(`${prefix}/_lists/`, compData._lists, getPutOperation);
  promiseUrisOps = saveBase64Strings(`${prefix}/_uris/`, compData._uris, getPutOperation);
  _.each(compData._uris, function (page, uri) {
    log('info', `bootstrapped: ${uri} => ${page}`);
  });
  promiseComponentsOps = saveWithInstances(`${prefix}/_components/`, compData._components, function (name, item) {
    return bluebird.join(
      dbOps.getPutOperations(components.cmptPut, name, _.cloneDeep(item), locals.getDefaultLocals(site))
    ).then(_.flatten);
  });
  promisePagesOps = saveObjects(`${prefix}/_pages/`, compData._pages, (name, item) => [getPutOperation(name, item)]);
  promiseUsersOps = saveObjects('', compData._users, (name, item) => [getPutOperation(`/_users/${encode(`${item.username}@${item.provider}`)}`, item)]);

  /* eslint max-params: ["error", 5] */
  return bluebird.join(promiseComponentsOps, promisePagesOps, promiseUrisOps, promiseListsOps, promiseUsersOps, function (componentsOps, pagesOps, urisOps, listsOps, userOps) {
    const flatComponentsOps = _.flatten(componentsOps),
      ops = flatComponentsOps.concat(_.flattenDeep(pagesOps.concat(urisOps, listsOps, userOps)));

    return db.batch(ops, { fillCache: false, sync: false });
  });
}
951066
function loadTemplates() {
  const templatesPath = path.join(process.cwd(), plugin.config.templatesPath);

  return plugin.myrmex.fire('beforeTemplatesLoad')
  .then(() => {
    // Retrieve paths of all node packages
    return Promise.promisify(fs.readdir)(templatesPath);
  })
  .then(files => {
    // Load all packages configurations
    const templatePromises = [];
    _.forEach(files, (fileName) => {
      const templatePath = path.join(templatesPath, fileName);
      // subdir is the identifier of the template, so we pass it as the second argument
      templatePromises.push(loadTemplate(templatePath, fileName));
    });
    return Promise.all(templatePromises);
  })
  .then(templates => {
    // This event allows to inject code to add or delete or alter node templates configurations
    return plugin.myrmex.fire('afterTemplatesLoad', templates);
  })
  .spread(templates => {
    return Promise.resolve(templates);
  })
  .catch(e => {
    // In case the project does not have any template yet, an exception will be thrown
    // We silently ignore it
    if (e.code === 'ENOENT' && path.basename(e.path) === 'templates') {
      return Promise.resolve([]);
    }
    return Promise.reject(e);
  });
}
438441
function (options, callback) {
    var log = this.log;

    if (this.startMockServerFunc) {
      log('manual mock server startup');
      // app specific test runner does most of the work
      this.startMockServerFunc(options, callback);
    } else if (this.mockServerPlugin) {
      log('using mock server plugin');
      // adapter does most of the work
      var mockServer = this.mockServer = new Hapi.Server(this.mockServerOptions);
      mockServer.connection({ port: this.mocksPort });
      mockServer.register(this.mockServerPlugin, function (err) {
        if (err) {
          log('registered mock server plugin: ' + err.message);
          return callback(err);
        }
        log('registered mock server plugin;  starting mock server');
        mockServer.start(callback);
      });
    } else {
      log('no mock server setup/teardown functions provided *and* no plugin provided... not starting mock server');
      callback();
    }
  }
954051
function handleQueryParameters(request, response, next) {
	if (args.query === true && Object.keys(request.query).length > 0) {
		request.path += '/' + Object.keys(request.query).join('_') + '.json';
	}
	return next();
}
377810
function makeHttpRequest(next) {
  var start = Date.now();

  sepia.fixtureDir(path.join(process.cwd(), 'fixtures/custom'));

  request({
    url: 'http://localhost:1337',
    method: 'GET'
  }, function(err, data, body) {
    var time = Date.now() - start;

    console.log('FIXTURE DIR');
    console.log('  status:', data.statusCode);
    console.log('  body  :', body);
    console.log('  time  :', time);

    common.verify(function() {
      fs.existsSync('fixtures/custom').should.equal(true);
      common.shouldBeDynamicallyTimed(time);
    });

    console.log();

    next();
  });
}
842800
function mockResponseBody (req, res, next) {
  if (res.swagger) {
    if (res.swagger.isEmpty) {
      // There is no response schema, so send an empty response
      util.debug("%s %s does not have a response schema. Sending an empty response", req.method, req.path);
      res.send();
    }
    else {
      // Serialize the response body according to the response schema
      let schema = new JsonSchema(res.swagger.schema);
      let serialized = schema.serialize(res.swagger.wrap(res.body));

      switch (res.swagger.schema.type) {
        case "object":
        case "array":
        case undefined:
          sendObject(req, res, next, serialized);
          break;

        case "file":
          sendFile(req, res, next, serialized);
          break;

        default:
          sendText(req, res, next, serialized);
      }
    }
  }
  else {
    next();
  }
}
817746
function (request, response, next) {
                if (!next) {
                    next = makeDefaultNext(request, response);
                }
                try {
                    var url = request.url;
                    var questionIndex = url.indexOf("?");
                    var querystring = "";
                    if (questionIndex !== -1) {
                        // if there is a querystring, we'll just chop that part off
                        // it's still preserved in request.url, and should be handled
                        // by other middleware.
                        querystring = url.substring(questionIndex);
                        url = url.substring(0, questionIndex);
                    }
                    
                    var now = +new Date();
                    if (cacheExpirationTime < now) {
                        // time to reset the dynamic cache cache
                        
                        // Object.create(null) is used instead of {} so it doesn't have a prototype of Object.prototype
                        dynamicRouteCache = Object.create(null);
                        redirectCache = Object.create(null);
                        cacheExpirationTime = now + CACHE_CLEAR_TIME;
                    }
                    
                    var actualUrl = url;
                    var cachedResult = redirectCache[actualUrl];
                    if (cachedResult) {
                        movedPermanently(response, cachedResult + querystring);
                        return;
                    }
                    
                    var lowerMethod = request.method.toLowerCase();
                    if (url.length > 1 && url[url.length - 1] === "/") {
                        url = trimEndingSlashes(url);
                    }
                    var lowerUrl = url.toLowerCase();
                    var staticRoute = staticRoutes[lowerUrl];
                    var params;
                    var callback;
                    var descriptor;
                    var properUrl;
                    
                    if (staticRoute) {
                        properUrl = staticRoute.route;
                        if (properUrl !== actualUrl) {
                            redirectCache[actualUrl] = properUrl;
                            movedPermanently(response, properUrl + querystring);
                            return;
                        }
                        
                        descriptor = staticRoute.descriptor;
                        
                        // we found a static route
                        callback = descriptor[lowerMethod];
                        
                        if (!callback) {
                            // the URL exists, but does not have the provided method defined for it
                            methodNotAllowedHandler(request, response, next);
                            return;
                        }

                        params = emptyParams;
                    } else {
                        cachedResult = dynamicRouteCache[actualUrl];
                        if (cachedResult) {
                            descriptor = cachedResult.descriptor;
                            callback = descriptor[lowerMethod];
                            if (!callback) {
                                // the URL exists, but does not have the provided method defined for it
                                methodNotAllowedHandler(request, response, next);
                                return;
                            }
                            params = cachedResult.params;
                        } else {
                            searchDynamicRoutes:
                            for (var i = 0, len = dynamicRoutes.length; i < len; i += 1) {
                                var dynamicRoute = dynamicRoutes[i];
                                var prefix = dynamicRoute.prefix;
                            
                                if (prefix !== "/" && !startsWith(lowerUrl, prefix)) {
                                    continue;
                                }
                            
                                var routes = dynamicRoute.routes;
                                searchWithinPrefix:
                                for (var j = 0, lenJ = routes.length; j < lenJ; j += 1) {
                                    var route = routes[j];
                                    var match = route.regex.exec(url);
                                    if (!match) {
                                        continue;
                                    }
                                
                                    descriptor = route.descriptor;
                                    callback = descriptor[lowerMethod];
                                    if (!callback) {
                                        // the URL exists, but does not have the provided method defined for it
                                        methodNotAllowedHandler(request, response, next);
                                        return;
                                    }
                                
                                    var literals = route.literals;
                                    properUrl = literals[0];
                                    var argumentNames = route.argumentNames;
                                    var converters = route.converters;
                                    params = {};
                                    for (var k = 0, lenK = argumentNames.length; k < lenK; k += 1) {
                                        var unconvertedValue = match[k * 2 + 2];
                                        var convertedValue;
                                        try {
                                            convertedValue = converters[k](unconvertedValue);
                                        } catch (ex) {
                                            if (ex instanceof escort.ValidationError) {
                                                // if the converter explicitly throws a ValidationError, the route doesn't match.
                                                // thus, we need to keep searching for the correct route.
                                                callback = undefined;
                                                continue searchWithinPrefix;
                                            } else if (ex instanceof escort.CasingError) {
                                                unconvertedValue = ex.expectedCasing;
                                                convertedValue = converters[k](unconvertedValue); // guaranteed not to error
                                            } else {
                                                throw ex;
                                            }
                                        }
                                        properUrl += unconvertedValue;
                                        properUrl += literals[k + 1] || "";
                                        params[argumentNames[k]] = convertedValue;
                                    }
                                    if (route.hasEndingSlash) {
                                        properUrl += "/";
                                    }
                            
                                    if (actualUrl !== properUrl) {
                                        redirectCache[actualUrl] = properUrl;
                                        movedPermanently(response, properUrl + querystring);
                                        return;
                                    }
                                    
                                    // params needs to be frozen since it will be potentially used in later requests through the dynamic route caching system
                                    freeze(params);
                                    dynamicRouteCache[actualUrl] = {
                                        descriptor: descriptor,
                                        params: params
                                    };
                                    
                                    // we're done, so we need to break out of the outer for loop
                                    break searchDynamicRoutes;
                                }
                            }
                        }
                    }
                    
                    if (!callback) {
                        // route was unable to be located
                        if (notFoundHandler) {
                            notFoundHandler(request, response, next);
                        } else {
                            next();
                        }
                        return;
                    }
                    
                    // set params on request as well as pass it into the callback.
                    request.params = params;
                    // the descriptor is passed in as "this" so that the user can do this.post(request, response) from their get callback.
                    callback.call(descriptor, request, response, params, !notFoundHandler ? next : function (err) {
                        if (err) {
                            next(err);
                        } else {
                            notFoundHandler(request, response, next);
                        }
                    });
                } catch (err) {
                    next(err);
                }
            }
57640
function swaggerMetadata (req, res, next) {
  /**
   * The Swagger Metadata that is added to each HTTP request.
   * This object is exposed as `req.swagger`.
   *
   * @name Request#swagger
   */
  req.swagger = {
    /**
     * The complete Swagger API object.
     * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object)
     * @type {SwaggerObject|null}
     */
    api: null,

    /**
     * The Swagger path name, as it appears in the Swagger API.
     * (e.g. "/users/{username}/orders/{orderId}")
     * @type {string}
     */
    pathName: "",

    /**
     * The Path object from the Swagger API.
     * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathItemObject)
     * @type {object|null}
     */
    path: null,

    /**
     * The Operation object from the Swagger API.
     * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject)
     * @type {object|null}
     */
    operation: null,

    /**
     * The Parameter objects that apply to this request.
     * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameter-object-)
     * @type {object[]}
     */
    params: [],

    /**
     * The Security Requirement objects that apply to this request.
     * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#securityRequirementObject)
     * @type {object[]}
     */
    security: []
  };

  next();
}
940357
function(next) {
            if (!inNativeApp) return next(null, false, null, null, null);
            if (resourceIsBinary(filePath)) {
              var fullPath = shared.removeUrlMultislashes(fileFullPathRoot + '/' + filePath),
                  xhr;
              xhr = new XMLHttpRequest();
              xhr.open("GET", cacheUrl, true);
              xhr.responseType = "blob";
              xhr.onload = function(e) {
                next(null, true, fullPath, xhr.response, null);
              };
              xhr.onerror = function(e) {
                next(null, false)
              }
              xhr.send(null);
            } else {
              ajax(cacheUrl, null, compileData, function(err, data, compiled) {
                next(null, !err, null, data, compiled);
              });
            }
          }
503101
function loadMockHttpRequestError (mockData, options) {
    immutableAutomock.httpRequestErrorMocks[mockData.data.httpRequestId] = mockData.data
}