private void saveCurrent() {
    PrintWriter writer = null;

    try {
      writer = new PrintWriter("config.txt", "UTF-8");
      writer.println("PhoneNumbers:");

      for (String s : Main.getEmails()) {
        writer.println(s);
      }

      writer.println("Items:");

      for (Item s : Main.getItems()) {
        writer.println(s.getName() + "," + s.getWebsite());
      }

      results.setText("Current settings have been saved sucessfully.");
    } catch (FileNotFoundException e1) {
      e1.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }

    writer.close();
  }
Beispiel #2
0
  /** 解析数据行 */
  private static boolean parserDate(String line) {
    if (line == null) {
      return true;
    }
    Item item = new Item();
    Attribute attr = null;
    int index = 0;
    int si;
    String data;
    int nData;
    /*
     * 根据解析出来的属性的个数和类别,解析数据。
     */
    for (AttributeClass ac : arff.aclasses) {
      si = index;
      while (index < line.length() && line.charAt(index) != ',') ++index;

      data = line.substring(si, index);

      if (ac.type == AttributeType.NUME) {
        nData = Integer.valueOf(data);
        attr = new Attribute(ac, nData);
      } else {
        attr = new Attribute(ac, ac.getCateIndex(data));
      }

      item.addAttr(attr);
      ++index;
    }

    arff.addItem(item);
    return true;
  }
  private String buildInvoice() {
    double taxRate = 6;
    String message;

    this.grandTotal = ((taxRate / 100) * this.subtotal) + this.subtotal;

    DateFormat dateFormat = new SimpleDateFormat("dd/MM/YY HH:mm:ss z");
    this.transDate = new Date();

    message = "Date: " + dateFormat.format(this.transDate) + "\n\n";
    message += "Number of line items: " + this.totalItems + "\n\n";
    message += "Item# / ID / Title / Price / Qty / Disc % / Subtotal:\n\n";
    int counter = 0;
    for (Item i : order.getOrder()) {
      counter++;
      message += counter + ". " + i.toString() + "\n";
    }
    message += "\n";
    message += "Order subtotal: " + formatter.format(this.subtotal) + "\n\n";
    message += "Tax rate: " + taxRate + "%\n\n";
    message += "Tax amount: " + formatter.format(((taxRate / 100) * this.subtotal)) + "\n\n";
    message += "Order total: " + formatter.format(this.grandTotal) + "\n\n";
    message += "Thanks for shopping at Funky Town Books\n\n";

    return message;
  }
 public String getRate(String nId) {
   Item item = this.rateItems.get(nId);
   if (item == null) {
     logger.debug("No Item found : " + nId);
     return null;
   }
   return item.getRate();
 }
  /**
   * update is an overwritten method of Observer, used in reaction to a change happening in an
   * observed class. In this case it updates the instance variable HashMap itemMap, removing
   * references to the Item at the old location, and adding it's reference to the new location. It
   * also updates the locations that the Player has visited, adding the most recent Location first
   * in the linked list. Note: more objects than Items and Player could be added later
   *
   * @param o : an Observable object (which should be an GameObject object of some sort)
   * @param arg : an Object (which should be a Location object)
   */
  public void update(Observable o, Object arg) {
    /** Item update code* */
    if (o instanceof Item && arg instanceof Integer) {
      Item item = (Item) o;
      int oldLocation = (Integer) arg;
      int newLocation = item.getObjectLocation();

      // remove old item from array list
      ArrayList<Item> newList = itemMap.get((Integer) oldLocation);

      if (newList != null) {
        // For loop while there is another element
        for (Iterator<Item> it = newList.iterator(); it.hasNext(); ) {
          if (item.getObjectID() == it.next().getObjectID()) {
            it.remove();
          }
          // End if matching id
        }
        // End for loop

        // Update the item map with the new status with the item removed
        itemMap.put((Integer) oldLocation, newList);
      }
      // if list not null

      // If not 'destroyed', which is sent to location 9999
      if (!(newLocation == 9999)) {
        // add the item to the new location's array list
        if (!(itemMap.containsKey((Integer) newLocation))) {
          newList = new ArrayList<Item>();
          newList.add(item);
          itemMap.put((Integer) newLocation, newList);
        } else {
          newList = itemMap.get((Integer) newLocation);
          // not checking for duplicates yet, add the item to the list
          newList.add(item);
          // Update the item map with the new status
          itemMap.put((Integer) newLocation, newList);
        }
        // End contains key
      }
      // End if not destroyed
    }
    // End if valid instances of Item and Integer

    /** Player update code* */
    if (o instanceof Player && arg instanceof Integer) {
      Player player = (Player) o;
      int location = player.getObjectLocation();

      // Add new locations the player visits Last in the linked list,
      // which makes last element always the current
      playerList.addLast(location);
    }
    // End if valid instances of Player and Integer
  }
Beispiel #6
0
    public void sendItems(Master m) {
      for (int i = 0; i < waitingForSending.size(); ++i) {
        Item newItem = new Item();

        newItem.fullCopy((Item) waitingForSending.get(i));

        m.inTransit.add(newItem);
        transitSentEntry("log_" + name + ".txt");
      }
      waitingForSending.clear();
    }
 public void add(String line) {
   String[] fields = line.split("\\t");
   if (fields.length != 2) {
     logger.error("wrong format : " + line);
     return;
   }
   Item item = new Item();
   item.setNaverId(fields[0]);
   item.setRate(fields[1]);
   this.rateItems.put(fields[0], item);
 }
Beispiel #8
0
 public void Update(Item item) {
   int i, sta = 0;
   for (i = 0; i < list.size(); i++)
     if (list.get(i).getNumber() == item.getNumber()) {
       sta = 1;
       break;
     }
   if (sta == 0) System.out.println("仓库中没有此编号商品");
   else {
     list.get(i).setStock(item.getStock());
     System.out.println("已更新仓库");
   }
 }
Beispiel #9
0
 public void deliverTransitItems() {
   for (int i = 0; i < inTransit.size(); ) {
     if (((Item) inTransit.get(i)).daysInTransit > ((Item) inTransit.get(i)).delivaryTime) {
       transitArrivedEntry("log_" + ((Item) inTransit.get(i)).toOffice + ".txt");
       int dstOfficeIndex = getOfficeIndex(((Item) inTransit.get(i)).toOffice);
       if (((Office) offices.get(dstOfficeIndex)).currentItems.size()
           < ((Office) offices.get(dstOfficeIndex)).maxCap) {
         if (((Item) inTransit.get(i)).type.equals("letter") == true) {
           Item newItem = new Item();
           newItem.fullCopy((Item) inTransit.get(i));
           newItem.daysInTransit = 0;
           newItem.daysSinceArraival = 0;
           newItem.delivaryTime = ((Office) offices.get(dstOfficeIndex)).transitTime;
           ((Office) offices.get(dstOfficeIndex)).currentItems.add(newItem);
           inTransit.remove(i);
         } else if (((Item) inTransit.get(i)).length
             <= ((Office) offices.get(dstOfficeIndex)).maxPackageSize) {
           Item newItem = new Item();
           newItem.fullCopy((Item) inTransit.get(i));
           newItem.daysInTransit = 0;
           newItem.daysSinceArraival = 0;
           newItem.delivaryTime = ((Office) offices.get(dstOfficeIndex)).transitTime;
           ((Office) offices.get(dstOfficeIndex)).currentItems.add(newItem);
           inTransit.remove(i);
         } else {
           destroyedPackageEntry(
               "log_" + ((Office) offices.get(dstOfficeIndex)).name + ".txt",
               ((Office) offices.get(dstOfficeIndex)).name);
           destroyedPackageEntry("log_master.txt", ((Office) offices.get(dstOfficeIndex)).name);
           inTransit.remove(i);
         }
       } else if (((Item) inTransit.get(i)).type.equals("letter") == true) {
         destroyedLetterEntry(
             "log_" + ((Office) offices.get(dstOfficeIndex)).name + ".txt",
             ((Office) offices.get(dstOfficeIndex)).name);
         destroyedLetterEntry("log_master.txt", ((Office) offices.get(dstOfficeIndex)).name);
         inTransit.remove(i);
       } else {
         destroyedPackageEntry(
             "log_" + ((Office) offices.get(dstOfficeIndex)).name + ".txt",
             ((Office) offices.get(dstOfficeIndex)).name);
         destroyedPackageEntry("log_master.txt", ((Office) offices.get(dstOfficeIndex)).name);
         inTransit.remove(i);
       }
       i = 0;
     } else {
       ++i;
     }
   }
 }
Beispiel #10
0
  /**
   * Compares results.
   *
   * @param expected expected result
   * @param returned returned result
   * @throws Exception exception
   */
  private static void compare(final ItemList expected, final ItemList returned) throws Exception {

    // Compare response with expected result
    assertEquals("Different number of results", expected.size(), returned.size());

    final long es = expected.size();
    for (int e = 0; e < es; e++) {
      final Item exp = expected.get(e), ret = returned.get(e);
      if (!new DeepEqual().equal(exp, ret)) {
        final TokenBuilder tb = new TokenBuilder("Result ").addLong(e).add(" differs:\nReturned: ");
        tb.addExt(ret.serialize()).add("\nExpected: ").addExt(exp.serialize());
        fail(tb.toString());
      }
    }
  }
  public void viewOrder() {
    String currentOrder = "";
    int counter = 0;
    for (Item i : order.getOrder()) {
      counter++;
      currentOrder += counter + ". " + i.toString() + "\n";
    }
    Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setTitle("Current Order");
    alert.setHeaderText("Your current order is as follows:");
    alert.setContentText(currentOrder);
    alert.getDialogPane().setStyle(" -fx-max-width:500px; -fx-pref-width: 500px;");

    alert.showAndWait();
  }
Beispiel #12
0
  public static void main(String[] args) throws Exception {
    for (int i = 0; i < 20; i++) {
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      ObjectOutputStream oout = new ObjectOutputStream(bout);
      Item item = new Item();
      oout.writeObject(item);
      oout.close();

      ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
      Item itemcopy = (Item) oin.readObject();

      if (!item.equals(itemcopy)) {
        throw new Error();
      }
    }
  }
 public void processItem() {
   createItem();
   if (item != null) {
     text_info.setText(item.toString());
     btn_confirm.setDisable(false);
   }
 }
  public void confirmItem() {
    this.subtotal += item.getTotal();
    String subtotalStr = formatter.format(this.subtotal);
    text_bookID.setText("");
    text_quantity.setText("");
    text_subtotal.setText(subtotalStr);

    confirmAlert();

    order.addItem(item);
    this.totalQuantity += item.getQuantity();
    changeItemNumber();
    btn_confirm.setDisable(true);
    btn_view.setDisable(false);
    text_totalItems.setDisable(true);
    item = null;
  }
Beispiel #15
0
  /**
   * Creates annotation child elements.
   *
   * @param anns annotations
   * @param parent parent element
   * @param uri include uri
   * @throws QueryException query exception
   */
  final void annotation(final AnnList anns, final FElem parent, final boolean uri)
      throws QueryException {

    for (final Ann ann : anns) {
      final FElem annotation = elem("annotation", parent);
      if (ann.sig != null) {
        annotation.add("name", ann.sig.id());
        if (uri) annotation.add("uri", ann.sig.uri);
      } else {
        annotation.add("name", ann.name.string());
        if (uri) annotation.add("uri", ann.name.uri());
      }

      for (final Item it : ann.args) {
        final FElem literal = elem("literal", annotation);
        literal.add("type", it.type.toString()).add(it.string(null));
      }
    }
  }
Beispiel #16
0
    public void commandLETTER(
        String srcPostOffice,
        String pickUpPerson,
        String dstPostOffice,
        String returnPerson,
        int systemTime) {
      int srcOfficeIndex = getOfficeIndex(srcPostOffice);
      if (srcOfficeIndex != -1) {
        newLetterEntry("log_" + srcPostOffice + ".txt", srcPostOffice, dstPostOffice);
        int dstOfficeIndex = getOfficeIndex(dstPostOffice);
        if (dstOfficeIndex != -1) {
          if (isNewCriminal(newCriminals, pickUpPerson) == false
              && isOldCriminal("wanted.txt", pickUpPerson) == false) {
            if (((Office) offices.get(srcOfficeIndex)).currentItems.size()
                < ((Office) offices.get(srcOfficeIndex)).maxCap) {
              Item newItem = new Item();
              newItem.fromOffice = new String(srcPostOffice);
              newItem.recipent = new String(pickUpPerson);
              newItem.toOffice = new String(dstPostOffice);
              if (returnPerson.equals("NONE")) {
                newItem.returnRecipent = "";
              } else {
                newItem.returnRecipent = new String(returnPerson);
              }
              newItem.dayGotInSystem = systemTime;
              newItem.type = new String("letter");
              newItem.delivaryTime = ((Office) offices.get(srcOfficeIndex)).transitTime;
              ((Office) offices.get(srcOfficeIndex)).waitingForSending.add(newItem);
              acceptedLetterEntry("log_" + srcPostOffice + ".txt", dstPostOffice);
            } else {
              rejectedLetterEntry("log_" + srcPostOffice + ".txt", srcPostOffice);
              rejectedLetterEntry("log_master.txt", srcPostOffice);
            }
          } else {
            rejectedLetterEntry("log_" + srcPostOffice + ".txt", srcPostOffice);
            rejectedLetterEntry("log_master.txt", srcPostOffice);
          }

        } else {
          rejectedLetterEntry("log_" + srcPostOffice + ".txt", srcPostOffice);
          rejectedLetterEntry("log_master.txt", srcPostOffice);
        }
      }
    }
  public void buyItemFromUser(User buyer, User seller, Item currentItem)
        // PRE:  buyer, seller, currentItem must be initialized
        // POST: Purchases item from the store and has stores it into inventory.
      {

    int buyer_balance; // The new balance of the buyer
    int seller_balance; // The new balance of the seller
    String str; // First query
    String str2; // Second query
    String str3; // Third query

    buyer_balance = buyer.getBalance() - currentItem.getPrice();
    seller_balance = seller.getBalance() + currentItem.getPrice();

    if (buyer_balance > 0) // If the buyer wont go negative
    {
      str =
          String.format(
              "Update users set balance = (%d) where user_name = '%s'",
              buyer_balance, buyer.getUserName());

      str2 =
          String.format(
              "Update users set balance = (%d) where user_name = '%s'",
              seller_balance, seller.getUserName());

      str3 =
          String.format(
              "Update items set owner_id = (%d) where item_name = '%s'",
              buyer.getUserId(), currentItem.getItemName());

      updateTables(str, str2, str3);

    } else {
      // Prompt the user with an error
      JOptionPane.showMessageDialog(
          null, "You will go bankrupt if you try buying that, try selling some items.");
    }
  }
Beispiel #18
0
  @Override
  public B64 item(final QueryContext qc, final InputInfo ii) throws QueryException {
    checkCreate(qc);

    final IOFile root = new IOFile(toPath(0, qc).toString());
    final ArchOptions opts = toOptions(1, Q_OPTIONS, new ArchOptions(), qc);
    final Iter entries;
    if (exprs.length > 2) {
      entries = qc.iter(exprs[2]);
    } else {
      final TokenList tl = new TokenList();
      for (final String file : root.descendants()) tl.add(file);
      entries = StrSeq.get(tl).iter();
    }

    final String format = opts.get(ArchOptions.FORMAT);
    final int level = level(opts);
    if (!root.isDir()) throw FILE_NO_DIR_X.get(info, root);

    try (final ArchiveOut out = ArchiveOut.get(format.toLowerCase(Locale.ENGLISH), info)) {
      out.level(level);
      try {
        while (true) {
          Item en = entries.next();
          if (en == null) break;
          en = checkElemToken(en);
          final IOFile file = new IOFile(root, string(en.string(info)));
          if (!file.exists()) throw FILE_NOT_FOUND_X.get(info, file);
          if (file.isDir()) throw FILE_IS_DIR_X.get(info, file);
          add(en, new B64(file.read()), out, level, qc);
        }
      } catch (final IOException ex) {
        throw ARCH_FAIL_X.get(info, ex);
      }
      return new B64(out.finish());
    }
  }
  private void displayInformation() {
    results.setText("-Cell Phones-\n");
    if (Main.getEmails().isEmpty()) {
      results.append("\nNo Numbers");
    } else {
      ArrayList<String> emails = Main.getEmails();
      int index = 0;

      for (String s : emails) {
        index++;
        results.append("\n(" + index + ")   " + s);
      }
    }

    results.append("\n\n-Current Items-");
    if (Main.getItems().isEmpty()) {
      results.append("\n\nNo Items");
    } else {
      ArrayList<Item> items = Main.getItems();
      int index = 0;

      for (Item i : items) {
        String s = i.getWebsite().substring(46, i.getWebsite().length());

        index++;

        for (int j = 0; j < s.length(); j++) {
          if (s.substring(j, j + 1).equals("&")) {
            s = s.substring(0, j);
          }
        }

        results.append("\n\n(" + index + ")\nName: \t" + i.getName() + "\nItem: \t" + s);
      }
      results.append("\n\n");
    }
  }
Beispiel #20
0
 public void Add(Item item) {
   int sta = 0;
   for (int i = 0; i < list.size(); i++)
     if (list.get(i).getNumber() == item.getNumber()) {
       sta = 1;
       break;
     }
   if (sta == 1)
     // 如果已经存在,打印通知
     System.out.println("仓库中已有该商品,请用Update更新");
   else {
     // 如果没有,直接加入
     list.add(item);
     System.out.println("已添加到仓库中");
   }
 }
  private String buildTransaction() {
    String transaction = "";
    DateFormat dateFormat;

    for (Item i : order.getOrder()) {
      dateFormat = new SimpleDateFormat("YYMMddHHmmss");
      transaction += dateFormat.format(this.transDate) + ", ";
      transaction +=
          i.getBook().getId() + ", " + i.getBook().getTitle() + ", " + i.getBook().getPriceStr();
      transaction +=
          ", " + i.getQuantity() + ", " + i.getPercentStr() + ", " + i.getTotalStr() + ", ";
      dateFormat = new SimpleDateFormat("dd/MM/YY HH:mm:ss z");
      transaction += dateFormat.format(this.transDate) + newLine;
    }
    return transaction;
  }
Beispiel #22
0
  /**
   * Adds the specified entry to the output stream.
   *
   * @param entry entry descriptor
   * @param con contents
   * @param out output archive
   * @param level default compression level
   * @throws QueryException query exception
   * @throws IOException I/O exception
   */
  private void add(final Item entry, final Item con, final ArchiveOut out, final int level)
      throws QueryException, IOException {

    // create new zip entry
    final String name = string(entry.string(info));
    if (name.isEmpty()) ARCH_EMPTY.thrw(info);
    final ZipEntry ze = new ZipEntry(name);
    String en = null;

    // compression level
    byte[] lvl = null;
    if (entry instanceof ANode) {
      final ANode el = (ANode) entry;
      lvl = el.attribute(Q_LEVEL);

      // last modified
      final byte[] mod = el.attribute(Q_LAST_MOD);
      if (mod != null) {
        try {
          ze.setTime(new Int(new Dtm(mod, info)).itr());
        } catch (final QueryException qe) {
          ARCH_DATETIME.thrw(info, mod);
        }
      }

      // encoding
      final byte[] enc = el.attribute(Q_ENCODING);
      if (enc != null) {
        en = string(enc);
        if (!Charset.isSupported(en)) ARCH_ENCODING.thrw(info, enc);
      }
    }

    // data to be compressed
    byte[] val = checkStrBin(con);
    if (con instanceof AStr && en != null && en != Token.UTF8) val = encode(val, en);

    try {
      out.level(lvl == null ? level : toInt(lvl));
    } catch (final IllegalArgumentException ex) {
      ARCH_LEVEL.thrw(info, lvl);
    }
    out.write(ze, val);
  }
Beispiel #23
0
  /**
   * Get an item to put in the database
   *
   * @param id for the item
   * @param warehouse for the item
   * @return item
   */
  public Item getItem(int id, Warehouse warehouse) {
    Item item = new Item();

    int itemIndex = randInt(0, inventory.size()); // choose an inventory item from list

    item.setItemID(id);
    item.setWarehouseID(warehouse.getWarehouseID());
    item.setName(inventory.get(itemIndex) + id);
    item.setPrice(new BigDecimal((double) randInt(0, 20) + randDouble()));
    item.setCurrentStock(randInt(50, 150)); // random number of stock listings per item, avg of 100

    return item;
  }
Beispiel #24
0
  /**
   * Get a line item to put in the database
   *
   * @param id for the line item
   * @param warehouse for the station
   * @param Station station
   * @param Customer customer
   * @param Order order
   * @param ArrayList<Item> itemList
   * @return lineItem
   */
  public LineItem getLineItem(
      int id,
      Warehouse warehouse,
      Station station,
      Customer customer,
      Order order,
      ArrayList<Item> itemList) {
    LineItem lineItem = new LineItem();

    Item item = itemList.get(randInt(0, itemList.size()));

    int numOrdered = randInt(1, 5);

    if (item.getCurrentStock() < numOrdered) return null;

    lineItem.setLineItemID(id);
    lineItem.setOrderID(order.getOrderID());
    lineItem.setItemID(item.getItemID());
    lineItem.setCustomerID(customer.getCustomerID());
    lineItem.setWarehouseID(warehouse.getWarehouseID());
    lineItem.setStationID(station.getStationID());
    lineItem.setNumOrdered(numOrdered);
    lineItem.setAmountDue(item.getPrice().multiply(new BigDecimal(lineItem.getNumOrdered())));
    lineItem.setAmountDue(
        lineItem.getAmountDue().add(station.getSalesTax().multiply(lineItem.getAmountDue())));
    lineItem.setAmountDue(
        lineItem.getAmountDue().subtract(customer.getDiscount().multiply(lineItem.getAmountDue())));
    lineItem.setDateDelivered(randDate());

    item.setNumLineItems(item.getNumLineItems() + 1);
    item.setNumSold(item.getNumSold() + lineItem.getNumOrdered());
    // item.setCurrentStock(item.getCurrentStock() - lineItem.getNumOrdered()); don't modify stock
    // counts for random generation

    customer.setTotalPaid(customer.getTotalPaid().add(lineItem.getAmountDue()));
    station.setTotalSales(station.getTotalSales().add(lineItem.getAmountDue()));
    warehouse.setTotalSales(warehouse.getTotalSales().add(lineItem.getAmountDue()));

    return lineItem;
  }
Beispiel #25
0
 // 读写的方法
 public void Save() {
   try {
     file.delete();
     FileWriter writer = new FileWriter(file);
     for (Item i : list)
       writer.write(
           i.getNumber()
               + ";"
               + i.getCategory()
               + ";"
               + i.getName()
               + ";"
               + i.getModel()
               + ";"
               + i.getStock()
               + "\n");
     writer.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Beispiel #26
0
 public void show() {
   Collections.sort(
       list,
       new Comparator<Item>() {
         public int compare(Item i1, Item i2) {
           if (i1.getNumber() > i2.getNumber()) return 1;
           else return -1;
         }
       });
   for (Item i : list)
     System.out.println(
         i.getNumber()
             + ";"
             + i.getCategory()
             + ";"
             + i.getName()
             + ";"
             + i.getModel()
             + ";"
             + i.getStock());
 }
Beispiel #27
0
 private void parseMobFile(String strStore, RandomAccessFile rafFile) {
   try {
     if (strStore.equalsIgnoreCase("skill")) {
       strStore = rafFile.readLine();
       int value = Byte.parseByte(rafFile.readLine());
       addToSkill(strStore, value);
       engGame.log.printMessage(Log.DEBUG, strStore + "=" + value);
       return;
     }
     if (strStore.equalsIgnoreCase("condition")) {
       Condition cndStore = engGame.getCondition(rafFile.readLine());
       cndStore.intTicksPast = Integer.parseInt(rafFile.readLine());
       cndStore.intDuration = Integer.parseInt(rafFile.readLine());
       addCondition(cndStore);
       engGame.log.printMessage(Log.DEBUG, "condition \"" + cndStore.strName + "\"");
       return;
     }
     if (strStore.equalsIgnoreCase("giveitem")) {
       String strItem = rafFile.readLine();
       double dblChance = Double.valueOf(rafFile.readLine()).doubleValue();
       vctGiveItems.addElement(new GiveItem(strItem, dblChance));
       engGame.log.printMessage(
           Log.DEBUG,
           strName + " gives a \"" + strItem + "\" " + (100 * dblChance) + "% of the time.");
       return;
     }
     if (strStore.equalsIgnoreCase("item")) {
       Item itmStore = engGame.getItem(rafFile.readLine());
       if (itmStore != null) {
         itmStore.lngDurability = Long.parseLong(rafFile.readLine());
         itmStore.intUses = Integer.parseInt(rafFile.readLine());
         vctItems.addElement(itmStore);
       }
       return;
     }
     if (strStore.equalsIgnoreCase("clan")) {
       strClan = rafFile.readLine();
       return;
     }
     if (strStore.equalsIgnoreCase("race")) {
       strRace = rafFile.readLine();
       return;
     }
     if (strStore.equalsIgnoreCase("title")) {
       strTitle = rafFile.readLine();
       return;
     }
     if (strStore.equalsIgnoreCase("description")) {
       strDescription = rafFile.readLine();
       return;
     }
     if (strStore.equalsIgnoreCase("x")) {
       intLocX = Integer.parseInt(rafFile.readLine());
       return;
     }
     if (strStore.equalsIgnoreCase("y")) {
       intLocY = Integer.parseInt(rafFile.readLine());
       return;
     }
     if (strStore.equalsIgnoreCase("maxhp")) {
       maxhp = Integer.parseInt(rafFile.readLine());
       return;
     }
     if (strStore.equalsIgnoreCase("maxmp")) {
       maxmp = Integer.parseInt(rafFile.readLine());
       return;
     }
     if (strStore.equalsIgnoreCase("stre")) {
       stre = Integer.parseInt(rafFile.readLine());
       return;
     }
     if (strStore.equalsIgnoreCase("inte")) {
       inte = Integer.parseInt(rafFile.readLine());
       return;
     }
     if (strStore.equalsIgnoreCase("dext")) {
       dext = Integer.parseInt(rafFile.readLine());
       return;
     }
     if (strStore.equals("cons")) {
       cons = Integer.parseInt(rafFile.readLine());
       return;
     }
     if (strStore.equalsIgnoreCase("wisd")) {
       wisd = Integer.parseInt(rafFile.readLine());
       return;
     }
     if (strStore.equalsIgnoreCase("image")) {
       intImage = Integer.parseInt(rafFile.readLine());
       return;
     }
     if (strStore.equalsIgnoreCase("bravery")) {
       dblBravery = Double.valueOf(rafFile.readLine()).doubleValue();
       return;
     }
     if (strStore.equalsIgnoreCase("grouprelation")) {
       dblGroupRelation = Double.valueOf(rafFile.readLine()).doubleValue();
       return;
     }
     if (strStore.equalsIgnoreCase("wield")) {
       equWorn.wield = engGame.getItem(rafFile.readLine());
       if (equWorn.wield != null) {
         equWorn.wield.lngDurability = Long.parseLong(rafFile.readLine());
         equWorn.wield.intUses = Integer.parseInt(rafFile.readLine());
       }
       runWearScript(equWorn.wield);
       return;
     }
     if (strStore.equalsIgnoreCase("arms")) {
       equWorn.arms = engGame.getItem(rafFile.readLine());
       if (equWorn.arms != null) {
         equWorn.arms.lngDurability = Long.parseLong(rafFile.readLine());
         equWorn.arms.intUses = Integer.parseInt(rafFile.readLine());
       }
       runWearScript(equWorn.arms);
       return;
     }
     if (strStore.equalsIgnoreCase("legs")) {
       equWorn.legs = engGame.getItem(rafFile.readLine());
       if (equWorn.legs != null) {
         equWorn.legs.lngDurability = Long.parseLong(rafFile.readLine());
         equWorn.legs.intUses = Integer.parseInt(rafFile.readLine());
       }
       runWearScript(equWorn.legs);
       return;
     }
     if (strStore.equalsIgnoreCase("torso")) {
       equWorn.torso = engGame.getItem(rafFile.readLine());
       if (equWorn.torso != null) {
         equWorn.torso.lngDurability = Long.parseLong(rafFile.readLine());
         equWorn.torso.intUses = Integer.parseInt(rafFile.readLine());
       }
       runWearScript(equWorn.torso);
       return;
     }
     if (strStore.equalsIgnoreCase("waist")) {
       equWorn.waist = engGame.getItem(rafFile.readLine());
       if (equWorn.waist != null) {
         equWorn.waist.lngDurability = Long.parseLong(rafFile.readLine());
         equWorn.waist.intUses = Integer.parseInt(rafFile.readLine());
       }
       runWearScript(equWorn.waist);
       return;
     }
     if (strStore.equalsIgnoreCase("neck")) {
       equWorn.neck = engGame.getItem(rafFile.readLine());
       if (equWorn.neck != null) {
         equWorn.neck.lngDurability = Long.parseLong(rafFile.readLine());
         equWorn.neck.intUses = Integer.parseInt(rafFile.readLine());
       }
       runWearScript(equWorn.neck);
       return;
     }
     if (strStore.equalsIgnoreCase("skull")) {
       equWorn.skull = engGame.getItem(rafFile.readLine());
       if (equWorn.skull != null) {
         equWorn.skull.lngDurability = Long.parseLong(rafFile.readLine());
         equWorn.skull.intUses = Integer.parseInt(rafFile.readLine());
       }
       runWearScript(equWorn.skull);
       return;
     }
     if (strStore.equalsIgnoreCase("eyes")) {
       equWorn.eyes = engGame.getItem(rafFile.readLine());
       if (equWorn.eyes != null) {
         equWorn.eyes.lngDurability = Long.parseLong(rafFile.readLine());
         equWorn.eyes.intUses = Integer.parseInt(rafFile.readLine());
       }
       runWearScript(equWorn.eyes);
       return;
     }
     if (strStore.equalsIgnoreCase("hands")) {
       equWorn.hands = engGame.getItem(rafFile.readLine());
       if (equWorn.hands != null) {
         equWorn.hands.lngDurability = Long.parseLong(rafFile.readLine());
         equWorn.hands.intUses = Integer.parseInt(rafFile.readLine());
       }
       runWearScript(equWorn.hands);
       return;
     }
     if (strStore.equalsIgnoreCase("faction")) {
       String strFaction = rafFile.readLine();
       fctFaction = engGame.getFaction(strFaction);
       if (fctFaction != null) {
         engGame.log.printMessage(Log.DEBUG, "faction=\"" + fctFaction.strName + "\"");
       } else {
         engGame.log.printMessage(Log.DEBUG, "no faction found for \"" + strFaction + "\"");
       }
       return;
     }
     if (strStore.equalsIgnoreCase("onBattle")) {
       strOnBattle = rafFile.readLine();
       return;
     }
     if (strStore.equalsIgnoreCase("nofollow")) {
       noFollow = true;
       return;
     }
   } catch (Exception e) {
     engGame.log.printError(
         "parseMobFile():Parsing \"" + strStore + "\" from " + strName + "'s file", e);
   }
 }
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == jbSaveLayer) {
      try {
        FileOutputStream fout = new FileOutputStream(jtfCengMing.getText() + ".wyf");
        ObjectOutputStream oout = new ObjectOutputStream(fout);
        oout.writeObject(itemArray);
        oout.close();
        fout.close();
      } catch (Exception ea) {
        ea.printStackTrace();
      }
    } else if (e.getSource() == jbLoadLayer) {
      try {
        FileInputStream fin = new FileInputStream(jtfCengMing.getText() + ".wyf");
        ObjectInputStream oin = new ObjectInputStream(fin);
        itemArray = (Item[][]) oin.readObject();

        oin.close();
        fin.close();
        this.flush();
      } catch (Exception ea) {
        ea.printStackTrace();
      }
      lvp.repaint();
    } else if (e.getSource() == jbLoadAll) { // 全部铺上当前选中

      for (int row = 0; row < 40; row++) {
        for (int col = 0; col < 60; col++) {
          Item item = ((Item) (jl.getSelectedValue())).clone();
          itemArray[row][col] = item;
          if (item != null) {
            item.setPosition(col, row);
          }
        }
      }

      lvp.repaint();
    } else if (e.getSource() == jbCreate) { // 生成源代码

      try {
        FileOutputStream fout = null;
        DataOutputStream dout = null;
        fout = new FileOutputStream("maps.so");
        dout = new DataOutputStream(fout);
        int totalBlocks = 0;

        for (int i = 0; i < 40; i++) {
          for (int j = 0; j < 60; j++) {
            Item item = itemArray[i][j];
            if (item != null) {
              totalBlocks++;
            }
          }
        }
        System.out.println("totalBlocks=" + totalBlocks);

        // 写入不空块的数量
        dout.writeInt(totalBlocks);

        for (int i = 0; i < 40; i++) {
          for (int j = 0; j < 60; j++) {
            Item item = itemArray[i][j];
            if (item != null) {
              int w = item.w; // 元素的图片宽度
              int h = item.h; // 元素的图片高度
              int col = item.col; // 元素的地图列
              int row = item.row; // 元素的地图行
              int pCol = item.pCol; // 元素的占位列
              int pRow = item.pRow; // 元素的占位行
              String leiMing = item.leiMing; // 类名

              int[][] notIn = item.notIn; // 不可通过
              int[][] keYu = item.keYu; // 可遇矩阵

              // 计算图片下标
              int outBitmapInxex = 0;
              if (leiMing.equals("Grass")) {
                outBitmapInxex = 0;
              } else if (leiMing.equals("XiaoHua1")) {
                outBitmapInxex = 1;
              } else if (leiMing.equals("MuZhuang")) {
                outBitmapInxex = 2;
              } else if (leiMing.equals("XiaoHua2")) {
                outBitmapInxex = 3;
              } else if (leiMing.equals("Road")) {
                outBitmapInxex = 4;
              } else if (leiMing.equals("Jing")) {
                outBitmapInxex = 5;
              }

              dout.writeByte(outBitmapInxex); // 记录图片下标
              dout.writeByte(0); // 记录可遇标志 0-不可遇 底层都不可遇
              dout.writeByte(w); // 图片宽度
              dout.writeByte(h); // 图片高度
              dout.writeByte(col); // 总列数
              dout.writeByte(row); // 总行数
              dout.writeByte(pCol); // 占位列
              dout.writeByte(pRow); // 占位行

              int bktgCount = notIn.length; // 不可通过点的数量
              dout.writeByte(bktgCount); // 写入不可通过点的数量

              for (int k = 0; k < bktgCount; k++) {
                dout.writeByte(notIn[k][0]);
                dout.writeByte(notIn[k][1]);
              }
            }
          }
        }

        dout.close();
        fout.close();

      } catch (Exception ea) {
        ea.printStackTrace();
      }
    }
  }
Beispiel #29
0
  /**
   * 查询商品明细
   *
   * @param xml
   * @return
   * @throws DocumentException
   */
  public static Item getItem(String xml) throws Exception {
    Item item = new Item();
    Document document = formatStr2Doc(xml);
    Element rootElt = document.getRootElement();
    Element element = rootElt.element("Item");
    item.setTitle(element.elementText("Title"));
    item.setCurrency(element.elementText("Currency"));
    item.setCountry(element.elementText("Country"));
    item.setSite(element.elementText("Site"));
    item.setPostalCode(element.elementText("PostalCode"));
    item.setLocation(element.elementText("Location"));
    item.setItemID(element.elementText("ItemID"));
    item.setHitCounter(element.elementText("HitCounter"));
    item.setAutoPay(element.elementText("AutoPay").equals("true") ? true : false);
    item.setGiftIcon(element.elementText("GiftIcon"));
    item.setListingDuration(element.elementText("ListingDuration"));
    item.setQuantity(Integer.parseInt(element.elementText("Quantity")));
    item.setPayPalEmailAddress(element.elementText("PayPalEmailAddress"));
    item.setGetItFast("false".equals(element.elementText("GetItFast")) ? false : true);
    item.setPrivateListing("true".equals(element.elementText("PrivateListing")) ? true : false);
    item.setDispatchTimeMax(Integer.parseInt(element.elementText("DispatchTimeMax")));
    item.setListingDuration(element.elementText("ListingDuration"));
    item.setDescription(element.elementText("Description"));
    item.setSKU(element.elementText("SKU"));
    item.setConditionID(
        Integer.parseInt(
            element.elementText("CategoryID") == null
                ? "1000"
                : element.elementText("CategoryID")));
    PrimaryCategory pc = new PrimaryCategory();
    pc.setCategoryID(element.element("PrimaryCategory").elementText("CategoryID"));

    item.setPrimaryCategory(pc);
    String listType = "";
    if ("FixedPriceItem".equals(element.elementText("ListingType"))) {
      if (element.element("Variations") != null) {
        listType = "2";
      } else {
        listType = element.elementText("ListingType");
      }
    } else {
      listType = element.elementText("ListingType");
    }
    item.setListingType(listType);
    // 自定义属性
    Element elspe = element.element("ItemSpecifics");
    if (elspe != null) {
      ItemSpecifics itemSpecifics = new ItemSpecifics();
      Iterator<Element> itnvl = elspe.elementIterator("NameValueList");
      List<NameValueList> linvl = new ArrayList<NameValueList>();
      while (itnvl.hasNext()) {
        Element nvl = itnvl.next();
        NameValueList nvli = new NameValueList();
        nvli.setName(nvl.elementText("Name"));
        List<String> listr = new ArrayList();
        Iterator<Element> itval = nvl.elementIterator("Value");
        while (itval.hasNext()) {
          listr.add(itval.next().getText());
        }
        nvli.setValue(listr);
        linvl.add(nvli);
      }
      itemSpecifics.setNameValueList(linvl);
    }
    // 图片信息
    Element pice = element.element("PictureDetails");
    if (pice != null) {
      PictureDetails pd = new PictureDetails();
      if (pice.elementText("GalleryType") != null) {
        pd.setGalleryType(pice.elementText("GalleryType"));
      }
      if (pice.elementText("PhotoDisplay") != null) {
        pd.setPhotoDisplay(pice.elementText("PhotoDisplay"));
      }
      if (pice.elementText("GalleryURL") != null) {
        String url = pice.elementText("GalleryURL");
        if (url.indexOf("?") > 0) {
          url.substring(0, url.indexOf("?"));
        }
        pd.setGalleryURL(url);
      }
      Iterator<Element> itpicurl = pice.elementIterator("PictureURL");
      List<String> urlli = new ArrayList();
      while (itpicurl.hasNext()) {
        Element url = itpicurl.next();
        String urlstr = url.getStringValue();
        if (urlstr.indexOf("?") > 0) {
          urlstr = urlstr.substring(0, urlstr.indexOf("?"));
        }
        urlli.add(urlstr);
      }
      pd.setPictureURL(urlli);
      item.setPictureDetails(pd);
    }
    // 取得退货政策并封装
    Element returne = element.element("ReturnPolicy");
    ReturnPolicy rp = new ReturnPolicy();
    rp.setRefundOption(returne.elementText("RefundOption"));
    rp.setReturnsWithinOption(returne.elementText("ReturnsWithinOption"));
    rp.setReturnsAcceptedOption(returne.elementText("ReturnsAcceptedOption"));
    rp.setDescription(returne.elementText("Description"));
    rp.setShippingCostPaidByOption(returne.elementText("ShippingCostPaidByOption"));
    item.setReturnPolicy(rp);
    // 买家要求
    BuyerRequirementDetails brd = new BuyerRequirementDetails();
    MaximumItemRequirements mirs = new MaximumItemRequirements();
    Element buyere = element.element("BuyerRequirementDetails");
    if (buyere != null) {
      Element maxiteme = buyere.element("MaximumItemRequirements");
      if (maxiteme != null) {
        if (maxiteme.elementText("MaximumItemCount") != null) {
          mirs.setMaximumItemCount(Integer.parseInt(maxiteme.elementText("MaximumItemCount")));
        }
        if (maxiteme.elementText("MinimumFeedbackScore") != null) {
          mirs.setMinimumFeedbackScore(
              Integer.parseInt(maxiteme.elementText("MinimumFeedbackScore")));
        }
        brd.setMaximumItemRequirements(mirs);
      }

      Element maxUnpaid = buyere.element("MaximumUnpaidItemStrikesInfo");
      if (maxUnpaid != null) {
        MaximumUnpaidItemStrikesInfo muis = new MaximumUnpaidItemStrikesInfo();
        String count = maxUnpaid.elementText("Count");
        muis.setCount(Integer.parseInt(count));
        muis.setPeriod(maxUnpaid.elementText("Period"));
        brd.setMaximumUnpaidItemStrikesInfo(muis);
      }

      Element maxPolicy = buyere.element("MaximumBuyerPolicyViolations");
      if (maxPolicy != null) {
        MaximumBuyerPolicyViolations mbpv = new MaximumBuyerPolicyViolations();
        mbpv.setCount(Integer.parseInt(maxPolicy.elementText("Count")));
        mbpv.setPeriod(maxPolicy.elementText("Period"));
        brd.setMaximumBuyerPolicyViolations(mbpv);
      }
      if (buyere.elementText("LinkedPayPalAccount") != null) {
        brd.setLinkedPayPalAccount(
            buyere.elementText("LinkedPayPalAccount").equals("true") ? true : false);
      }
      if (buyere.elementText("ShipToRegistrationCountry") != null) {
        brd.setShipToRegistrationCountry(
            buyere.elementText("ShipToRegistrationCountry").equals("true") ? true : false);
      }
      item.setBuyerRequirementDetails(brd);
    }
    // 运输选项
    ShippingDetails sd = new ShippingDetails();
    Element elsd = element.element("ShippingDetails");
    Iterator<Element> itershipping = elsd.elementIterator("ShippingServiceOptions");
    List<ShippingServiceOptions> lisso = new ArrayList();
    // 国内运输
    while (itershipping.hasNext()) {
      Element shipping = itershipping.next();
      ShippingServiceOptions sso = new ShippingServiceOptions();
      sso.setShippingService(shipping.elementText("ShippingService"));
      if (shipping.elementText("ShippingServiceCost") != null) {
        sso.setShippingServiceCost(
            new ShippingServiceCost(
                shipping.attributeValue("currencyID"),
                Double.parseDouble(shipping.elementText("ShippingServiceCost"))));
      }
      sso.setShippingServicePriority(
          Integer.parseInt(shipping.elementText("ShippingServicePriority")));
      if (shipping.elementText("FreeShipping") != null) {
        sso.setFreeShipping(shipping.elementText("FreeShipping").equals("true") ? true : false);
      }
      ShippingServiceAdditionalCost ssac = new ShippingServiceAdditionalCost();
      ssac.setValue(
          Double.parseDouble(
              shipping.elementText("ShippingServiceAdditionalCost") != null
                  ? shipping.elementText("ShippingServiceAdditionalCost")
                  : "0"));
      sso.setShippingServiceAdditionalCost(ssac);
      ShippingSurcharge ss = new ShippingSurcharge();
      ss.setValue(
          Double.parseDouble(
              shipping.elementText("ShippingSurcharge") != null
                  ? shipping.elementText("ShippingSurcharge")
                  : "0"));
      sso.setShippingSurcharge(ss);
      lisso.add(sso);
    }
    if (lisso.size() > 0) {
      sd.setShippingServiceOptions(lisso);
    }
    // 不运送到的国家
    Iterator<Element> excEl = elsd.elementIterator("ExcludeShipToLocation");
    List<String> liex = new ArrayList<String>();
    while (excEl.hasNext()) {
      Element els = excEl.next();
      liex.add(els.getText());
    }
    if (liex.size() > 0) {
      sd.setExcludeShipToLocation(liex);
    }
    // 国际运输
    Iterator<Element> iteInt = elsd.elementIterator("InternationalShippingServiceOption");
    List<InternationalShippingServiceOption> liint =
        new ArrayList<InternationalShippingServiceOption>();
    while (iteInt.hasNext()) {
      Element intel = iteInt.next();
      InternationalShippingServiceOption isso = new InternationalShippingServiceOption();
      isso.setShippingService(intel.elementText("ShippingService"));
      isso.setShippingServiceCost(
          new ShippingServiceCost(
              intel.attributeValue("currencyID"),
              Double.parseDouble(intel.elementText("ShippingServiceCost"))));
      Iterator<Element> iteto = intel.elementIterator("ShipToLocation");
      List<String> listr = new ArrayList();
      while (iteto.hasNext()) {
        listr.add(iteto.next().getText());
      }
      isso.setShipToLocation(listr);
      isso.setShippingServicePriority(
          Integer.parseInt(intel.elementText("ShippingServicePriority")));

      ShippingServiceAdditionalCost ssac = new ShippingServiceAdditionalCost();
      ssac.setValue(
          Double.parseDouble(
              intel.elementText("ShippingServiceAdditionalCost") != null
                  ? intel.elementText("ShippingServiceAdditionalCost")
                  : "0"));
      isso.setShippingServiceAdditionalCost(ssac);
      liint.add(isso);
    }
    if (liint.size() > 0) {
      sd.setInternationalShippingServiceOption(liint);
    }
    // 计算所需的长宽高
    Element re = elsd.element("CalculatedShippingRate");
    if (re != null) {
      CalculatedShippingRate csr = new CalculatedShippingRate();
      if (re.elementText("InternationalPackagingHandlingCosts") != null) {
        csr.setPackagingHandlingCosts(
            new PackagingHandlingCosts(
                re.attributeValue("currencyID"),
                Double.parseDouble(re.elementText("InternationalPackagingHandlingCosts"))));
      }
      if (re.elementText("OriginatingPostalCode") != null) {
        csr.setOriginatingPostalCode(re.elementText("OriginatingPostalCode"));
      }
      if (re.elementText("PackageDepth") != null) {
        csr.setPackageDepth(Double.parseDouble(re.elementText("PackageDepth")));
      }
      if (re.elementText("PackageLength") != null) {
        csr.setPackageLength(Double.parseDouble(re.elementText("PackageLength")));
      }
      if (re.elementText("PackageWidth") != null) {
        csr.setPackageWidth(Double.parseDouble(re.elementText("PackageWidth")));
      }
      if (re.elementText("ShippingIrregular") != null) {
        csr.setShippingIrregular(Boolean.parseBoolean(re.elementText("ShippingIrregular")));
      }
      if (re.elementText("ShippingPackage") != null) {
        csr.setShippingPackage(re.elementText("ShippingPackage"));
      }
      if (re.elementText("WeightMajor") != null) {
        csr.setWeightMajor(Double.parseDouble(re.elementText("WeightMajor")));
      }
      if (re.elementText("WeightMinor") != null) {
        csr.setWeightMinor(Double.parseDouble(re.elementText("WeightMinor")));
      }
      sd.setCalculatedShippingRate(csr);
    }
    sd.setShippingType(elsd.elementText("ShippingType"));
    item.setShippingDetails(sd);
    // 卖家信息
    Seller seller = new Seller();
    Element elsel = element.element("Seller");
    seller.setUserID(elsel.elementText("UserID"));
    seller.setEmail(elsel.elementText("Email"));
    item.setSeller(seller);
    // 多属性
    Element vartions = element.element("Variations");
    if (vartions != null) {
      Iterator<Element> elvar = vartions.elementIterator("Variation");
      List<Variation> livar = new ArrayList();
      while (elvar.hasNext()) {
        Element ele = elvar.next();
        Variation var = new Variation();
        var.setSKU(ele.elementText("SKU"));
        var.setQuantity(
            Integer.parseInt(ele.elementText("Quantity"))
                - Integer.parseInt(ele.element("SellingStatus").elementText("QuantitySold")));
        var.setStartPrice(
            new StartPrice(
                ele.attributeValue("currencyID"),
                Double.parseDouble(ele.elementText("StartPrice"))));
        Element elvs = ele.element("VariationSpecifics");
        Iterator<Element> elnvl = elvs.elementIterator("NameValueList");
        List<NameValueList> linvl = new ArrayList();
        while (elnvl.hasNext()) {
          Element elment = elnvl.next();
          NameValueList nvl = new NameValueList();
          nvl.setName(elment.elementText("Name"));
          List<String> li = new ArrayList<String>();
          li.add(elment.elementText("Value"));
          nvl.setValue(li);
          linvl.add(nvl);
        }
        List<VariationSpecifics> livs = new ArrayList();
        VariationSpecifics vs = new VariationSpecifics();
        vs.setNameValueList(linvl);
        livs.add(vs);
        var.setVariationSpecifics(livs);
        livar.add(var);
      }
      Variations vtions = new Variations();
      vtions.setVariation(livar);
      // 多属性值
      Element elvss = vartions.element("VariationSpecificsSet");
      Iterator<Element> itele = elvss.elementIterator("NameValueList");
      List<NameValueList> linvl = new ArrayList();
      while (itele.hasNext()) {
        Element nvlel = itele.next();
        NameValueList nvl = new NameValueList();
        nvl.setName(nvlel.elementText("Name"));
        Iterator<Element> itvalue = nvlel.elementIterator("Value");
        List<String> livalue = new ArrayList();
        while (itvalue.hasNext()) {
          Element value = itvalue.next();
          livalue.add(value.getText());
        }
        nvl.setValue(livalue);
        linvl.add(nvl);
      }
      VariationSpecificsSet vss = new VariationSpecificsSet();
      vss.setNameValueList(linvl);
      vtions.setVariationSpecificsSet(vss);
      // 多属性图片信息
      Pictures pic = new Pictures();
      Element elpic = vartions.element("Pictures");
      pic.setVariationSpecificName(elpic.elementText("VariationSpecificName"));
      Iterator<Element> iturl = elpic.elementIterator("VariationSpecificPictureSet");
      List<VariationSpecificPictureSet> livsps = new ArrayList();
      while (iturl.hasNext()) {
        Element urle = iturl.next();
        VariationSpecificPictureSet vsps = new VariationSpecificPictureSet();
        vsps.setVariationSpecificValue(urle.elementText("VariationSpecificValue"));
        Iterator<Element> url = urle.elementIterator("PictureURL");
        List li = new ArrayList();
        while (url.hasNext()) {
          Element e = url.next();
          String urlstr = e.getText();
          if (urlstr.indexOf("?") > 0) {
            urlstr = urlstr.substring(0, urlstr.indexOf("?"));
          }
          li.add(urlstr);
        }
        vsps.setPictureURL(li);
        livsps.add(vsps);
      }
      pic.setVariationSpecificPictureSet(livsps);
      vtions.setPictures(pic);

      item.setVariations(vtions);
    } else {
      Element el = element.element("StartPrice");
      item.setStartPrice(
          new StartPrice(el.attributeValue("currencyID"), Double.parseDouble(el.getText())));
      if (element.element("BuyItNowPrice") != null) {
        item.setBuyItNowPrice(Double.parseDouble(element.elementText("BuyItNowPrice")));
      }
      if (element.element("ReservePrice") != null) {
        item.setReservePrice(Double.parseDouble(element.elementText("ReservePrice")));
      }
    }
    return item;
  }
Beispiel #30
0
  /**
   * 封装在线商品列表
   *
   * @param xml
   * @return
   * @throws DocumentException
   */
  public static List<Item> getItemElememt(String xml) throws Exception {
    List li = new ArrayList();
    Document document = formatStr2Doc(xml);
    Element rootElt = document.getRootElement();
    Element recommend = rootElt.element("ItemArray");
    Iterator<Element> iter = recommend.elementIterator("Item");
    while (iter.hasNext()) {
      Item item = new Item();
      Element element = iter.next();
      Element elflag = element.element("SellingStatus").element("ListingStatus");
      if (elflag != null) { // 如查商品不在线,就不取在线商品
        if (elflag.getText().equals("Active")) {

        } else {
          continue;
        }
      }
      item.setTitle(element.elementText("Title"));
      item.setCurrency(element.elementText("Currency"));
      item.setCountry(element.elementText("Country"));
      item.setSite(element.elementText("Site"));
      item.setPostalCode(element.elementText("PostalCode"));
      item.setLocation(element.elementText("Location"));
      item.setItemID(element.elementText("ItemID"));
      item.setHitCounter(element.elementText("HitCounter"));
      item.setAutoPay(element.elementText("AutoPay").equals("true") ? true : false);
      item.setGiftIcon(element.elementText("GiftIcon"));
      item.setListingDuration(element.elementText("ListingDuration"));
      item.setQuantity(Integer.parseInt(element.elementText("Quantity")));
      item.setSKU(element.elementText("SKU"));
      StartPrice sp = new StartPrice();
      sp.setValue(Double.parseDouble(element.element("SellingStatus").elementText("CurrentPrice")));
      sp.setCurrencyID(
          element.element("SellingStatus").element("CurrentPrice").attributeValue("currencyID"));
      item.setStartPrice(sp);
      item.setConditionID(
          Integer.parseInt(
              element.elementText("ConditionID") == null
                  ? "1000"
                  : element.elementText("ConditionID")));
      List lishipto = new ArrayList();
      Iterator<Element> shipe = element.elementIterator("ShipToLocations");
      while (shipe.hasNext()) {
        Element elstr = shipe.next();
        lishipto.add(elstr.getText());
      }
      item.setShipToLocations(lishipto);
      // 取得退货政策并封装
      Element returne = element.element("ReturnPolicy");
      ReturnPolicy rp = new ReturnPolicy();
      rp.setRefundOption(returne.elementText("RefundOption"));
      rp.setReturnsWithinOption(returne.elementText("ReturnsWithinOption"));
      rp.setReturnsAcceptedOption(returne.elementText("ReturnsAcceptedOption"));
      rp.setDescription(returne.elementText("Description"));
      rp.setShippingCostPaidByOption(returne.elementText("ShippingCostPaidByOption"));
      item.setReturnPolicy(rp);
      // 买家要求
      BuyerRequirementDetails brd = new BuyerRequirementDetails();
      MaximumItemRequirements mirs = new MaximumItemRequirements();
      Element buyere = element.element("BuyerRequirementDetails");
      if (buyere != null) {
        Element maxiteme = buyere.element("MaximumItemRequirements");
        if (maxiteme != null) {
          if (StringUtils.isNotEmpty(maxiteme.elementText("MaximumItemCount"))) {
            mirs.setMaximumItemCount(Integer.parseInt(maxiteme.elementText("MaximumItemCount")));
          }
          if (StringUtils.isNotEmpty(maxiteme.elementText("MinimumFeedbackScore"))) {
            mirs.setMinimumFeedbackScore(
                Integer.parseInt(maxiteme.elementText("MinimumFeedbackScore")));
          }
          brd.setMaximumItemRequirements(mirs);
        }

        Element maxUnpaid = buyere.element("MaximumUnpaidItemStrikesInfo");
        if (maxUnpaid != null) {
          MaximumUnpaidItemStrikesInfo muis = new MaximumUnpaidItemStrikesInfo();
          if (StringUtils.isNotEmpty(maxUnpaid.elementText("Count"))) {
            muis.setCount(Integer.getInteger(maxUnpaid.elementText("Count")));
          }
          muis.setPeriod(maxUnpaid.elementText("Period"));
          brd.setMaximumUnpaidItemStrikesInfo(muis);
        }

        Element maxPolicy = buyere.element("MaximumBuyerPolicyViolations");
        if (maxPolicy != null) {
          MaximumBuyerPolicyViolations mbpv = new MaximumBuyerPolicyViolations();
          if (StringUtils.isNotEmpty(maxPolicy.elementText("Count"))) {
            mbpv.setCount(Integer.parseInt(maxPolicy.elementText("Count")));
          }
          mbpv.setPeriod(maxPolicy.elementText("Period"));
          brd.setMaximumBuyerPolicyViolations(mbpv);
        }
        item.setBuyerRequirementDetails(brd);
      }

      li.add(item);
    }
    return li;
  }