Ejemplo n.º 1
0
  /**
   * Create and return an OrderTotal object for the tax amount.
   *
   * @param order
   * @param dispPriceWithTax
   * @param locale
   * @return Returns an OrderTotal object for this module
   * @throws Exception
   */
  public OrderTotal getOrderTotal(Order order, boolean dispPriceWithTax, Locale locale)
      throws Exception {
    OrderTotal ot;
    StaticData sd = staticDataHM.get(getStoreId());

    // Get the resource bundle
    ResourceBundle rb = getResourceBundle(mutex, bundleName, resourceBundleMap, locale);
    if (rb == null) {
      throw new KKException(
          "A resource file cannot be found for the country " + locale.getCountry());
    }
    ot = new OrderTotal();
    ot.setSortOrder(sd.getSortOrder());
    ot.setClassName(code);

    // Call the TaxCloud service
    callTaxCloud(sd, order, ot);

    // Set the title of the order total
    StringBuffer title = new StringBuffer();
    title.append(rb.getString(MODULE_ORDER_TOTAL_TAX_CLOUD_TITLE));
    title.append(":");
    ot.setTitle(title.toString());

    return ot;
  }
Ejemplo n.º 2
0
  public GlobalLexicalModel(
      final String filePath, final float weight, final int[] inFactors, final int[] outFactors) {
    System.err.print("Creating global lexical model...\n");

    // register as score producer
    StaticData.instance().getScoreIndexManager().addScoreProducer(this);

    List<Float> weights = new ArrayList<Float>();
    weights.add(weight);
    StaticData.instance().setWeightsForScoreProducer(this, weights);

    // load model

    try {
      loadData(filePath, inFactors, outFactors);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    // define bias word
    FactorCollection factorCollection = FactorCollection.instance();
    m_bias = new Word();
    final Factor factor =
        factorCollection.addFactor(FactorDirection.Input, inFactors[0], "**BIAS**");
    m_bias.setFactor(inFactors[0], factor);

    m_cache = null;
  }
Ejemplo n.º 3
0
 @Override
 public byte[] getStaticData(UserPublicKey owner) {
   byte[] dummy = null;
   StaticData staticData = new StaticData(owner.getPublicKeys(), dummy);
   RowData[] users = staticData.select();
   if (users == null || users.length != 1) return null;
   return users[0].data;
 }
Ejemplo n.º 4
0
  @Override
  public GameEngine.StaticData initStatic() {
    StaticData s = new StaticData();

    s.sprite = Sprite.fromResources(R.drawable.plateau1, 4);
    s.sprite.setMatrix(1f, 1f, null, null);

    return s;
  }
Ejemplo n.º 5
0
 public int getSortOrder() {
   StaticData sd;
   try {
     sd = staticDataHM.get(getStoreId());
     return sd.getSortOrder();
   } catch (KKException e) {
     log.error("Can't get the store id", e);
     return 0;
   }
 }
Ejemplo n.º 6
0
 @Override
 public boolean setStaticData(UserPublicKey owner, byte[] signedStaticData) {
   try {
     StaticData userData =
         new StaticData(owner.getPublicKeys(), owner.unsignMessage(signedStaticData));
     return userData.insert();
   } catch (TweetNaCl.InvalidSignatureException e) {
     System.err.println("Invalid signature setting static data for: " + owner);
     return false;
   }
 }
Ejemplo n.º 7
0
  @Override
  public GameEngine.StaticData initStatic() {
    StaticData s = new StaticData();

    s.spriteBase = Sprite.fromResources(R.drawable.base2, 4);
    s.spriteBase.setMatrix(1f, 1f, null, null);

    s.spriteCanon = Sprite.fromResources(R.drawable.mortar, 8);
    s.spriteCanon.setMatrix(0.8f, null, new Vector2(0.4f, 0.2f), -90f);

    return s;
  }
Ejemplo n.º 8
0
  /**
   * Sets some static variables during setup
   *
   * @throws KKException
   */
  public void setStaticVariables() throws KKException {
    KKConfiguration conf;
    StaticData staticData = staticDataHM.get(getStoreId());
    if (staticData == null) {
      staticData = new StaticData();
      staticDataHM.put(getStoreId(), staticData);
    }

    conf = getEng().getConfiguration(MODULE_ORDER_TOTAL_SHIPPING_SORT_ORDER);
    if (conf == null) {
      staticData.setSortOrder(0);
    } else {
      staticData.setSortOrder(new Integer(conf.getValue()).intValue());
    }
  }
  public static void join(String name, String pass, int maxStanzas) {
    StaticData sd = StaticData.getInstance();

    ConferenceGroup grp = sd.roster.initMuc(name, pass);
    // требуется для возможности нормального выхода
    // sd.roster.mucContact(name, Contact.ORIGIN_GC_MYSELF);
    // sd.roster.activeRooms.addElement(jid);

    JabberDataBlock x = new JabberDataBlock("x", null, null);
    x.setNameSpace("http://jabber.org/protocol/muc");
    if (pass.length() != 0) {
      // adding password to presence
      x.addChild("password", pass);
    }

    JabberDataBlock history = x.addChild("history", null);
    history.setAttribute("maxstanzas", String.valueOf(maxStanzas));
    history.setAttribute("maxchars", "32768");
    try {
      long last = grp.getConference().lastMessageTime;
      long delay = (grp.conferenceJoinTime - last) / 1000;
      if (last != 0)
        history.setAttribute("seconds", String.valueOf(delay)); // todo: change to since
    } catch (Exception e) {
    }
    ;

    // sd.roster.groups.getGroup(name.substring(0,
    // name.indexOf('@'))).imageExpandedIndex=ImageList.ICON_GCJOIN_INDEX;
    sd.roster.sendPresence(name, null, x);
    sd.roster.reEnumRoster();
  }
Ejemplo n.º 10
0
  @Test
  public void testStaticLangDs() throws JAXBException, IOException {
    JAXBElement<?> jaxb =
        (JAXBElement<?>)
            _ds.unmarshal(
                JarTestResourceUtils.readDemoFileAsStream("test/static_test_lmap.xml", _ds_cfg));

    DataSetDescr dsd = (DataSetDescr) jaxb.getValue();

    StaticData sdf = dsd.getStaticData();
    assertEquals(1, sdf.getColumns().getColumn().size());
    assertEquals(2, sdf.getStaticRows().getRow().size());

    LangMap lm = dsd.getLangMap();
    assertNotNull(lm);
    assertEquals(1, lm.getColumn().size());
  }
 private void switchAccount(boolean login) {
   if (!login) parentView = StaticData.getInstance().roster;
   destroyView();
   Config cf = Config.getInstance();
   cf.accountIndex = cursor;
   cf.saveToStorage();
   Account.loadAccount(login);
 }
Ejemplo n.º 12
0
  /**
   * @param rb
   * @return A ShippingQuote object
   * @throws KKException
   */
  private ShippingQuote getShippingQuote(ResourceBundle rb) throws KKException {
    StaticData sd = staticDataHM.get(getStoreId());
    ShippingQuote quote = new ShippingQuote();

    // Populate some attributes from static data
    quote.setCode(code);
    quote.setModuleCode(code);
    quote.setSortOrder(sd.getSortOrder());
    quote.setIcon(icon);
    quote.setTaxClass(sd.getTaxClass());

    // Populate locale specific attributes from the resource bundle
    quote.setDescription(rb.getString(MODULE_SHIPPING_ITEM_TEXT_DESCRIPTION));
    quote.setTitle(rb.getString(MODULE_SHIPPING_ITEM_TEXT_TITLE));

    return quote;
  }
Ejemplo n.º 13
0
  /**
   * From the ShippingCountry we find the iso code of the country and determine its zone.
   *
   * @param order
   * @return Returns a ShippingQuote object
   * @throws KKException
   */
  public ShippingQuote getQuote(Order order, ShippingInfo info) throws Exception {
    StaticData sd = staticDataHM.get(getStoreId());
    // Throws an exception if there are no physical products. They may be all digital download
    // products.
    checkForProducts(info);

    // Get the resource bundle
    ResourceBundle rb = getResourceBundle(mutex, bundleName, resourceBundleMap, info.getLocale());
    if (rb == null) {
      throw new KKException(
          "A resource file cannot be found for the country " + info.getLocale().getCountry());
    }

    // Get a partially filled ShippingQuote object
    ShippingQuote quote = this.getShippingQuote(rb);

    /*
     * The global parameter zone, if greater than zero, should reference a GeoZone. If the
     * DeliveryAddress of the order isn't within that GeoZone, then we throw an exception
     */
    if (sd.getZone() > 0) {
      checkZone(info, sd.getZone());
    }

    // Create the return string
    StringBuffer retTextBuf = new StringBuffer();
    retTextBuf.append(rb.getString(MODULE_SHIPPING_ITEM_TEXT_WAY));
    quote.setResponseText(retTextBuf.toString());

    // Return the cost
    BigDecimal orderCost = sd.getCost().multiply(new BigDecimal(info.getNumProducts()));
    quote.setCost(orderCost);
    quote.setHandlingCost(sd.getHandling());
    BigDecimal costPlusHandling = orderCost.add(sd.getHandling());
    if (sd.getTaxClass() > 0) {
      quote.setTax(
          getEng()
              .getTax(
                  costPlusHandling,
                  info.getDeliveryCountry().getId(),
                  info.getDeliveryZone().getZoneId(),
                  sd.getTaxClass()));
      quote.setTotalExTax(costPlusHandling);
      quote.setTotalIncTax(quote.getTax().add(costPlusHandling));
    } else {
      quote.setTax(new BigDecimal(0));
      quote.setTotalExTax(costPlusHandling);
      quote.setTotalIncTax(costPlusHandling);
    }
    return quote;
  }
Ejemplo n.º 14
0
  private net.taxcloud.Address verifyAddress(StaticData sd, net.taxcloud.Address address) {

    String uspsUserID = sd.getUspsId();
    AddressService addressService = new AddressService();

    try {
      address = addressService.verifyAddress(uspsUserID, address);
    } catch (Exception e) {
      log.error("Error in verifyAddress: ", e);
    }
    return address;
  }
Ejemplo n.º 15
0
  /**
   * Create and return an OrderTotal object for the shipping cost.
   *
   * @param order
   * @param dispPriceWithTax
   * @param locale
   * @return Returns an OrderTotal object for this module
   * @throws Exception
   */
  public OrderTotal getOrderTotal(Order order, boolean dispPriceWithTax, Locale locale)
      throws Exception {
    OrderTotal ot;
    StaticData sd = staticDataHM.get(getStoreId());

    // Get the resource bundle
    ResourceBundle rb = getResourceBundle(mutex, bundleName, resourceBundleMap, locale);
    if (rb == null) {
      throw new KKException(
          "A resource file cannot be found for the country " + locale.getCountry());
    }

    ot = new OrderTotal();
    ot.setSortOrder(sd.getSortOrder());
    ot.setClassName(code);
    if (order.getShippingQuote() == null) {
      ot.setTitle(rb.getString(MODULE_ORDER_TOTAL_SHIPPING_TITLE) + ":");
      ot.setValue(new BigDecimal(0));
      ot.setText(getCurrMgr().formatPrice(new BigDecimal(0), order.getCurrencyCode()));
    } else {
      ot.setTitle(
          order.getShippingQuote().getTitle()
              + " ("
              + order.getShippingQuote().getResponseText()
              + "):");
      BigDecimal cost;
      if (dispPriceWithTax) {
        cost = order.getShippingQuote().getTotalIncTax();
      } else {
        cost = order.getShippingQuote().getTotalExTax();
      }
      ot.setValue(cost);
      ot.setText(getCurrMgr().formatPrice(cost, order.getCurrencyCode()));
    }

    return ot;
  }
Ejemplo n.º 16
0
  private void switchType() {
    int index = choiseType.getSelectedIndex();
    try {
      Object rfocus = StaticData.getInstance().roster.getFocusedObject();
      switch (index) {
        case 0: // jid
          if (targetList != null)
            if (rfocus instanceof Contact) {
              textValue.setString(((Contact) rfocus).getBareJid());
            }
          form.set(2, textValue);
          break;
        case 1: // group
          if (targetList != null)
            textValue.setString(
                ((rfocus instanceof Group) ? (Group) rfocus : ((Contact) rfocus).getGroup())
                    .getName());

          form.set(2, textValue);
          break;
        case 2: // subscription
          form.set(2, choiceSubscr);
          break;

        case 3:
          form.set(2, new StringItem(null, "(ANY)"));
      }
      /*if (index==2) {
          form.set(2, choiceSubscr);
      } else {
          textValue.setLabel(PrivacyItem.types[index]);
          form.set(2, textValue);
      }
       */
    } catch (Exception e) {
      /* При смене на самого себя */
    }
  }
Ejemplo n.º 17
0
  public static void checkDataSetDescrFull(DataSetDescr ds) {
    assertEquals("Description", "Test DataSet", ds.getDescr());
    assertEquals("Enabled", true, ds.isEnabled());

    LangMap lmap = ds.getLangMap();
    assertNotNull("lang_map tag check", lmap);
    List<LangColumn> lc = lmap.getColumn();
    assertNotNull("lang_map->column(s) tag check", lc);
    assertEquals("Lang Map Size", 2, lc.size());
    assertEquals("COL1 Lang Column not found", "COL1", lc.get(0).getName());
    assertEquals("COL2 Lang Column not found", "COL2", lc.get(1).getName());

    ExColumns ec = ds.getExColumns();
    assertNotNull("ex_columns tag check", ec);

    AutoIncColumns lai = ec.getAutoInc();
    assertNotNull("ex_columns->auto_inc tag check", lai);
    List<AutoIncColumn> ai = lai.getColumn();
    assertNotNull("ex_columns->auto_inc->column(s) tag check", ai);
    assertEquals("Auto Inc Column Size", 2, ai.size());
    assertEquals("Auto Inc Column #1 Name", "A11", ai.get(0).getName());
    assertEquals("Auto Inc Column #2 Name", "B22", ai.get(1).getName());

    CalcColumns lcc = ec.getCalc();
    assertNotNull("ex_columns->calc tag check", lcc);
    List<CalcColumn> cc = lcc.getColumn();
    assertNotNull("ex_columns->calc->column(s) tag check", lc);
    assertEquals("Calculated Column Size", 2, cc.size());
    assertEquals("Calculated Column #1 Name", "CALC1", cc.get(0).getName());
    assertEquals("Calculated Column #1 Formula", "A + B", cc.get(0).getValue());
    assertEquals("Calculated Column #2 Name", "CALC2", cc.get(1).getName());
    assertEquals("Calculated Column #2 Formula", "C + D", cc.get(1).getValue());

    SortGroup fs = ds.getSortByGrp();
    ConditionFilter cf = ds.getFilter();
    assertEquals("Condition", "A < B", cf.getValue());

    List<SortCond> sff = fs.getSortBy();
    checkFilter(sff.get(0), 1, "COL1", SortTypes.ASC, false);
    checkFilter(sff.get(1), 2, "COL2", SortTypes.DESC, false);

    assertNull("Non-existing static_ds", ds.getStaticData());
    // Check recursion
    GroupData dsg = ds.getGroupData();

    assertNotNull("group_ds tag check", dsg);
    List<DataSetExt> ldsd1 = dsg.getDsList().getGroupDsOrStaticDsOrCsvDs();
    assertEquals("DsGroup #1 size", 2, ldsd1.size());

    // Check nested group
    DataSetExt dse = ldsd1.get(0);
    assertEquals(dse.getClass(), GroupDataSetDescr.class);
    List<DataSetExt> ldsd2 =
        ((GroupDataSetDescr) dse).getGroupData().getDsList().getGroupDsOrStaticDsOrCsvDs();
    assertEquals("DsGroup #2 size", 4, ldsd2.size());

    // Check just class of each element
    assertEquals(ldsd2.get(0).getClass(), GroupDataSetDescr.class);
    assertEquals(ldsd2.get(1).getClass(), StaticDataSetDescr.class);
    assertEquals(ldsd2.get(2).getClass(), CsvDataSetDescr.class);
    assertEquals(ldsd2.get(3).getClass(), SqlDataSetDescr.class);

    dse = ldsd1.get(1);
    assertEquals(dse.getClass(), StaticDataSetDescr.class);
    StaticDataSetDescr dsd = (StaticDataSetDescr) dse;

    StaticDataSetDescr sds = dsd;
    assertNotNull("group_ds->static_ds tag check", sds);
    StaticData sdf = sds.getStaticData();
    assertNotNull("static_ds->static_set tag check", sdf);
    Columns cs = sdf.getColumns();
    assertNotNull("static_ds->columns tag check", cs);
    List<ColumnHeader> ch = cs.getColumn();
    assertNotNull("columns->column tag check", ch);
    assertEquals(2, ch.size());
    checkColumnHeader(ch.get(0), "COL1", "java.lang.String", "ERROR GRP 2 !!!");
    checkColumnHeader(ch.get(1), "COL2", "java.lang.String", "ERROR GRP 2 !!!");

    StaticRecords sr = sdf.getStaticRows();
    assertNotNull("static_ds->static tag check", dsg);
    List<RowDef> lrd = sr.getRow();
    assertNotNull("static tag->row(s) check", dsg);
    assertEquals("Static Rows size", 2, lrd.size());

    RowDef srd = lrd.get(0);
    List<RowCell> lcd = srd.getCell();
    assertNotNull("row#1>column(s) check", lcd);
    assertEquals("Static Columns size", 2, lcd.size());

    checkRowColumn(lcd.get(0), 1, 1, "COL1", "bBb");
    checkRowColumn(lcd.get(1), 1, 2, "COL2", "УуУ");

    srd = lrd.get(1);
    lcd = srd.getCell();
    assertNotNull("row#2>column(s) check", lcd);
    checkRowColumn(lcd.get(0), 2, 1, "COL1", "AaA");
    checkRowColumn(lcd.get(1), 2, 2, "COL2", "пПп");
  }
Ejemplo n.º 18
0
  public ContactEdit(Display display, Contact c) {
    this.display = display;
    parentView = display.getCurrent();

    StaticData sd = StaticData.getInstance();
    roster = sd.roster;

    Vector groups = sd.roster.groups.getRosterGroupNames();
    cf = Config.getInstance();

    f = new Form(SR.MS_ADD_CONTACT); // locale

    tJid = new TextField(SR.MS_USER_JID, null, 150, TextField.EMAILADDR);

    tNick = new TextField("Name", null, 32, TextField.ANY); // locale
    tGroup = new TextField(SR.MS_GROUP, null, 32, TextField.ANY); // locale

    tGrpList = new ChoiceGroup(SR.MS_GROUP, ConstMIDP.CHOICE_POPUP);
    tTranspList = new ChoiceGroup(SR.MS_TRANSPORT, ConstMIDP.CHOICE_POPUP);

    tAskSubscrCheckBox = new ChoiceGroup(SR.MS_SUBSCRIPTION, ChoiceGroup.MULTIPLE); // locale
    tAskSubscrCheckBox.append(SR.MS_ASK_SUBSCRIPTION, null); // locale

    tGrpList.addCommand(cmdSet);
    tGrpList.setItemCommandListener(this);

    tTranspList.addCommand(cmdSet);
    tTranspList.setItemCommandListener(this);

    // Transport droplist
    tTranspList.append(sd.account.getServer(), null);
    for (Enumeration e = sd.roster.getHContacts().elements(); e.hasMoreElements(); ) {
      Contact ct = (Contact) e.nextElement();
      Jid transpJid = ct.jid;
      if (transpJid.isTransport()) tTranspList.append(transpJid.getBareJid(), null);
    }
    tTranspList.append(SR.MS_OTHER, null); // locale

    try {
      String jid;
      if (c instanceof MucContact) {
        jid = Jid.toBareJid(((MucContact) c).realJid);
      } else {
        jid = c.getBareJid();
      }
      // edit contact
      tJid.setString(jid);
      tNick.setString(c.nick);

      if (c instanceof MucContact) {
        c = null;
        throw new Exception();
      }

      if (c.getGroupType() != Groups.TYPE_NOT_IN_LIST
          && c.getGroupType() != Groups.TYPE_SEARCH_RESULT) {
        // edit contact
        f.setTitle(jid);
        cmdOk = new Command("Update", Command.OK, 1); // locale
        newContact = false;
      } else c = null; // adding not-in-list
    } catch (Exception e) {
      c = null;
    } // if MucContact does not contains realJid

    int sel = -1;
    ngroups = 0;
    String grpName = "";
    if (c != null) grpName = c.getGroup().name;

    if (groups != null) {
      ngroups = groups.size();
      for (int i = 0; i < ngroups; i++) {
        String gn = (String) groups.elementAt(i);
        tGrpList.append(gn, null);

        if (gn.equals(grpName)) sel = i;
      }
    }

    // if (sel==-1) sel=groups.size()-1;
    if (sel < 0) sel = 0;
    // tGroup.setString(group(sel));

    if (c == null) {
      f.append(tJid);
      f.append(tTranspList);
    }
    updateChoise(tJid.getString(), tTranspList);
    f.append(tNick);

    tGrpList.append(SR.MS_NEWGROUP, null);

    tGrpList.setSelectedIndex(sel, true);

    grpFIndex = f.append(tGrpList);

    if (newContact) {
      f.append(tAskSubscrCheckBox);
      tAskSubscrCheckBox.setSelectedIndex(0, true);
    }

    f.addCommand(cmdOk);
    f.addCommand(cmdCancel);

    f.setCommandListener(this);
    f.setItemStateListener(this);

    display.setCurrent(f);
  }
Ejemplo n.º 19
0
  private void loadData(String filePath, final int[] inFactors, final int[] outFactors)
      throws IOException {
    FactorCollection factorCollection = FactorCollection.instance();
    final String factorDelimiter = StaticData.instance().getFactorDelimiter();

    VERBOSE.v(2, "Loading global lexical model from file " + filePath + "\n");

    // m_inputFactors = new FactorMask(inFactors);
    // m_outputFactors = new FactorMask(outFactors);

    BufferedReader inFile = new BufferedReader(new FileReader(filePath));
    // reading in data one line at a time
    int lineNum = 0;
    String line;
    while ((line = inFile.readLine()) != null) {
      ++lineNum;
      String token[] = Util.tokenize(line, " ");

      if (token.length != 3) // format checking
      {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage
            .append("Syntax error at ")
            .append(filePath)
            .append(":")
            .append(lineNum)
            .append('\n')
            .append(line)
            .append('\n');
        UserMessage.add(errorMessage.toString());
        System.exit(0);
      }

      // create the output word
      Word outWord = new Word();
      String[] factorString = Util.tokenize(token[0], factorDelimiter);
      for (int i = 0; i < outFactors.length; i++) {
        final FactorDirection direction = FactorDirection.Output;
        final int factorType = outFactors[i];
        final Factor factor = factorCollection.addFactor(direction, factorType, factorString[i]);
        outWord.setFactor(factorType, factor);
      }

      // create the input word
      Word inWord = new Word();
      factorString = Util.tokenize(token[1], factorDelimiter);
      for (int i = 0; i < inFactors.length; i++) {
        final FactorDirection direction = FactorDirection.Input;
        final int factorType = inFactors[i];
        final Factor factor = factorCollection.addFactor(direction, factorType, factorString[i]);
        inWord.setFactor(factorType, factor);
      }

      // maximum entropy feature score
      float score = Float.valueOf(token[2]);

      // std::cerr << "storing word " << *outWord << " " << *inWord <<
      // " " << score << endl;

      // store feature in hash
      Map<Word, Float> dh = m_hash.get(outWord);
      if (dh == null) {
        dh = new HashMap<Word, Float>();
        dh.put(inWord, score);
        m_hash.put(outWord, dh);
      } else {
        dh.put(inWord, score);
        outWord = null;
      }
    }
  }
Ejemplo n.º 20
0
  /**
   * Sets some static variables during setup
   *
   * @throws KKException
   */
  public void setStaticVariables() throws KKException {
    KKConfiguration conf;
    StaticData staticData = staticDataHM.get(getStoreId());
    if (staticData == null) {
      staticData = new StaticData();
      staticDataHM.put(getStoreId(), staticData);
    }

    conf = getConfiguration(MODULE_SHIPPING_ITEM_SORT_ORDER);
    if (conf == null) {
      staticData.setSortOrder(0);
    } else {
      staticData.setSortOrder(new Integer(conf.getValue()).intValue());
    }

    conf = getConfiguration(MODULE_SHIPPING_ITEM_TAX_CLASS);
    if (conf == null) {
      staticData.setTaxClass(0);
    } else {
      staticData.setTaxClass(new Integer(conf.getValue()).intValue());
    }

    conf = getConfiguration(MODULE_SHIPPING_ITEM_ZONE);
    if (conf == null) {
      staticData.setZone(0);
    } else {
      staticData.setZone(new Integer(conf.getValue()).intValue());
    }

    conf = getConfiguration(MODULE_SHIPPING_ITEM_COST);
    if (conf == null) {
      staticData.setCost(new BigDecimal(0));
    } else {
      staticData.setCost(new BigDecimal(conf.getValue()));
    }

    conf = getConfiguration(MODULE_SHIPPING_ITEM_HANDLING);
    if (conf == null) {
      staticData.setHandling(new BigDecimal(0));
    } else {
      staticData.setHandling(new BigDecimal(conf.getValue()));
    }
  }
Ejemplo n.º 21
0
 /** < number of options pruned */
 public PartialTranslOptColl() {
   m_bestScore = Float.NEGATIVE_INFINITY;
   m_worstScore = Float.NEGATIVE_INFINITY;
   m_maxSize = StaticData.instance().getMaxNoPartTransOpt();
   m_totalPruned = 0;
 }
/** @author EvgS */
public class ConferenceForm implements CommandListener {

  private Display display;
  private Displayable parentView;

  Command cmdJoin = new Command(SR.MS_JOIN, Command.SCREEN, 1);
  // Command cmdBookmarks=new Command(SR.MS_BOOKMARKS, Command.SCREEN, 2);
  Command cmdAdd = new Command(SR.MS_ADD_BOOKMARK, Command.SCREEN, 5);
  Command cmdCancel = new Command(SR.MS_CANCEL, Command.BACK, 99);

  TextField roomField;
  TextField hostField;
  TextField nickField;
  TextField passField;
  NumberField msgLimitField;

  StaticData sd = StaticData.getInstance();
  /** Creates a new instance of GroupChatForm */
  public ConferenceForm(Display display) {
    String room = Config.getInstance().defGcRoom;
    String server = null;
    // trying to split string like room@server
    int roomE = room.indexOf('@');
    if (roomE > 0) {
      server = room.substring(roomE + 1);
      room = room.substring(0, roomE);
    }
    // default server
    if (server == null) server = "conference." + sd.account.getServer();
    createForm(display, room, server, null, null);
  }
  /** Creates a new instance of GroupChatForm */

  /** Creates a new instance of GroupChatForm */
  public ConferenceForm(Display display, String confJid, String password) {
    int roomEnd = confJid.indexOf('@');
    String room = "";
    if (roomEnd > 0) room = confJid.substring(0, roomEnd);
    String server;
    String nick = null;
    int serverEnd = confJid.indexOf('/');
    if (serverEnd > 0) {
      server = confJid.substring(roomEnd + 1, serverEnd);
      nick = confJid.substring(serverEnd + 1);
    } else {
      server = confJid.substring(roomEnd + 1);
    }
    createForm(display, room, server, nick, password);
  }

  public ConferenceForm(Display display, String room, String server, String nick, String password) {
    createForm(display, room, server, nick, password);
  }

  private void createForm(
      final Display display, String room, String server, String nick, final String password) {
    this.display = display;
    parentView = display.getCurrent();

    Form formJoin = new Form(SR.MS_JOIN_CONFERENCE);

    roomField = new TextField(SR.MS_ROOM, room, 64, ConstMIDP.TEXTFIELD_URL);
    TextFieldCombo.setLowerCaseLatin(roomField);
    formJoin.append(roomField);

    hostField = new TextField(SR.MS_AT_HOST, server, 64, ConstMIDP.TEXTFIELD_URL);
    TextFieldCombo.setLowerCaseLatin(hostField);
    formJoin.append(hostField);

    if (nick == null) nick = sd.account.getNickName();
    nickField = new TextFieldCombo(SR.MS_NICKNAME, nick, 32, TextField.ANY, "roomnick", display);
    formJoin.append(nickField);

    passField =
        new TextField(SR.MS_PASSWORD, password, 32, TextField.ANY | ConstMIDP.TEXTFIELD_SENSITIVE);
    formJoin.append(passField);

    msgLimitField = new NumberField(SR.MS_MSG_LIMIT, 20, 0, 20);
    formJoin.append(msgLimitField);

    formJoin.addCommand(cmdJoin);
    // formJoin.addCommand(cmdBookmarks);
    formJoin.addCommand(cmdAdd);

    formJoin.addCommand(cmdCancel);
    formJoin.setCommandListener(this);
    display.setCurrent(formJoin);
  }

  public void commandAction(Command c, Displayable d) {
    if (c == cmdCancel) {
      destroyView();
    }
    // if (c==cmdBookmarks) { new Bookmarks(display, null); }
    if (c == cmdJoin || c == cmdAdd) {
      String nick = nickField.getString().trim();
      String host = hostField.getString().trim();
      String room = roomField.getString().trim();
      String pass = passField.getString();
      int msgLimit = msgLimitField.getValue();

      if (nick.length() == 0) return;
      if (room.length() == 0) return;
      if (host.length() == 0) return;
      StringBuffer gchat = new StringBuffer(room.trim());
      gchat.append('@');
      gchat.append(host.trim());
      // sd.roster.mucContact(gchat.toString(), Contact.ORIGIN_GROUPCHAT);
      if (c == cmdAdd) new Bookmarks(display, new BookmarkItem(gchat.toString(), nick, pass));
      else {
        try {
          gchat.append('/');
          gchat.append(nick);
          join(gchat.toString(), pass, msgLimit);

          display.setCurrent(sd.roster);
        } catch (Exception e) {
          e.printStackTrace();
          // display.setCurrent(new Alert("Exception", e.toString(), null, AlertType.ERROR),
          // sd.roster);
        }
      }
    }
  }

  public static void join(String name, String pass, int maxStanzas) {
    StaticData sd = StaticData.getInstance();

    ConferenceGroup grp = sd.roster.initMuc(name, pass);
    // требуется для возможности нормального выхода
    // sd.roster.mucContact(name, Contact.ORIGIN_GC_MYSELF);
    // sd.roster.activeRooms.addElement(jid);

    JabberDataBlock x = new JabberDataBlock("x", null, null);
    x.setNameSpace("http://jabber.org/protocol/muc");
    if (pass.length() != 0) {
      // adding password to presence
      x.addChild("password", pass);
    }

    JabberDataBlock history = x.addChild("history", null);
    history.setAttribute("maxstanzas", String.valueOf(maxStanzas));
    history.setAttribute("maxchars", "32768");
    try {
      long last = grp.getConference().lastMessageTime;
      long delay = (grp.conferenceJoinTime - last) / 1000;
      if (last != 0)
        history.setAttribute("seconds", String.valueOf(delay)); // todo: change to since
    } catch (Exception e) {
    }
    ;

    // sd.roster.groups.getGroup(name.substring(0,
    // name.indexOf('@'))).imageExpandedIndex=ImageList.ICON_GCJOIN_INDEX;
    sd.roster.sendPresence(name, null, x);
    sd.roster.reEnumRoster();
  }

  public void destroyView() {
    if (parentView != null) display.setCurrent(parentView);
  }
}
Ejemplo n.º 23
0
  /**
   * Call the TaxCloud tax service which calculates the total tax for the order (including shipping)
   * and populates the Order Total and Order objects with the tax information.
   *
   * @param sd
   * @param order
   * @param ot
   * @throws Exception
   * @throws DataSetException
   * @throws TorqueException
   */
  private void callTaxCloud(StaticData sd, Order order, OrderTotal ot)
      throws TorqueException, DataSetException, Exception {

    // Look up tax rates from TaxCloud
    LookupService lookupService = new LookupService();

    String apiLoginID = sd.getLoginId();
    String apiKey = sd.getLoginKey();
    String customerId = String.valueOf(order.getCustomerId());
    String cartId = order.getLifecycleId();

    // Figure out whether there is a shipping charge
    boolean isShipping = false;
    ShippingQuoteIf shippingQuote = order.getShippingQuote();
    if (shippingQuote != null
        && shippingQuote.getTotalExTax() != null
        && shippingQuote.getTotalExTax().compareTo(new BigDecimal(0)) == 1) {
      isShipping = true;
    }

    /*
     * Create an array of cart items to send to TaxCloud. Every item needs a TIC (Taxability
     * Information Code) which is contained in each order product object in the TaxCode
     * attribute. If we need to calculate tax for shipping we make the CartItem array longer by
     * one.
     */
    int arrayLength =
        (isShipping) ? order.getOrderProducts().length + 1 : order.getOrderProducts().length;
    CartItem[] cartItems = new CartItem[arrayLength];
    int cartIndex = 0;
    for (int i = 0; i < order.getOrderProducts().length; i++) {
      OrderProductIf orderProduct = order.getOrderProducts()[i];
      CartItem cartItem = new CartItem();
      cartItem.setIndex(cartIndex);
      cartItem.setItemID(String.valueOf(orderProduct.getProductId()));
      if (orderProduct.getTaxCode() == null || orderProduct.getTaxCode().length() == 0) {
        throw new KKException(
            "The TaxClass object for the product with id = "
                + orderProduct.getProductId()
                + " does not have a TIC (Taxability Information Code) set.");
      }
      int ticID;
      try {
        ticID = Integer.parseInt(orderProduct.getTaxCode());
      } catch (Exception e) {
        throw new KKException(
            "The TaxClass object for the product with id = "
                + orderProduct.getProductId()
                + " does not have a numeric TIC (Taxability Information Code) set. The value found = "
                + orderProduct.getTaxCode()
                + " is invalid.");
      }
      cartItem.setTIC(ticID);

      // Must call TaxCloud with final price of a single product
      int scale = getTaxMgr().getTaxScale();
      BigDecimal singleProdPrice =
          (orderProduct.getFinalPriceExTax())
              .divide(new BigDecimal(orderProduct.getQuantity()), scale, BigDecimal.ROUND_HALF_UP);
      cartItem.setPrice(singleProdPrice.floatValue());
      cartItem.setQty(orderProduct.getQuantity());
      cartItems[cartIndex] = cartItem;
      cartIndex++;
    }

    if (isShipping) {
      // Add shipping charges to the cart (shipping charges are taxable)
      CartItem cartItem = new CartItem();
      cartItem.setIndex(cartIndex);
      cartItem.setItemID(SHIPPING_TIC_STR);
      cartItem.setTIC(SHIPPING_TIC);
      cartItem.setPrice(shippingQuote.getTotalExTax().floatValue());
      cartItem.setQty(1);
      cartItems[cartIndex] = cartItem;
    }

    net.taxcloud.Address destination = new net.taxcloud.Address();
    destination.setAddress1(order.getDeliveryStreetAddress());
    destination.setAddress2("");
    destination.setCity(order.getDeliveryCity());
    destination.setState(order.getDeliveryState());
    destination.setZip5(order.getDeliveryPostcode());
    net.taxcloud.Address destinationVerified = verifyAddress(sd, destination);
    if (destinationVerified == null) {
      throw new KKException(
          "The destination address could not be verified using the USPS verification service probably due to a communications problem.");
    }
    validateAddress(destination, destinationVerified);

    // Now set the verified address back into the Order
    order.setDeliveryStreetAddress(destinationVerified.getAddress1());
    order.setDeliveryCity(destinationVerified.getCity());
    order.setDeliveryState(destinationVerified.getState());
    order.setDeliveryPostcode(destinationVerified.getZip5() + "-" + destinationVerified.getZip4());

    boolean deliveredBySeller = true;
    ExemptionCertificate exemptionCertificate = null;

    CartItemResponse[] cartItemsResponse = null;
    try {
      if (log.isDebugEnabled()) {
        StringBuffer sb = new StringBuffer();
        sb.append("Calling tax cloud tax service with the following data:\n");
        sb.append("apiLoginID =  ").append(apiLoginID).append("\n");
        sb.append("apiKey =      ").append(apiKey).append("\n");
        sb.append("customerId =  ").append(customerId).append("\n");
        sb.append("cartId =      ").append(cartId).append("\n");
        sb.append("Store Address:\n");
        sb.append("Address1 =    ").append(sd.getOriginAddr().getAddress1()).append("\n");
        sb.append("Address2 =    ").append(sd.getOriginAddr().getAddress2()).append("\n");
        sb.append("City =        ").append(sd.getOriginAddr().getCity()).append("\n");
        sb.append("State =       ").append(sd.getOriginAddr().getState()).append("\n");
        sb.append("Zip4 =        ").append(sd.getOriginAddr().getZip4()).append("\n");
        sb.append("Zip5 =        ").append(sd.getOriginAddr().getZip5()).append("\n");
        sb.append("Delivery Address:\n");
        sb.append("Address1 =    ").append(destinationVerified.getAddress1()).append("\n");
        sb.append("Address2 =    ").append(destinationVerified.getAddress2()).append("\n");
        sb.append("City =        ").append(destinationVerified.getCity()).append("\n");
        sb.append("State =       ").append(destinationVerified.getState()).append("\n");
        sb.append("Zip4 =        ").append(destinationVerified.getZip4()).append("\n");
        sb.append("Zip5 =        ").append(destinationVerified.getZip5()).append("\n");
        sb.append("CartItems:\n");
        for (int i = 0; i < cartItems.length; i++) {
          CartItem item = cartItems[i];
          sb.append("ItemID =        ").append(item.getItemID()).append("\n");
          sb.append("TIC =           ").append(item.getTIC()).append("\n");
          sb.append("Qty =           ").append(item.getQty()).append("\n");
          sb.append("Price =         ").append(item.getPrice()).append("\n");
        }
        log.debug(sb);
      }
      // Call TaxCloud to look up tax rates
      cartItemsResponse =
          lookupService.lookup(
              apiLoginID,
              apiKey,
              customerId,
              cartId,
              cartItems,
              sd.getOriginAddr(),
              destinationVerified,
              deliveredBySeller,
              exemptionCertificate);
    } catch (Exception e) {
      log.error("Problem calling TaxCloud: ", e);
    }
    if (cartItemsResponse == null || cartItemsResponse.length == 0) {
      throw new KKException(
          "TaxCloud returned an empty response from the lookupService.lookup() API call.");
    }

    if (log.isDebugEnabled()) {
      log.debug("Response from TaxCloud lookup:");
      for (int i = 0; i < cartItemsResponse.length; i++) {
        CartItemResponse r = cartItemsResponse[i];
        log.debug("CartItem [index=" + r.getCartItemIndex() + ", tax=" + r.getTaxAmount() + "]");
      }
    }

    float taxAmount = 0;
    for (int i = 0; i < cartItemsResponse.length - 1; i++) {
      CartItemResponse cartItemResponse = cartItemsResponse[i];
      taxAmount = taxAmount + cartItemResponse.getTaxAmount();
    }

    // Now get the tax amount for the shipping charges
    CartItemResponse cartItemResponse = cartItemsResponse[cartItemsResponse.length - 1];
    taxAmount = taxAmount + cartItemResponse.getTaxAmount();

    // Set the Order Total with the total tax amount
    BigDecimal taxAmountBD = new BigDecimal(taxAmount);
    ot.setValue(taxAmountBD);
    ot.setText(getCurrMgr().formatPrice(taxAmountBD, order.getCurrencyCode()));

    // Set the order with tax information
    order.setTax(taxAmountBD);
    order.setTotalIncTax(order.getTotalExTax().add(taxAmountBD));
  }
Ejemplo n.º 24
0
  /**
   * Sets some static variables during setup
   *
   * @throws KKException
   */
  public void setStaticVariables() throws KKException {
    KKConfiguration conf;
    StaticData staticData = staticDataHM.get(getStoreId());
    if (staticData == null) {
      staticData = new StaticData();
      staticDataHM.put(getStoreId(), staticData);
    }

    conf = getConfiguration(MODULE_ORDER_TOTAL_TAX_CLOUD_SORT_ORDER);
    if (conf == null) {
      staticData.setSortOrder(0);
    } else {
      staticData.setSortOrder(new Integer(conf.getValue()).intValue());
    }

    staticData.setLoginId(getConfigurationValue(MODULE_ORDER_TOTAL_TAX_CLOUD_API_LOGIN_ID));
    staticData.setLoginKey(getConfigurationValue(MODULE_ORDER_TOTAL_TAX_CLOUD_API_LOGIN_KEY));
    staticData.setAddress1(getConfigurationValue(MODULE_ORDER_TOTAL_TAX_CLOUD_STORE_ADDRESS1));
    staticData.setAddress2(getConfigurationValue(MODULE_ORDER_TOTAL_TAX_CLOUD_STORE_ADDRESS2));
    staticData.setCity(getConfigurationValue(MODULE_ORDER_TOTAL_TAX_CLOUD_STORE_CITY));
    staticData.setState(getConfigurationValue(MODULE_ORDER_TOTAL_TAX_CLOUD_STORE_STATE));
    staticData.setZip(getConfigurationValue(MODULE_ORDER_TOTAL_TAX_CLOUD_STORE_ZIP));
    staticData.setUspsId(getConfigurationValue(MODULE_ORDER_TOTAL_TAX_CLOUD_USPS_USER_ID));

    // Verify and cache the origin address
    net.taxcloud.Address origin = new net.taxcloud.Address();
    origin.setAddress1(staticData.getAddress1());
    origin.setAddress2(staticData.getAddress2());
    origin.setCity(staticData.getCity());
    origin.setState(staticData.getState());
    origin.setZip5(staticData.getZip());
    net.taxcloud.Address originVerified = verifyAddress(staticData, origin);
    if (originVerified == null) {
      throw new KKException(
          "The store address for store "
              + getStoreId()
              + " could not be verified using the USPS verification service probably due to a communications problem.");
    }
    validateAddress(origin, originVerified);
    staticData.setOriginAddr(originVerified);
  }