Beispiel #1
0
  @Override
  public void run(final StackEntry stack) {
    String output =
        this.source.hasText() ? stack.resolveValue(this.source.getText()).toString() : null;
    long steps = stack.intFromSource("Steps", -1);
    long step = stack.intFromSource("Step", -1);
    long amount = stack.intFromSource("Amount", -1);
    long add = stack.intFromSource("Add", -1);
    String name = stack.stringFromSource("Name");

    if (amount >= 0) OperationContext.get().setAmountCompleted((int) amount);
    else if (add >= 0)
      OperationContext.get()
          .setAmountCompleted(OperationContext.get().getAmountCompleted() + (int) add);

    if ((step >= 0) && StringUtil.isNotEmpty(name))
      OperationContext.get().setCurrentStep((int) step, name);

    if (steps >= 0) OperationContext.get().setSteps((int) steps);

    if (StringUtil.isNotEmpty(output)) OperationContext.get().setProgressMessage(output);

    stack.setState(ExecuteState.Done);

    stack.resume();
  }
Beispiel #2
0
  public CacheFile resolveCachePath(String path) {
    LocalFileStore fs = Hub.instance.getPublicFileStore();

    if (fs == null) return null;

    if (StringUtil.isEmpty(path)) return fs.cacheResolvePath("dcw/" + this.getAlias());

    if (path.charAt(0) == '/') return fs.cacheResolvePath("dcw/" + this.getAlias() + path);

    return fs.cacheResolvePath("dcw/" + this.getAlias() + "/" + path);
  }
Beispiel #3
0
  @Override
  public void init(StackEntry stack, XElement el) {
    this.seqnum = (int) stack.intFromElement(el, "StartAt", this.seqnum);

    String size = stack.stringFromElement(el, "Size", "10MB");

    this.size = (int) FileUtil.parseFileSize(size);

    String temp = stack.stringFromElement(el, "Template");

    if (StringUtil.isNotEmpty(temp)) this.template = temp;
  }
Beispiel #4
0
  public static FileSystemFile tempFile(String ext) {
    CommonPath path =
        new CommonPath(
            "/"
                + (StringUtil.isNotEmpty(ext)
                    ? FileUtil.randomFilename(ext)
                    : FileUtil.randomFilename()));

    Path tfpath = FileUtil.allocateTempFolder2();

    FileSystemDriver drv = new FileSystemDriver(tfpath);
    drv.isTemp(true);

    return new FileSystemFile(drv, path, false);
  }
Beispiel #5
0
  @Override
  public CompositeStruct buildParams() {
    RecordStruct flds = new RecordStruct();

    for (FieldRequest fld : this.fields) flds.setField(fld.getName(), fld.getParams(flds));

    RecordStruct params =
        new RecordStruct(new FieldStruct("Table", this.table), new FieldStruct("Fields", flds));

    if (StringUtil.isNotEmpty(this.id)) params.setField("Id", this.id);

    params.setField("When", this.when);

    if (this.sets.getSize() > 0) params.setField("Sets", this.sets);

    this.parameters = params;

    return this.parameters;
  }
Beispiel #6
0
  public static ISettingsObfuscator prepDomainObfuscator(String obclass, String seed) {
    ISettingsObfuscator obfuscator = null;

    if (StringUtil.isEmpty(obclass)) obclass = "divconq.util.BasicSettingsObfuscator";

    try {
      obfuscator = (ISettingsObfuscator) Hub.instance.getInstance(obclass);
    } catch (Exception x) {
      OperationContext.get().error("Bad Settings Obfuscator");
      return null;
    }

    XElement clock1 = Hub.instance.getConfig().find("Clock");

    String obid = (clock1 != null) ? clock1.getAttribute("Id") : null;

    obfuscator.init(
        new XElement("Clock", new XAttribute("Id", obid), new XAttribute("Feed", seed)));

    return obfuscator;
  }
Beispiel #7
0
  @Override
  public void execute(DatabaseInterface conn, DatabaseTask task, OperationResult log) {
    RecordStruct params = task.getParamsAsRecord();

    // System.out.println("NT 1 Got: " + params.toPrettyString());

    // TODO replicating
    // if (task.isReplicating())

    String title = params.getFieldAsString("Title");

    if (StringUtil.isNotEmpty(title)) title = title.trim();

    /* this is a fine concept, but maybe not the right place for it - TODO
    String hash = null;

    if (StringUtil.isNotEmpty(title)) {
    	title = title.trim();

    	hash = HashUtil.getSha256(title);

    	Object tid = db.firstInIndex("dcmThread", "dcmHash", hash, when, false);

    	if (tid == null) {
    		String titleb = title.toLowerCase();

    		if (titleb.startsWith("re:")) {
    			titleb = titleb.substring(3).trim();
    			hash = HashUtil.getSha256(title);

    			tid = db.firstInIndex("dcmThread", "dcmHash", hash, when, false);
    		}
    	}

    	String threadid = tid.toString();
    }
    */

    boolean trackTitle = params.getFieldAsBooleanOrFalse("TrackTitle");

    // TODO figure out how to send to future date (target date vs modified)

    String uuid = Session.nextUUId();
    String hash = HashUtil.getSha256((trackTitle && StringUtil.isNotEmpty(title)) ? title : uuid);
    DateTime now = new DateTime();
    DateTime target = params.getFieldAsDateTime("TargetDate");

    if (target == null) target = now;

    String originator =
        !params.isFieldEmpty("Originator")
            ? params.getFieldAsString("Originator")
            : log.getContext().getUserContext().getUserId();

    DbRecordRequest req =
        new InsertRecordRequest()
            .withTable("dcmThread")
            .withUpdateField("dcmUuid", uuid)
            .withUpdateField("dcmHash", hash)
            .withUpdateField("dcmCreated", now)
            .withUpdateField("dcmModified", now)
            .withUpdateField("dcmOriginator", originator)
            .withConditionallyUpdateFields(params, "Title", "dcmTitle", "EndDate", "dcmEndDate");

    if (target != null) req.withUpdateField("dcmTargetDate", target);

    ListStruct lbs = params.getFieldAsList("Labels");

    if ((lbs != null) && !lbs.isEmpty())
      req.withUpdateField("dcmLabels", "|" + StringUtil.join(lbs.toStringList(), "|") + "|");

    ListStruct parties = params.getFieldAsList("Parties");

    if (!parties.isEmpty()) {
      for (int i = 0; i < parties.getSize(); i++) {
        RecordStruct party = parties.getItemAsRecord(i);

        String pident = party.getFieldAsString("Party");

        req.withUpdateField("dcmParty", pident, pident)
            .withUpdateField("dcmFolder", pident, party.getFieldAsString("Folder"));

        lbs = party.getFieldAsList("PartyLabels");

        if ((lbs != null) && !lbs.isEmpty())
          req.withUpdateField(
              "dcmPartyLabels", pident, "|" + StringUtil.join(lbs.toStringList(), "|") + "|");
      }
    }

    RecordStruct cnt = params.getFieldAsRecord("Content");
    String content = cnt.getFieldAsString("Content");
    String stamp = TimeUtil.stampFmt.print(new DateTime());

    req.withUpdateField("dcmContent", stamp, content)
        .withUpdateField("dcmContentHash", stamp, HashUtil.getSha256(content))
        .withUpdateField("dcmContentType", stamp, cnt.getFieldAsString("ContentType"));

    if (!cnt.isFieldEmpty("Source"))
      req.withUpdateField("dcmSource", stamp, cnt.getFieldAsString("Source"));

    if (!cnt.isFieldEmpty("Attributes"))
      req.withUpdateField("dcmAttributes", stamp, cnt.getFieldAsRecord("Attributes"));

    task.getDbm().submit(req, task.getResult());
  }
Beispiel #8
0
  public Cookie resolveLocale(HttpContext context, UserContext usr, OperationContextBuilder ctxb) {
    if (this.locales.size() == 0) {
      // make sure we have at least 1 locale listed for the site
      String lvalue = this.getDefaultLocale();

      // add the list of locales supported for this site
      this.locales.put(lvalue, this.getLocaleDefinition(lvalue));
    }

    LocaleDefinition locale = null;

    // see if the path indicates a language
    CommonPath path = context.getRequest().getPath();

    if (path.getNameCount() > 0) {
      String lvalue = path.getName(0);

      locale = this.locales.get(lvalue);

      // extract the language from the path
      if (locale != null) context.getRequest().setPath(path.subpath(1));
    }

    // but respect the cookie if it matches something though
    Cookie langcookie = context.getRequest().getCookie("dcLang");

    if (locale == null) {
      if (langcookie != null) {
        String lvalue = langcookie.value();

        // if everything checks out set the op locale and done
        if (this.locales.containsKey(lvalue)) {
          ctxb.withOperatingLocale(lvalue);
          return null;
        }

        locale = this.getLocaleDefinition(lvalue);

        // use language if variant - still ok and done
        if (locale.hasVariant()) {
          if (this.locales.containsKey(locale.getLanguage())) {
            ctxb.withOperatingLocale(
                lvalue); // keep the variant part, it may be used in places on site - supporting a
                         // lang implicitly allows all variants
            return null;
          }
        }

        // otherwise ignore the cookie, will replace it
      }
    }

    // see if the domain is set for a specific language
    if (locale == null) {
      String domain = context.getRequest().getHeader("Host");

      if (domain.indexOf(':') > -1) domain = domain.substring(0, domain.indexOf(':'));

      locale = this.domainlocales.get(domain);
    }

    // see if the user has a preference
    if (locale == null) {
      String lvalue = usr.getLocale();

      if (StringUtil.isNotEmpty(lvalue)) locale = this.locales.get(lvalue);
    }

    // if we find any locale at all then to see if it is the default
    // if not use it, else use the default
    if ((locale != null) && !locale.equals(this.getDefaultLocaleDefinition())) {
      ctxb.withOperatingLocale(locale.getName());
      return new DefaultCookie("dcLang", locale.getName());
    }

    // clear the cookie if we are to use default locale
    if (langcookie != null) return new DefaultCookie("dcLang", "");

    // we are using default locale, nothing more to do
    return null;
  }
Beispiel #9
0
  public void init(XElement config) {
    this.dictionary = null;
    this.locales.clear();

    // for a sub-site, may have additional dict to load
    if (this != this.domain.getRootSite()) {
      LocalFileStore pubfs = Hub.instance.getPublicFileStore();

      Path cpath =
          pubfs.resolvePath("/dcw/" + this.domain.getAlias() + "/sites/" + this.alias + "/config");

      if ((cpath != null) && Files.exists(cpath)) {
        // dictionary

        Path dicpath = cpath.resolve("dictionary.xml");

        if (Files.exists(dicpath)) {
          this.dictionary = new Dictionary();
          this.dictionary.setParent(this.domain.getDomainInfo().getDictionary());
          this.dictionary.load(dicpath);
        }
      }
    }

    if (config != null) {
      // this settings are only valid for sub sites
      if (this != this.domain.getRootSite()) {
        if (config.hasAttribute("Integration")) {
          try {
            this.integration = SiteIntegration.valueOf(config.getAttribute("Integration", "Files"));
          } catch (Exception x) {
            this.integration = SiteIntegration.Files;
          }
        }
      }

      if (config.hasAttribute("Locale")) {
        this.locale = config.getAttribute("Locale");

        this.localedef = this.getLocaleDefinition(this.locale);

        // add the list of locales supported for this site
        this.locales.put(this.locale, this.localedef);
      }

      // these settings are valid for root and sub sites

      for (XElement pel : config.selectAll("Locale")) {
        String lname = pel.getAttribute("Name");

        if (StringUtil.isEmpty(lname)) continue;

        LocaleDefinition def = this.getLocaleDefinition(lname);

        this.locales.put(lname, def);

        for (XElement del : pel.selectAll("Domain")) {
          String dname = del.getAttribute("Name");

          if (StringUtil.isEmpty(lname)) continue;

          this.domainlocales.put(dname, def);
        }
      }
    }
  }
Beispiel #10
0
  @Override
  public void execute(DatabaseInterface conn, DatabaseTask task, OperationResult log) {
    if (task.isReplicating()) {
      // TODO what should happen during a replicate?
      task.complete();
      return;
    }

    RecordStruct params = task.getParamsAsRecord();
    TablesAdapter db = new TablesAdapter(conn, task);
    BigDateTime when = BigDateTime.nowDateTime();

    String password = params.getFieldAsString("Password");
    String uname = params.getFieldAsString("Username");

    // TODO part of Trust monitoring -- boolean suspect =
    // if (AddUserRequest.meetsPasswordPolicy(password, true).hasLogLevel(DebugLevel.Warn))
    //	params.withField("Suspect", true);

    String uid = null;

    Object userid = db.firstInIndex("dcUser", "dcUsername", uname, when, false);

    if (userid != null) uid = userid.toString();

    // fail right away if not a valid user
    if (StringUtil.isEmpty(uid)) {
      log.errorTr(123);
      task.complete();
      return;
    }

    String ckey = params.getFieldAsString("ClientKeyPrint");

    // find out if this is a master key
    if (StringUtil.isNotEmpty(ckey)) {
      System.out.println("sign in client key: " + ckey);

      task.pushDomain(Constants.DB_GLOBAL_ROOT_DOMAIN);

      Object mk =
          db.getStaticList("dcDomain", Constants.DB_GLOBAL_ROOT_DOMAIN, "dcMasterKeys", ckey);

      Object mpp =
          (mk == null)
              ? null
              : db.getStaticScalar(
                  "dcDomain", Constants.DB_GLOBAL_ROOT_DOMAIN, "dcMasterPasswordPattern");

      task.popDomain();

      // if master key is present for the client key then check the password pattern
      if (mk != null) {
        boolean passcheck = false;

        if (StringUtil.isEmpty((String) mpp)) {
          passcheck = true;
        } else {
          Pattern pp = Pattern.compile((String) mpp);
          Matcher pm = pp.matcher(password);
          passcheck = pm.matches();
        }

        if (passcheck) {
          this.signIn(conn, task, db, log, when, uid);
          return;
        }
      }
    }

    if (StringUtil.isNotEmpty(password)) {
      password = password.trim();

      Object fndpass = db.getDynamicScalar("dcUser", uid, "dcPassword", when);

      System.out.println("local password: "******"try local password: "******"root")) {
        task.pushDomain(Constants.DB_GLOBAL_ROOT_DOMAIN);

        Object gp =
            db.getStaticScalar("dcDomain", Constants.DB_GLOBAL_ROOT_DOMAIN, "dcGlobalPassword");

        task.popDomain();

        System.out.println("global password: "******"try global password: "******"dcUser", uid, "dcConfirmCode");

      if (password.equals(fndpass)) {
        Object ra = db.getStaticScalar("dcUser", uid, "dcRecoverAt");

        if (ra == null) {
          // if code matches then good login
          this.signIn(conn, task, db, log, when, uid);
          return;
        }

        if (ra != null) {
          DateTime radt = Struct.objectToDateTime(ra);
          DateTime pastra = new DateTime().minusHours(2);

          if (!pastra.isAfter(radt)) {
            // if code matches and has not expired then good login
            this.signIn(conn, task, db, log, when, uid);
            return;
          }
        }
      }
    }

    log.errorTr(123);
    task.complete();
  }
Beispiel #11
0
  public void signIn(
      DatabaseInterface conn,
      DatabaseTask task,
      TablesAdapter db,
      OperationResult log,
      BigDateTime when,
      String uid) {
    ICompositeBuilder out = task.getBuilder();
    RecordStruct params = task.getParamsAsRecord();
    String did = task.getDomain();

    String token = null;

    try {
      if (StringUtil.isEmpty(uid)) {
        log.errorTr(123);
        task.complete();
        return;
      }

      if (!db.isCurrent("dcUser", uid, when, false)) {
        log.errorTr(123);
        task.complete();
        return;
      }

      if (!task.isReplicating()) {
        // TODO a confirmed login requires at least user name and a confirmation code, it might also
        // take a password
        // but the code must be present to become a confirmed user
        // i '$$get1^dcDb("dcUser",uid,"dcConfirmed") d
        // . i (code'="")&($$get1^dcDb("dcUser",uid,"dcConfirmCode")=code) s
        // Params("Confirmed")=1,confirmed=1 q
        // . d err^dcConn(124) q

        token = Session.nextSessionId();
      }

      if (log.hasErrors()) {
        task.complete();
        return;
      }

      // replication will need these later
      if (!task.isReplicating()) {
        params.setField("Token", token);
        params.setField("Uid", uid);
      }

      // both isReplicating and normal store the token

      conn.set("dcSession", token, "LastAccess", task.getStamp());
      conn.set("dcSession", token, "User", uid);
      conn.set("dcSession", token, "Domain", did);

      // if (confirmed)
      //	db.setStaticScalar("dcUser", uid, "dcConfirmed", confirmed);

      // TODO create some way to track last login that doesn't take up db space
      // or make last login an audit thing...track all logins in StaticList?

      // done with replication stuff
      if (task.isReplicating()) {
        task.complete();
        return;
      }

      // load info about the user
      ListStruct select =
          new ListStruct(
              new RecordStruct(new FieldStruct("Field", "Id"), new FieldStruct("Name", "UserId")),
              new RecordStruct(
                  new FieldStruct("Field", "dcUsername"), new FieldStruct("Name", "Username")),
              new RecordStruct(
                  new FieldStruct("Field", "dcFirstName"), new FieldStruct("Name", "FirstName")),
              new RecordStruct(
                  new FieldStruct("Field", "dcLastName"), new FieldStruct("Name", "LastName")),
              new RecordStruct(
                  new FieldStruct("Field", "dcEmail"), new FieldStruct("Name", "Email")),
              new RecordStruct(
                  new FieldStruct("Field", "dcLocale"), new FieldStruct("Name", "Locale")),
              new RecordStruct(
                  new FieldStruct("Field", "dcChronology"), new FieldStruct("Name", "Chronology")),
              // TODO we actually need group tags too - extend how this works
              new RecordStruct(
                  new FieldStruct("Field", "dcAuthorizationTag"),
                  new FieldStruct("Name", "AuthorizationTags")),
              new RecordStruct(
                  new FieldStruct("Value", token), new FieldStruct("Name", "AuthToken")));

      // out.startRecord();
      // out.field("UserInfo");

      this.writeRecord(conn, task, log, out, db, "dcUser", uid, when, select, true, false, false);

      // out.field("AdditionalTags", null);
      // out.endRecord();
    } catch (Exception x) {
      log.error("SignIn: Unable to create resp: " + x);
    }

    task.complete();
  }