Default callback used when the http request queue gets a resource (html, pdf, css, ...) or an error

@param the HTTP error (if exist)
@param The HTTP result with the crawl options
@param callback(error)
499290
function crawl(error, result, callback) {

    // if HTTP error, delegate to the plugins
    if (error) {
        pm.error(error,result, callback);
        return;
    }

    var $ =  html.$(result);

    // Analyse the HTTP response in order to check the content (links, images, ...)
    // or apply a redirect
    async.parallel([
      // Call crawl function of the different plugins
      async.apply(pm.crawl.bind(pm), result, $),

      // Check if redirect
      async.apply(applyRedirect, result),

      // Check if HTML
      async.apply(analyzeHTML, result, $),
    ], function(error) {
        result = null;
        callback(error);
    });

}
494747
function(err, results) {
  if(err) {
    this.success = false;
    this.error = err;
    this.results = null;

    // customize error for error types
    if(util.isError(err)) {
      this.error = {
        message: err.message,
        type: err.type,
        arguments: err.arguments
      };
      if(NODE_ENV === 'development') {
        this.error.stack = err.stack;
      }
    }    

  } else {
    this.success = true;
    this.error = null;      
    this.results = convertToClient(results);    
  }
}
1217667
function crawlHref($,result, a, callback) {

      var link = $(a).attr('href');
      var parentUrl = result.url;
      if (link) {

        var anchor = $(a).text() ? $(a).text() : "";
        var noFollow = $(a).attr("rel");
        var isDoFollow =  ! (noFollow && noFollow === "nofollow");

        var linkUri = URI.linkToURI(parentUrl, link);

        pm.crawlLink(parentUrl, linkUri, anchor, isDoFollow, function(){
          addLinkToQueue(result, parentUrl, linkUri, anchor, isDoFollow, callback);
        });

      }
      else {
        callback();
      }

}
773599
function (baseUrl, method, handler, example, callback) {
    baseUrl = baseUrl || 'http://localhost';

    var client = null;
    var results = {
      failed: [],
      passed: []
    };
    var self = this;
    var testUrl = url.parse(String(baseUrl));
    testUrl.pathname = normalizePath(self.path, testUrl.pathname);
    testUrl = url.parse(url.format(testUrl));
    switch (testUrl.protocol) {
      case 'https:':
        client = https;
        break;
      case 'http:':
        client = http;
        break;
      default:
        var error = new Error('Invalid base site: ' + baseUrl +
          ' (should start with "http://" or "https://")');
        callback(error, results);
        return;
    }

    var beforeEachTest = self.beforeEachTest || function (next) { next(); };
    if (typeof beforeEachTest !== 'function') {
      callback(new Error('"beforeEachTest" should be a function'), results);
      return;
    }

    var afterEachTest = self.afterEachTest || function (next) { next(); };
    if (typeof afterEachTest !== 'function') {
      callback(new Error('"afterEachTest" should be a function'), results);
      return;
    }

    var requestOptions = {
      hostname: testUrl.hostname,
      port: testUrl.port,
      path: testUrl.pathname,
      method: method
    };

    var exampleRequest = example.request || {};
    var exampleResponse = example.response || {};

    if (exampleRequest.urlParameters) {
      requestOptions.path = replaceUrlParameters(requestOptions.path,
        exampleRequest.urlParameters);
    }

    if (exampleRequest.queryParameters) {
      var queryPairs = [];
      for (var queryParameter in exampleRequest.queryParameters) {
        var queryValue = exampleRequest.queryParameters[queryParameter];
        queryPairs.push(encodeURIComponent(queryParameter) +
          (queryValue ? '=' + encodeURIComponent(queryValue) : ''));
      }
      requestOptions.path += '?' + queryPairs.join('&');
    }

    if (exampleRequest.headers) {
      requestOptions.headers = exampleRequest.headers;
    }

    var summary = {
      handler: handler.title || '(no title)',
      method: requestOptions.method,
      uri: requestOptions.path,
      request: exampleRequest
    };

    beforeEachTest(function (error) {
      if (error) {
        callback(error, results);
        return;
      }

      var request = client.request(requestOptions, function (response) {
        var success = true;

        var expectedStatusCode = (typeof exampleResponse.status === 'function'
          ? exampleResponse.status
          : function (statusCode) {
            return statusCode === (exampleResponse.status || 200);
          });
        if (!expectedStatusCode(response.statusCode)) {
          success = false;
        }

        var expectedHeaders = null;
        if (exampleResponse.headers) {
          expectedHeaders = exampleResponse.headers;
          for (var header in expectedHeaders) {
            var headerValue = expectedHeaders[header];
            var expectedHeaderValue = (typeof headerValue === 'function'
              ? headerValue
              : function (value) {
                return value === headerValue;
              });
            if (!expectedHeaderValue(response.headers[header.toLowerCase()])) {
              success = false;
              break;
            }
          }
        }

        var expectedBody = null;
        if ('body' in exampleResponse) {
          var exampleBody = exampleResponse.body;
          expectedBody = (typeof exampleBody === 'function'
            ? exampleBody
            : function (body) {
              return body === jsonStringifyIfObject(exampleBody).trim();
            });
        }

        var body = '';
        response.on('data', function (chunk) {
          body += String(chunk);
        });

        response.on('end', function () {
          clearTimeout(timeout);
          body = body.trim();
          if (expectedBody !== null && !expectedBody(body)) {
            success = false;
          }
          if (success) {
            summary.response = exampleResponse;
            results.passed.push(summary);
            afterEachTest(function (error) {
              callback(error, results);
            });
            return;
          }
          summary.expectedResponse = exampleResponse;
          summary.actualResponse = {
            status: response.statusCode
          };
          if (expectedHeaders !== null) {
            summary.actualResponse.headers = response.headers;
          }
          if (expectedBody !== null) {
            summary.actualResponse.body = body;
          }
          results.failed.push(summary);
          afterEachTest(function (error) {
            callback(error, results);
          });
        });
      });

      request.on('error', function (error) {
        clearTimeout(timeout);
        summary.expectedResponse = exampleResponse;
        summary.actualResponse = {
          error: error.message || String(error)
        };
        results.failed.push(summary);
        afterEachTest(function (error) {
          callback(error, results);
        });
      });

      // Abort requests that take longer than 10 seconds.
      var timeout = setTimeout(function () {
        request.emit('error', new Error('timed out'));
      }, 10000);

      if ('body' in exampleRequest) {
        request.write(jsonStringifyIfObject(exampleRequest.body));
      }
      request.end();
    });
  }
768920
private static void callbackResult(String str, String pubKey, ICheckLoginSignHandler callback){
        JSONObject json = null;
        try {
            json = new JSONObject(str);
        } catch (JSONException e) {
            callback.onCheckResult(null, "json parse fail:" + e.getMessage(), false);
            return;
        }

        String rtnCode = json.optString("rtnCode");
        String errMsg = json.optString("errMsg");
        String ts = json.optString("ts");
        String rtnSign = json.optString("rtnSign");

        if("0".equals(rtnCode))
        {
            String nosign = "rtnCode=" + RSAUtil.urlEncode(rtnCode) + "&ts=" + RSAUtil.urlEncode(ts);
            boolean s = RSAUtil.doCheck(nosign, rtnSign, pubKey);
            callback.onCheckResult(rtnCode, "request success", s);
        } else {
            callback.onCheckResult(rtnCode, "request sign fail:" + errMsg, false);
        }
    }
823385
function(url, callback) {
      var t = this,
          originalUrl = url,
          page = null;

      // Change urls that end in / to /index
      if (url.substr(-1) === '/') {
        url = url + 'index';
      }

      // Return if it's in cache
      page = pageCache.get(url);
      if (page) {
        return callback(null, page);
      }

      // Read from storage
      page = new Page({id: url});
      page.fetch({liveSync: true, silenceErrors: true}, function(error) {

        // Process a 404.  This returns a transient page copied from
        // the default 404 page, with the id replaced by the specified url.
        if (error && error.code === 'NOTFOUND' && url !== '/app/core/404') {

          // Default the home page if notfound
          if (originalUrl === '/') {
            return t._getPage('/app/core/index', callback);
          }

          // Default the 404 page if notfound
          if (originalUrl === '/404') {
            return t._getPage('/app/core/404', callback);
          }

          // Otherwise it's a new page.  Create it.
          t._getPage('/404', function(error, page404) {
            if (error) {
              console.error("Error loading the 404 page", error);
              return callback('404 page load error');
            }

            // Copy the 404 page into a new page
            var newPage = new Page(JSON.parse(JSON.stringify(page404)));

            // Build a sane starting title.  TitleCase the last url element, separate words, replace underscores
            var title = $.titleCase(url.split('/').pop(), true).replace(/([A-Z])/g," $1").replace(/^ /,'').replace(/_/g,' ');
            var title = url.split('/').pop().replace(/([A-Z])/g," $1").replace(/^ /,'').replace(/_/g,' ');
            newPage.set({id:url, title:title, is404page:true});
            callback(null, newPage);
          });
          return;
        }

        // Process other errors
        if (error) {
          return callback(error);
        }

        // Assure the page model ID is correct on disk
        if (url !== page.get('id')) {
          page.set('id', url);
        }

        // Put the page into cache and return it
        pageCache.add(page);
        return callback(null, page);
      });
    }
503644
function (baseUrl, callback) {
    callback = callback || function (error, results) {
      if (error) {
        console.error.apply(console,
          error.stack ? [ error.stack ] : [ 'Error:', error ]);
      }
      var total = results.passed.length + results.failed.length;
      console.log('Results: ' + results.passed.length + '/' + total + ' test' +
        (total === 1 ? '' : 's') + ' passed.');
      if (results.failed.length > 0) {
        console.error('Failed:', jsonStringifyWithFunctions(results.failed));
      }
    };

    var results = {
      failed: [],
      passed: []
    };

    this.exportAllTests(baseUrl, function runNextTest (tests) {
      if (tests.length === 0) {
        callback(null, results);
        return;
      }

      var i = Math.floor(Math.random() * tests.length);
      var test = tests.splice(i, 1)[0];
      test(function (error, testResults) {
        if (testResults) {
          results.failed = results.failed.concat(testResults.failed);
          results.passed = results.passed.concat(testResults.passed);
        }
        if (error) {
          callback(error, results);
          return;
        }
        runNextTest(tests);
      });
    });
  }
275559
function crawlScripts(result, $, endCallback) {

    if (! result.scripts) {
      return endCallback();
    }

    log.debug({"url" : result.url, "step" : "analyzeHTML", "message" : "CrawlScripts"});

    async.each($('script'), function(script, callback) {
        crawlScript($, result, script, callback);
    }, endCallback);
}
1168835
protected final void registerCustomEventCallback(
            final CrawlEvent event,
            final PatternMatchingCallback callback) {
        Validate.notNull(event, "The event cannot be null.");
        Validate.notNull(callback, "The callback cannot be null.");

        callbackManager.addCustomEventCallback(event, callback);
    }
1030892
@Override
    public void error(VirtualConnection vc, Throwable t) {

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "error() called: vc=" + vc + " t=" + t);
        }

        // The VC might be null if the channel was destroyed before the callback completes
        if (vc != null) {
            HttpInboundServiceContextImpl mySC = (HttpInboundServiceContextImpl) vc.getStateMap().get(CallbackIDs.CALLBACK_HTTPISC);

            if (mySC.getHttpConfig().getDebugLog().isEnabled(DebugLog.Level.WARN)) {
                mySC.getHttpConfig().getDebugLog().log(DebugLog.Level.WARN, HttpMessages.MSG_WRITE_FAIL, mySC);
            }
            mySC.logLegacyMessage();
            // sendError() API already set persistent to false
            mySC.finishSendError();
        }
    }
642044
function QueueEntry(url, success, error, queue) {
    var _this = this;

    // A list of callbacks that will be called. Supports multiple callbacks.
    this.callbacks = {
        success: [success],
        error: [error]
        /**
         * @type {string}
         */
    };this.url = url;
    /**
     * Passes all the arguments to LoadSuccess
     * @type {function}
     */
    this.success = function () {
        for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
        }

        runCallbacks(_this.callbacks.success, function (callback) {
            callback.apply(undefined, [url].concat(args));
        });
    };
    /**
     * @type {function}
     * @param {Error} errorObject
     */
    this.error = function (errorObject) {
        runCallbacks(_this.callbacks.success, function (callback) {
            callback(url, errorObject);
        });
    };

    /**
     * Cancels loading - removes the image
     */
    this.cancel = function () {
        queue.cancel(_this);
    };

    /**
     * @type {LoadTask|null}
     */
    this.task = null;
}
1161579
@Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    JsonGenerator jg = null;
    String jsonpcb = null;
    PrintWriter writer = null;
    try {

      writer = response.getWriter();

      // "callback" parameter implies JSONP output
      jsonpcb = request.getParameter(CALLBACK_PARAM);
      if (jsonpcb != null) {
        response.setContentType("application/javascript; charset=utf8");
        writer.write(jsonpcb + "(");
      } else {
        response.setContentType("application/json; charset=utf8");
      }

      jg = jsonFactory.createJsonGenerator(writer);
      jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
      jg.useDefaultPrettyPrinter();

      int statusCode = renderMBeans(jg, request.getParameterValues("qry"));
      response.setStatus(statusCode);

    } catch (IOException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } finally {
      if (jg != null) {
        jg.close();
      }
      if (jsonpcb != null) {
        writer.write(");");
      }
      if (writer != null) {
        writer.close();
      }
    }

  }
688338
public static void executeAsync(Executor executor, HttpRequestBase request, FutureCallback<HttpResponse> callback) {

		try {
			executor.execute(new AsyncHttpCall(request, callback));
		}
		catch (Exception e) {
			log.error("Failed to execute asynchronously: " + request.getMethod() + " " + request.getURI().toString());
		}
	}
825745
function(url, callback) {
      if (!url) return callback('send(): url is empty.');
      console.log('send(): ' + url);
      request.get(url, function(err, res, body) {
        console.log(body);
	if (err) return callback(err);
        body = JSON.parse(body);
        if (body && body.query) {
          return callback('', body);
        } else {
          return callback('send(): No results returned.');
        }
      });
    }
155835
public static void result(final RequestContext context) {
        final HttpServletResponse response = context.getResponse();
        if (response.isCommitted()) { // Response sends redirect or error
            return;
        }

        AbstractResponseRenderer renderer = context.getRenderer();
        if (null == renderer) {
            renderer = new Http404Renderer();
        }
        renderer.render(context);
    }
62411
function callback(err, hasError) {

    if (err !== null) {
        console.log(chalk.red('Error running JSHint over project: %j\n'), err);
    }

    if (hasError) {
        console.log(chalk.blue('\nSummary\n=======\n'));
        for (var errorCode in errors) {
            if (errors.hasOwnProperty(errorCode)) {
                displaySummary(errorCode);
            }
        }

        console.log('');

        if (totalErrors > 1) {
            console.log(chalk.red('Found %d errors.\n'), totalErrors);
        } else {
            console.log(chalk.red('Found 1 error.\n'));
        }
    } else {
        console.log(chalk.green('No JSHint errors found.\n'));
    }
}
715743
@SuppressWarnings("unchecked")
    public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                callback.onFailure(new ApiException(e), 0, null);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                T result;
                try {
                    result = (T) handleResponse(response, returnType);
                } catch (ApiException e) {
                    callback.onFailure(e, response.code(), response.headers().toMultimap());
                    return;
                }
                callback.onSuccess(result, response.code(), response.headers().toMultimap());
            }
        });
    }