Example #1
0
void Trajectory::readJSON(const string &filename) {
  JSON::Reader reader(filename);
  JSON::ValuePtr data = reader.parse();

  if (data->isDict()) {
    // Units
    float scale = 10;
    if (data->has("units")) {
      string units = String::toUpper(data->getString("units"));

      if (units == "NM" || units == "NANOMETERS") scale = 1;
      else if (units != "A" && units != "ANGSTROM" && units == "ANGSTROMS")
        LOG_WARNING("Unrecognized units '" << data->getString("units") << "'");
    }

    // Topology
    if (data->has("atoms")) {
      topology->loadJSON(*data, scale);
      topology->setTS();
    }

    // Positions
    if (data->has("positions")) {
      JSON::List list = data->getList("positions");
      for (unsigned i = 0; i < list.size(); i++)
        add(new Positions(list.getList(i), scale));
    }

  } else add(new Positions(*data, 10));
}
Example #2
0
bool JSONAPI::handlePage(HTTP::WebContext &ctx, ostream &stream,
                         const URI &uri) {
  if (!String::startsWith(uri.getPath(), root)) return false;

  string cmd = uri.getPath().substr(root.length());

  // Look up command
  api_t::const_iterator it = api.find(cmd);
  if (it == api.end()) return false;

  ctx.setDynamic(); // Don't cache
  HTTP::Connection &con = ctx.getConnection();

  bool jsonp = !jsonpCB.empty() && uri.has(jsonpCB);

  if (jsonp) {
    con.getResponse().setContentType("application/javascript");
    con << uri.get(jsonpCB) << '(';

  } else con.getResponse().setContentType("application/json");

  JSON::Writer writer(con, 0, !uri.has("pretty"),
                      uri.has("python_mode") ? JSON::Writer::PYTHON_MODE :
                      JSON::Writer::JSON_MODE);

  try {
    // Parse JSON data
    JSON::ValuePtr msg;

    if (con.getRequest().hasContentType() &&
        String::startsWith(con.getRequest().getContentType(),
                           "application/json")) {
      MemoryBuffer &payload = con.getPayload();
      if (payload.getFill()) msg = JSON::Reader(payload).parse();

    } else if (!uri.empty()) {
      msg = new JSON::Dict;

      for (URI::const_iterator it = uri.begin(); it != uri.end(); it++)
        msg->insert(it->first, it->second);
    }

    // Dispatch API command
    if (msg.isNull()) LOG_DEBUG(5, "JSONAPI Call: " << cmd << "()");
    else LOG_DEBUG(5, "JSONAPI Call: " << cmd << '(' << *msg << ')');
    it->second->handle(ctx, cmd, msg, writer);

    // Make sure JSON stream is complete
    writer.close();

  } catch (const Exception &e) {
    LOG_ERROR(e);

    // Clear possibly partial or invalid response
    con.clearResponseBuffer();

    // jsonp header
    if (jsonp) con << uri.get(jsonpCB) << '(';

    // Send error message
    JSON::Writer writer(con, 0, true);
    writer.beginList();
    writer.append("error");
    writer.append(e.getMessage());
    writer.endList();
    writer.close();
  }

  if (jsonp) con << ");";

  return true;
}
SmartPointer<Value> Javascript::require(Callback &cb, Value &args) {
    string id = args.getString(0);

    modules_t::iterator it = modules.find(id);
    if (it != modules.end()) return it->second->getExports();

    string path = searchPath(id);
    if (path.empty()) THROWS("Module '" << id << "' not found");

    // Handle package.json
    if (String::endsWith(path, "/package.json")) {
        JSON::ValuePtr package = JSON::Reader(path).parse();
        path = SystemUtilities::absolute(path, package->getString("main"));
    }

    // Register module
    SmartPointer<Module> module = new Module(id, path);
    modules.insert(modules_t::value_type(id, module));

    SmartPointer<Scope> scope = impl->newScope();
    SmartPointer<Factory> factory = getFactory();
    SmartPointer<Value> exports = factory->createObject();

    if (String::endsWith(path, ".json")) {
        // Read JSON data
        js::Sink sink(factory);
        JSON::Reader(path).parse(sink);
        sink.close();
        exports = sink.getRoot();

    } else {
        // Push path
        SmartFunctor<Javascript> smartPopPath(this, &Javascript::popPath);
        pushPath(path);

        // Get global object for this scope
        SmartPointer<Value> global = scope->getGlobalObject();

        // Inject native properties
        global->copyProperties(*nativeProps);

        // Create module object
        SmartPointer<Value> obj = factory->createObject();
        obj->set("id", factory->create(id));
        obj->set("exports", exports);
        obj->set("filename", factory->create(path));
        obj->set("name", factory->create(id));

        // Set global vars
        global->set("id", factory->create(id));
        global->set("exports", exports);
        global->set("module", obj);

        // Compile & eval code
        scope->eval(path);

        // Get exports, it may have been reassigned
        exports = obj->get("exports");
    }

    module->setExports(exports->makePersistent());

    return exports;
}
Example #4
0
bool OAuth2SessionLogin::handlePage(HTTP::WebContext &ctx, ostream &stream,
                                    const URI &uri) {
  HTTP::Connection &con = ctx.getConnection();
  HTTP::Request &request = con.getRequest();
  HTTP::Response &response = con.getResponse();

  ctx.setDynamic(); // Don't cache

  // Force secure
  if (!con.isSecure())
    THROWCS("Cannot logon via insecure port",
            HTTP::StatusCode::HTTP_UNAUTHORIZED);

  // Get session ID
  string sid = request.findCookie(sessionManager->getSessionCookie());
  if (sid.empty() && uri.has("state")) sid = uri.get("state");

  HTTP::SessionPtr session = sessionManager->findSession(ctx, sid);

  try {
    if (session.isNull() ||
        (uri.has("state") && uri.get("state") != session->getID()) ||
        (!uri.has("state") && session->getUser().empty())) {
      session = sessionManager->openSession(ctx);
      sid = session->getID();

      URI redirectURL = auth->getRedirectURL(uri.getPath(), sid);
      response.redirect(redirectURL);

    } else if (session->getUser().empty()) {
      // TODO Make sure session is not very old

      URI postURI = auth->getVerifyURL(uri, sid);
      LOG_DEBUG(5, "Token URI: " << postURI);

      // Extract query data
      string data = postURI.getQuery();
      postURI.setQuery("");

      // Verify authorization with OAuth2 server
      HTTP::Transaction tran(sslCtx);
      tran.post(postURI, data.data(), data.length(),
                "application/x-www-form-urlencoded", 1.0);

      // Read response
      tran.receiveHeader();
      JSON::ValuePtr token = JSON::Reader(tran).parse();

      LOG_DEBUG(5, "Token Response: \n" << tran.getResponse() << *token);

      // Verify token
      string accessToken = auth->verifyToken(token);

      // Get profile
      URI profileURL = auth->getProfileURL(accessToken);
      HTTP::Transaction tran2(sslCtx);
      tran2.get(profileURL);

      // Read response
      tran2.receiveHeader();
      JSON::ValuePtr profile = JSON::Reader(tran2).parse();

      // Process profile
      string email = profile->getString("email");
      if (!profile->getBoolean("email_verified"))
        THROWCS("Email not verified", HTTP::StatusCode::HTTP_UNAUTHORIZED);
      session->setUser(email);
      LOG_INFO(1, "Authorized: " << email);

      // Final redirect to remove auth parameters
      response.redirect(uri.getPath());

    } else return false; // Already authorized

    // Make sure session cookie is set
    sessionManager->setSessionCookie(ctx);

  } catch (...) {
    // Close session on error
    if (!sid.empty()) sessionManager->closeSession(ctx, sid);
    throw;
  }

  return true;
}