示例#1
0
  /** notify all observers */
  public void notifyObservers(ObserverType type, Object... object) {
    List<ActionObserver> tempOnceused = Collections.emptyList();
    lock.lock();
    try {
      if (onceUsedObservers.size() > 0) {
        tempOnceused = new ArrayList<ActionObserver>();
        Iterator<ActionObserver> iterator = onceUsedObservers.iterator();
        while (iterator.hasNext()) {
          ActionObserver observer = iterator.next();
          if (observer.getObserverType().matchesObserver(type)) {
            if (observer.tryUse()) {
              tempOnceused.add(observer);
              iterator.remove();
            }
          }
        }
      }
    } finally {
      lock.unlock();
    }

    // notify outside of lock
    for (ActionObserver observer : tempOnceused) {
      notifyAction(type, observer, object);
    }

    if (observers.size() > 0) {
      for (ActionObserver observer : observers) {
        if (observer.getObserverType().matchesObserver(type)) {
          notifyAction(type, observer, object);
        }
      }
    }
  }
示例#2
0
  /**
   * Create a Tree structure adding the reference to passed As. The Tree is created starting from
   * {@link DPCNode} as parent node containing 'n' {@link OPCNode} leafs where 'n' is list of OPC
   * passed. For each {@link OPCNode} there will be 'm' {@link SINode} leafs where 'm' is number of
   * Service Indicator passed.
   *
   * <p>DPC is mandatory while OPC and SI list are optional. If OPC or SI is not passed the wild
   * card '-1' leaf will be added to parent node
   *
   * @param rk
   * @param asImpl
   * @throws Exception
   */
  public void addRk(RoutingKey rk, AsImpl asImpl) throws Exception {
    int dpc = rk.getDestinationPointCodes()[0].getPointCode();
    OPCList[] opcArray = rk.getOPCLists();

    int[] opcIntArr = null;
    if (opcArray == null) {
      opcIntArr = new int[] {-1};
    } else {
      opcIntArr = opcArray[0].getPointCodes();
    }

    ServiceIndicators[] siArray = rk.getServiceIndicators();
    short[] siShortArr = null;
    if (siArray == null) {
      siShortArr = new short[] {-1};
    } else {
      siShortArr = siArray[0].getIndicators();
    }

    for (FastList.Node<DPCNode> n = dpcList.head(), end = dpcList.tail();
        (n = n.getNext()) != end; ) {
      DPCNode dpcNode = n.getValue();
      if (dpcNode.dpc == dpc) {
        this.addSi(dpcNode, opcIntArr, siShortArr, asImpl);
        return;
      }
    }

    DPCNode dpcNode = new DPCNode(dpc);
    this.addSi(dpcNode, opcIntArr, siShortArr, asImpl);
    this.dpcList.add(dpcNode);
  }
 public FastList<Byte> getFreeRooms(byte type) {
   FastList<Byte> list = new FastList<Byte>();
   for (Object room : _rooms.get(type).getValues()) {
     if (!((DimensionalRiftRoom) room).ispartyInside())
       list.add(((DimensionalRiftRoom) room)._room);
   }
   return list;
 }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ServletInputStream is = request.getInputStream();
    try {
      XmlCAPDialog original = factory.deserialize(is);
      HttpSession session = request.getSession(true);
      if (logger.isInfoEnabled()) {
        logger.info("doPost. HttpSession=" + session.getId() + " Dialog = " + original);
      }

      if ((original.getNoActivityTimeout() != null) && (original.getNoActivityTimeout())) {
        try {
          original.close(true);
          this.sendResponse(response, original);
        } catch (CAPException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        return;
      }

      FastList<CAPMessage> capMessages = original.getCAPMessages();

      for (FastList.Node<CAPMessage> n = capMessages.head(), end = capMessages.tail();
          (n = n.getNext()) != end; ) {

        CAPMessage capMessage = n.getValue();
        switch (capMessage.getMessageType()) {
          case initialDP_Request:
            InitialDPRequestImpl initialDPRequest = (InitialDPRequestImpl) capMessage;
            this.handleIdp(original, initialDPRequest);
            break;
          case applyChargingReport_Request:
            ApplyChargingReportRequestImpl applyChargingReportRequest =
                (ApplyChargingReportRequestImpl) capMessage;
            logger.info(
                String.format(
                    "Received applyChargingReportRequest=%s", applyChargingReportRequest));
            break;
          case eventReportBCSM_Request:
            EventReportBCSMRequestImpl eventReportBCSMRequest =
                (EventReportBCSMRequestImpl) capMessage;
            logger.info(
                String.format("Received eventReportBCSMRequest=%s", eventReportBCSMRequest));
            break;
          default:
            logger.info(String.format("unrecognized capMessage=%s", capMessage));
            break;
        }
      }

      // send response
      this.sendResponse(response, original);
    } catch (XMLStreamException e) {
      logger.error("Error while processing received XML", e);
    }
  }
示例#5
0
 /**
  * Match the passed dpc, opc and si with Tree structure and return the As from corresponding
  * matched {@link SINode}.
  *
  * <p>For example if AS1 is added for Routing Key with DPC=123 only. The tree will be formed with
  * 123 as {@link DPCNode} parent node and -1 as {@link OPCNode} leaf and within {@link OPCNode} -1
  * as {@link SINode}
  *
  * @param dpc
  * @param opc
  * @param si
  * @return
  */
 public AsImpl getAs(int dpc, int opc, short si) {
   for (FastList.Node<DPCNode> n = dpcList.head(), end = dpcList.tail();
       (n = n.getNext()) != end; ) {
     DPCNode dpcNode = n.getValue();
     if (dpcNode.dpc == dpc) {
       return dpcNode.getAs(opc, si);
     }
   }
   return null;
 }
 /**
  * Returns a complete category trail - can be used for exporting proper category trees. This is
  * mostly useful when used in combination with bread-crumbs, for building a faceted index tree, or
  * to export a category tree for migration to another system. Will create the tree from root point
  * to categoryId.
  *
  * <p>This method is not meant to be run on every request. Its best use is to generate the trail
  * every so often and store somewhere (a lucene/solr tree, entities, cache or so).
  *
  * @param productCategoryId id of category the trail should be generated for
  * @returns List organized trail from root point to categoryId.
  */
 public static Map getCategoryTrail(DispatchContext dctx, Map context) {
   String productCategoryId = (String) context.get("productCategoryId");
   Map<String, Object> results = ServiceUtil.returnSuccess();
   GenericDelegator delegator = (GenericDelegator) dctx.getDelegator();
   List<String> trailElements = FastList.newInstance();
   trailElements.add(productCategoryId);
   String parentProductCategoryId = productCategoryId;
   while (UtilValidate.isNotEmpty(parentProductCategoryId)) {
     // find product category rollup
     try {
       List<EntityCondition> rolllupConds = FastList.newInstance();
       rolllupConds.add(
           EntityCondition.makeCondition("productCategoryId", parentProductCategoryId));
       rolllupConds.add(EntityUtil.getFilterByDateExpr());
       List<GenericValue> productCategoryRollups =
           delegator.findList(
               "ProductCategoryRollup",
               EntityCondition.makeCondition(rolllupConds),
               null,
               UtilMisc.toList("sequenceNum"),
               null,
               true);
       if (UtilValidate.isNotEmpty(productCategoryRollups)) {
         // add only categories that belong to the top category to trail
         for (GenericValue productCategoryRollup : productCategoryRollups) {
           String trailCategoryId = productCategoryRollup.getString("parentProductCategoryId");
           parentProductCategoryId = trailCategoryId;
           if (trailElements.contains(trailCategoryId)) {
             break;
           } else {
             trailElements.add(trailCategoryId);
           }
         }
       } else {
         parentProductCategoryId = null;
       }
     } catch (GenericEntityException e) {
       Map<String, String> messageMap =
           UtilMisc.toMap("errMessage", ". Cannot generate trail from product category. ");
       String errMsg =
           UtilProperties.getMessage(
               "CommonUiLabels",
               "CommonDatabaseProblem",
               messageMap,
               (Locale) context.get("locale"));
       Debug.logError(e, errMsg, module);
       return ServiceUtil.returnError(errMsg);
     }
   }
   Collections.reverse(trailElements);
   results.put("trail", trailElements);
   return results;
 }
示例#7
0
  public static Map<String, Object> convertOrderIdListToHeaders(
      DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();

    List<GenericValue> orderHeaderList = UtilGenerics.checkList(context.get("orderHeaderList"));
    List<String> orderIdList = UtilGenerics.checkList(context.get("orderIdList"));

    // we don't want to process if there is already a header list
    if (orderHeaderList == null) {
      // convert the ID list to headers
      if (orderIdList != null) {
        List<EntityCondition> conditionList1 = FastList.newInstance();
        List<EntityCondition> conditionList2 = FastList.newInstance();

        // we are only concerned about approved sales orders
        conditionList2.add(
            EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_APPROVED"));
        conditionList2.add(
            EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER"));

        // build the expression list from the IDs
        for (String orderId : orderIdList) {
          conditionList1.add(
              EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId));
        }

        // create the conditions
        EntityCondition idCond = EntityCondition.makeCondition(conditionList1, EntityOperator.OR);
        conditionList2.add(idCond);

        EntityCondition cond = EntityCondition.makeCondition(conditionList2, EntityOperator.AND);

        // run the query
        try {
          orderHeaderList =
              delegator.findList(
                  "OrderHeader", cond, null, UtilMisc.toList("+orderDate"), null, false);
        } catch (GenericEntityException e) {
          Debug.logError(e, module);
          return ServiceUtil.returnError(e.getMessage());
        }
        Debug.logInfo("Recieved orderIdList  - " + orderIdList, module);
        Debug.logInfo("Found orderHeaderList - " + orderHeaderList, module);
      }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("orderHeaderList", orderHeaderList);
    return result;
  }
示例#8
0
  public static List<Map<String, GenericValue>> getPartyPaymentMethodValueMaps(
      Delegator delegator, String partyId, Boolean showOld) {
    List<Map<String, GenericValue>> paymentMethodValueMaps = FastList.newInstance();
    try {
      List<GenericValue> paymentMethods =
          delegator.findByAnd("PaymentMethod", UtilMisc.toMap("partyId", partyId));

      if (!showOld) paymentMethods = EntityUtil.filterByDate(paymentMethods, true);

      for (GenericValue paymentMethod : paymentMethods) {
        Map<String, GenericValue> valueMap = FastMap.newInstance();

        paymentMethodValueMaps.add(valueMap);
        valueMap.put("paymentMethod", paymentMethod);
        if ("CREDIT_CARD".equals(paymentMethod.getString("paymentMethodTypeId"))) {
          GenericValue creditCard = paymentMethod.getRelatedOne("CreditCard");
          if (creditCard != null) valueMap.put("creditCard", creditCard);
        } else if ("GIFT_CARD".equals(paymentMethod.getString("paymentMethodTypeId"))) {
          GenericValue giftCard = paymentMethod.getRelatedOne("GiftCard");
          if (giftCard != null) valueMap.put("giftCard", giftCard);
        } else if ("EFT_ACCOUNT".equals(paymentMethod.getString("paymentMethodTypeId"))) {
          GenericValue eftAccount = paymentMethod.getRelatedOne("EftAccount");
          if (eftAccount != null) valueMap.put("eftAccount", eftAccount);
        }
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e, module);
    }
    return paymentMethodValueMaps;
  }
 public List<String> getAttachmentIndexes() {
   List<String> attachments = FastList.newInstance();
   if (getMainPartCount() == 0) { // single part message (no attachments)
     return attachments;
   } else {
     for (int i = 0; i < getMainPartCount(); i++) {
       int subPartCount = getSubPartCount(i);
       String idx = Integer.toString(i);
       if (subPartCount > 0) {
         for (int si = 0; si < subPartCount; si++) {
           String sidx = idx + "." + Integer.toString(si);
           if (getPartDisposition(sidx) != null
               && (getPartDisposition(sidx).equals(Part.ATTACHMENT)
                   || getPartDisposition(sidx).equals(Part.INLINE))) {
             attachments.add(sidx);
           }
         }
       } else {
         if (getPartDisposition(idx) != null
             && (getPartDisposition(idx).equals(Part.ATTACHMENT)
                 || getPartDisposition(idx).equals(Part.INLINE))) {
           attachments.add(idx);
         }
       }
     }
     return attachments;
   }
 }
示例#10
0
  private static String parseStateProvinceGeoId(
      String payPalShipToState, String countryGeoId, Delegator delegator) {
    String lookupField = "geoName";
    List<EntityCondition> conditionList = FastList.newInstance();
    conditionList.add(EntityCondition.makeCondition("geoAssocTypeId", "REGIONS"));
    if ("USA".equals(countryGeoId) || "CAN".equals(countryGeoId)) {
      // PayPal returns two letter code for US and Canadian States/Provinces
      String geoTypeId = "USA".equals(countryGeoId) ? "STATE" : "PROVINCE";
      conditionList.add(EntityCondition.makeCondition("geoTypeId", geoTypeId));
      lookupField = "geoCode";
    }
    conditionList.add(EntityCondition.makeCondition("geoIdFrom", countryGeoId));
    conditionList.add(EntityCondition.makeCondition(lookupField, payPalShipToState));
    EntityCondition cond = EntityCondition.makeCondition(conditionList);
    GenericValue geoAssocAndGeoTo = null;
    try {
      geoAssocAndGeoTo =
          EntityQuery.use(delegator).from("GeoAssocAndGeoTo").where(cond).cache().queryFirst();

    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }
    if (geoAssocAndGeoTo != null) {
      return geoAssocAndGeoTo.getString("geoId");
    }
    return null;
  }
示例#11
0
  /**
   * Finds all matching PartyAndPostalAddress records based on the values provided. Excludes party
   * records with a statusId of PARTY_DISABLED. Results are ordered by descending
   * PartyContactMech.fromDate. The matching process is as follows: 1. Calls {@link
   * #findMatchingPartyPostalAddress(Delegator, String, String, String, String, String, String,
   * String, String)} to retrieve a list of address matched PartyAndPostalAddress records. Results
   * are limited to Parties of type PERSON. 2. For each matching PartyAndPostalAddress record, the
   * Person record for the Party is then retrieved and an upper case comparison is performed against
   * the supplied firstName, lastName and if provided, middleName.
   *
   * @param delegator Delegator instance
   * @param address1 PostalAddress.address1 to match against (Required).
   * @param address2 Optional PostalAddress.address2 to match against.
   * @param city PostalAddress.city value to match against (Required).
   * @param stateProvinceGeoId Optional PostalAddress.stateProvinceGeoId value to match against. If
   *     null or "**" is passed then the value will be ignored during matching. "NA" can be passed
   *     in place of "_NA_".
   * @param postalCode PostalAddress.postalCode value to match against. Cannot be null but can be
   *     skipped by passing a value starting with an "*". If the length of the supplied string is 10
   *     characters and the string contains a "-" then the postal code will be split at the "-" and
   *     the second half will be used as the postalCodeExt.
   * @param postalCodeExt Optional PostalAddress.postalCodeExt value to match against. Will be
   *     overridden if a postalCodeExt value is retrieved from postalCode as described above.
   * @param countryGeoId Optional PostalAddress.countryGeoId value to match against.
   * @param firstName Person.firstName to match against (Required).
   * @param middleName Optional Person.middleName to match against.
   * @param lastName Person.lastName to match against (Required).
   * @return List of PartyAndPostalAddress GenericValue objects that match the supplied criteria.
   * @throws GeneralException
   */
  public static List<GenericValue> findMatchingPersonPostalAddresses(
      Delegator delegator,
      String address1,
      String address2,
      String city,
      String stateProvinceGeoId,
      String postalCode,
      String postalCodeExt,
      String countryGeoId,
      String firstName,
      String middleName,
      String lastName)
      throws GeneralException {
    // return list
    List<GenericValue> returnList = FastList.newInstance();

    // address information
    if (firstName == null || lastName == null) {
      throw new IllegalArgumentException();
    }

    List<GenericValue> validFound =
        findMatchingPartyPostalAddress(
            delegator,
            address1,
            address2,
            city,
            stateProvinceGeoId,
            postalCode,
            postalCodeExt,
            countryGeoId,
            "PERSON");

    if (UtilValidate.isNotEmpty(validFound)) {
      for (GenericValue partyAndAddr : validFound) {
        String partyId = partyAndAddr.getString("partyId");
        if (UtilValidate.isNotEmpty(partyId)) {
          GenericValue p = delegator.findByPrimaryKey("Person", UtilMisc.toMap("partyId", partyId));
          if (p != null) {
            String fName = p.getString("firstName");
            String lName = p.getString("lastName");
            String mName = p.getString("middleName");
            if (lName.toUpperCase().equals(lastName.toUpperCase())) {
              if (fName.toUpperCase().equals(firstName.toUpperCase())) {
                if (mName != null && middleName != null) {
                  if (mName.toUpperCase().equals(middleName.toUpperCase())) {
                    returnList.add(partyAndAddr);
                  }
                } else if (middleName == null) {
                  returnList.add(partyAndAddr);
                }
              }
            }
          }
        }
      }
    }

    return returnList;
  }
示例#12
0
  /**
   * Performs a cascade delete on a party.
   *
   * <p>One reason this method can fail is that there were relationships with entities that are not
   * being deleted. If a party is not being deleted like it should, the developer should take a look
   * at the exception thrown by this method to see if any relations were violated. If there were
   * violations, consider adding the entities to the CASCADE array above.
   *
   * <p>XXX Warning, this method is very brittle. It is essentially emulating the ON DELETE CASCADE
   * functionality of well featured databases, but very poorly. As the datamodel evolves, this
   * method would have to be updated.
   */
  public static void deleteCrmParty(String partyId, Delegator delegator)
      throws GenericEntityException {
    // remove related entities from constant list
    for (int i = 0; i < CRM_PARTY_DELETE_CASCADE.length; i++) {
      String entityName = CRM_PARTY_DELETE_CASCADE[i][0];
      String fieldName = CRM_PARTY_DELETE_CASCADE[i][1];

      Map<String, Object> input = UtilMisc.<String, Object>toMap(fieldName, partyId);
      delegator.removeByAnd(entityName, input);
    }

    // remove communication events
    GenericValue party = delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", partyId));
    List<GenericValue> commEvnts = FastList.<GenericValue>newInstance();
    commEvnts.addAll(party.getRelated("ToCommunicationEvent"));
    commEvnts.addAll(party.getRelated("FromCommunicationEvent"));
    for (GenericValue commEvnt : commEvnts) {
      commEvnt.removeRelated("CommunicationEventRole");
      commEvnt.removeRelated("CommunicationEventWorkEff");
      commEvnt.removeRelated("CommEventContentAssoc");
      delegator.removeValue(commEvnt);
    }

    // finally remove party
    delegator.removeValue(party);
  }
示例#13
0
  public ModelReader(String modelName) throws GenericEntityException {
    this.modelName = modelName;
    entityResourceHandlers = FastList.newInstance();
    resourceHandlerEntities = FastMap.newInstance();
    entityResourceHandlerMap = FastMap.newInstance();

    EntityModelReaderInfo entityModelReaderInfo =
        EntityConfigUtil.getEntityModelReaderInfo(modelName);

    if (entityModelReaderInfo == null) {
      throw new GenericEntityConfException(
          "Cound not find an entity-model-reader with the name " + modelName);
    }

    // get all of the main resource model stuff, ie specified in the entityengine.xml file
    for (Element resourceElement : entityModelReaderInfo.resourceElements) {
      ResourceHandler handler =
          new MainResourceHandler(EntityConfigUtil.ENTITY_ENGINE_XML_FILENAME, resourceElement);
      entityResourceHandlers.add(handler);
    }

    // get all of the component resource model stuff, ie specified in each ofbiz-component.xml file
    for (ComponentConfig.EntityResourceInfo componentResourceInfo :
        ComponentConfig.getAllEntityResourceInfos("model")) {
      if (modelName.equals(componentResourceInfo.readerName)) {
        entityResourceHandlers.add(componentResourceInfo.createResourceHandler());
      }
    }
  }
示例#14
0
 /**
  * Returns the description of the previous loaded resource.
  *
  * @return
  */
 @Nonnull
 public String getPrevDescription() {
   if (index <= 0) {
     return "";
   }
   return res.get(index - 1).getDescription();
 }
  public void parse() {
    String fileName = "npcinfo_" + sessionName + ".txt";

    try {
      BufferedWriter out = new BufferedWriter(new FileWriter(fileName));

      for (DataPacket packet : packets) {
        String name = packet.getName();
        if ("SM_NPC_INFO".equals(name)) {
          List<ValuePart> valuePartList = packet.getValuePartList();
          NpcInfo npc = new NpcInfo();

          for (ValuePart valuePart : valuePartList) {
            String partName = valuePart.getModelPart().getName();
            if ("npcId".equals(partName)) {
              npc.npcId = Integer.parseInt(valuePart.readValue());
            } else if ("titleId".equals(partName)) {
              npc.titleId = Integer.parseInt(valuePart.readValue());
            } else if ("nameId".equals(partName)) {
              npc.nameId = Integer.parseInt(valuePart.readValue());
            } else if ("npcMaxHP".equals(partName)) {
              npc.npcMaxHp = Integer.parseInt(valuePart.readValue());
            } else if ("npclevel".equals(partName)) {
              npc.npcLevel = Byte.parseByte(valuePart.readValue());
            } else if ("npcTemplateHeight".equals(partName)) {
              npc.npcTemplateHeight = Float.parseFloat(valuePart.readValue());
            }
          }
          npcInfoList.add(npc);
        }
      }

      out.write("npcId\ttitleId\tnameId\tnpcMaxHp\tnpcLevel\tnpcTemplateHeight\n");

      for (NpcInfo npc : npcInfoList) {
        StringBuilder sb = new StringBuilder();
        sb.append(npc.npcId);
        sb.append("\t");
        sb.append(npc.titleId);
        sb.append("\t");
        sb.append(npc.nameId);
        sb.append("\t");
        sb.append(npc.npcMaxHp);
        sb.append("\t");
        sb.append(npc.npcLevel);
        sb.append("\t");
        sb.append(npc.npcTemplateHeight);
        sb.append("\t");
        sb.append("\n");
        out.write(sb.toString());
      }

      out.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    PacketSamurai.getUserInterface().log("The npc infos have been written");
  }
示例#16
0
  public static List<Map<String, BigDecimal>> getPackageSplit(
      DispatchContext dctx, List<Map<String, Object>> shippableItemInfo, BigDecimal maxWeight) {
    // create the package list w/ the first package
    List<Map<String, BigDecimal>> packages = FastList.newInstance();

    if (UtilValidate.isNotEmpty(shippableItemInfo)) {
      for (Map<String, Object> itemInfo : shippableItemInfo) {
        long pieces = ((Long) itemInfo.get("piecesIncluded")).longValue();
        BigDecimal totalQuantity = (BigDecimal) itemInfo.get("quantity");
        BigDecimal totalWeight = (BigDecimal) itemInfo.get("weight");
        String productId = (String) itemInfo.get("productId");

        // sanity check
        if (pieces < 1) {
          pieces = 1; // can NEVER be less than one
        }
        BigDecimal weight = totalWeight.divide(BigDecimal.valueOf(pieces), generalRounding);
        for (int z = 1; z <= totalQuantity.intValue(); z++) {
          BigDecimal partialQty =
              pieces > 1
                  ? BigDecimal.ONE.divide(BigDecimal.valueOf(pieces), generalRounding)
                  : BigDecimal.ONE;
          for (long x = 0; x < pieces; x++) {
            if (weight.compareTo(maxWeight) >= 0) {
              Map<String, BigDecimal> newPackage = FastMap.newInstance();
              newPackage.put(productId, partialQty);
              packages.add(newPackage);
            } else if (totalWeight.compareTo(BigDecimal.ZERO) > 0) {
              // create the first package
              if (packages.size() == 0) {
                packages.add(FastMap.<String, BigDecimal>newInstance());
              }

              // package loop
              boolean addedToPackage = false;
              for (Map<String, BigDecimal> packageMap : packages) {
                if (!addedToPackage) {
                  BigDecimal packageWeight =
                      calcPackageWeight(dctx, packageMap, shippableItemInfo, weight);
                  if (packageWeight.compareTo(maxWeight) <= 0) {
                    BigDecimal qty = packageMap.get(productId);
                    qty = UtilValidate.isEmpty(qty) ? BigDecimal.ZERO : qty;
                    packageMap.put(productId, qty.add(partialQty));
                    addedToPackage = true;
                  }
                }
              }
              if (!addedToPackage) {
                Map<String, BigDecimal> packageMap = FastMap.newInstance();
                packageMap.put(productId, partialQty);
                packages.add(packageMap);
              }
            }
          }
        }
      }
    }
    return packages;
  }
示例#17
0
  @Override
  protected final void writeImpl() {
    writeC(0xf3);
    writeD(_messageId);

    if (_info.isEmpty()) {
      writeD(0x00);
      writeD(_time);
      writeD(_requesterId);
    } else {
      writeD(_info.size());

      // TODO: Verify this i bet its same like SystemMessage
      for (CnfDlgData data : _info) {
        writeD(data.type);

        switch (data.type) {
          case TYPE_TEXT:
            writeS((String) data.value);
            break;
          case TYPE_NUMBER:
          case TYPE_NPC_NAME:
          case TYPE_ITEM_NAME:
            writeD((Integer) data.value);
            break;
          case TYPE_SKILL_NAME:
            writeD((Integer) data.value); // Skill Id
            writeD(_skillLvL); // Skill lvl
            break;
          case TYPE_ZONE_NAME:
            Integer[] array = (Integer[]) data.value;
            writeD(array[0]);
            writeD(array[1]);
            writeD(array[2]);
            break;
        }
      }
      if (_time != 0) {
        writeD(_time);
      }
      if (_requesterId != 0) {
        writeD(_requesterId);
      }
    }
  }
示例#18
0
  protected static void addEcaDefinitions(
      ResourceHandler handler, Map<String, Map<String, List<EntityEcaRule>>> ecaCache) {
    Element rootElement = null;
    try {
      rootElement = handler.getDocument().getDocumentElement();
    } catch (GenericConfigException e) {
      Debug.logError(e, module);
      return;
    }

    int numDefs = 0;
    for (Element e : UtilXml.childElementList(rootElement, "eca")) {
      String entityName = e.getAttribute("entity");
      String eventName = e.getAttribute("event");
      Map<String, List<EntityEcaRule>> eventMap = ecaCache.get(entityName);
      List<EntityEcaRule> rules = null;
      if (eventMap == null) {
        eventMap = FastMap.newInstance();
        rules = FastList.newInstance();
        ecaCache.put(entityName, eventMap);
        eventMap.put(eventName, rules);
      } else {
        rules = eventMap.get(eventName);
        if (rules == null) {
          rules = FastList.newInstance();
          eventMap.put(eventName, rules);
        }
      }
      rules.add(new EntityEcaRule(e));
      numDefs++;
    }
    try {
      Debug.logImportant(
          "Loaded ["
              + numDefs
              + "] Entity ECA definitions from "
              + handler.getFullLocation()
              + " in loader "
              + handler.getLoaderName(),
          module);
    } catch (GenericConfigException e) {
      Debug.logError(e, module);
      return;
    }
  }
 public static List<ScreenCondition> readSubConditions(
     ModelScreen modelScreen, Element conditionElement) {
   List<ScreenCondition> condList = FastList.newInstance();
   List<? extends Element> subElementList = UtilXml.childElementList(conditionElement);
   for (Element subElement : subElementList) {
     condList.add(readCondition(modelScreen, subElement));
   }
   return condList;
 }
  private static EntityCondition buildCountCondition(String fieldName, String fieldValue) {
    List<EntityCondition> orCondList = FastList.newInstance();
    orCondList.add(
        EntityCondition.makeCondition(
            "thruDate", EntityOperator.GREATER_THAN, UtilDateTime.nowTimestamp()));
    orCondList.add(EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null));
    EntityCondition orCond = EntityCondition.makeCondition(orCondList, EntityOperator.OR);

    List<EntityCondition> andCondList = FastList.newInstance();
    andCondList.add(
        EntityCondition.makeCondition(
            "fromDate", EntityOperator.LESS_THAN, UtilDateTime.nowTimestamp()));
    andCondList.add(EntityCondition.makeCondition(fieldName, EntityOperator.EQUALS, fieldValue));
    andCondList.add(orCond);
    EntityCondition andCond = EntityCondition.makeCondition(andCondList, EntityOperator.AND);

    return andCond;
  }
示例#21
0
  protected ArchivalSink checkForArchivalSink(ITraceSink sink) {
    if (sink instanceof ArchivalSink) return (ArchivalSink) sink;
    if (sink instanceof ChainedSink) {
      ChainedSink cSink = (ChainedSink) sink;
      FastList<ITraceSink> sinks = FastList.newInstance();
      cSink.getSinks(sinks);

      try {
        for (ITraceSink tSink : sinks) {
          ArchivalSink as = checkForArchivalSink(tSink);
          if (as != null) return as;
        }
      } finally {
        FastList.recycle(sinks);
      }
    }
    return null;
  }
示例#22
0
 /**
  * Once used observer add to observerController. If observer notify will be removed.
  *
  * @param observer
  */
 public void attach(ActionObserver observer) {
   observer.makeOneTimeUse();
   lock.lock();
   try {
     onceUsedObservers.add(observer);
   } finally {
     lock.unlock();
   }
 }
示例#23
0
 /** @param observer */
 public void removeObserver(ActionObserver observer) {
   observers.remove(observer);
   lock.lock();
   try {
     onceUsedObservers.remove(observer);
   } finally {
     lock.unlock();
   }
 }
 /** @see l2.brick.gameserver.network.serverpackets.L2GameServerPacket#writeImpl() */
 @Override
 protected void writeImpl() {
   writeC(0xfe);
   writeH(0x92);
   FastList<Territory> territoryList = TerritoryWarManager.getInstance().getAllTerritories();
   writeD(territoryList.size()); // Territory Count
   for (Territory t : territoryList) {
     writeD(t.getTerritoryId()); // Territory Id
     writeS(
         CastleManager.getInstance().getCastleById(t.getCastleId()).getName().toLowerCase()
             + "_dominion"); // territory name
     writeS(t.getOwnerClan().getName());
     writeD(t.getOwnedWardIds().size()); // Emblem Count
     for (int i : t.getOwnedWardIds())
       writeD(i); // Emblem ID - should be in for loop for emblem count
     writeD(_warTime);
   }
 }
 public List<Map<String, Object>> getAdItemTemplates(String temGroupId) {
   List<Map<String, Object>> themes = FastList.newInstance();
   for (Map<String, Object> temp : this.adItemTemplates) {
     if (temp.get("TemplateGroupId").equals(temGroupId)) {
       themes = UtilGenerics.checkList(temp.get("Templates"));
       break;
     }
   }
   return themes;
 }
示例#26
0
 /** Clear all observers */
 public void clear() {
   lock.lock();
   try {
     onceUsedObservers.clear();
   } finally {
     lock.unlock();
   }
   observers.clear();
   attackCalcObservers.clear();
 }
示例#27
0
/** Map Processor Main Class */
public class MapProcessor {

  List<MakeInString> makeInStrings = FastList.newInstance();
  String name;
  List<SimpleMapProcess> simpleMapProcesses = FastList.newInstance();

  public MapProcessor(Element simpleMapProcessorElement) {
    name = simpleMapProcessorElement.getAttribute("name");
    for (Element makeInStringElement :
        UtilXml.childElementList(simpleMapProcessorElement, "make-in-string")) {
      MakeInString makeInString = new MakeInString(makeInStringElement);
      makeInStrings.add(makeInString);
    }
    for (Element simpleMapProcessElement :
        UtilXml.childElementList(simpleMapProcessorElement, "process")) {
      SimpleMapProcess strProc = new SimpleMapProcess(simpleMapProcessElement);
      simpleMapProcesses.add(strProc);
    }
  }

  public void exec(
      Map<String, Object> inMap,
      Map<String, Object> results,
      List<Object> messages,
      Locale locale,
      ClassLoader loader) {
    if (UtilValidate.isNotEmpty(makeInStrings)) {
      for (MakeInString makeInString : makeInStrings) {
        makeInString.exec(inMap, results, messages, locale, loader);
      }
    }
    if (UtilValidate.isNotEmpty(simpleMapProcesses)) {
      for (SimpleMapProcess simpleMapProcess : simpleMapProcesses) {
        simpleMapProcess.exec(inMap, results, messages, locale, loader);
      }
    }
  }

  public String getName() {
    return name;
  }
}
示例#28
0
 public static List<String> getAssociatedPartyIdsByRelationshipType(
     Delegator delegator, String partyIdFrom, String partyRelationshipTypeId) {
   List<GenericValue> partyList = FastList.newInstance();
   List<String> partyIds = null;
   try {
     EntityConditionList<EntityExpr> baseExprs =
         EntityCondition.makeCondition(
             UtilMisc.toList(
                 EntityCondition.makeCondition("partyIdFrom", partyIdFrom),
                 EntityCondition.makeCondition(
                     "partyRelationshipTypeId", partyRelationshipTypeId)),
             EntityOperator.AND);
     List<GenericValue> associatedParties =
         delegator.findList("PartyRelationship", baseExprs, null, null, null, true);
     partyList.addAll(associatedParties);
     while (UtilValidate.isNotEmpty(associatedParties)) {
       List<GenericValue> currentAssociatedParties = FastList.newInstance();
       for (GenericValue associatedParty : associatedParties) {
         EntityConditionList<EntityExpr> innerExprs =
             EntityCondition.makeCondition(
                 UtilMisc.toList(
                     EntityCondition.makeCondition(
                         "partyIdFrom", associatedParty.get("partyIdTo")),
                     EntityCondition.makeCondition(
                         "partyRelationshipTypeId", partyRelationshipTypeId)),
                 EntityOperator.AND);
         List<GenericValue> associatedPartiesChilds =
             delegator.findList("PartyRelationship", innerExprs, null, null, null, true);
         if (UtilValidate.isNotEmpty(associatedPartiesChilds)) {
           currentAssociatedParties.addAll(associatedPartiesChilds);
         }
         partyList.add(associatedParty);
       }
       associatedParties = currentAssociatedParties;
     }
     partyIds = EntityUtil.getFieldListFromEntityList(partyList, "partyIdTo", true);
   } catch (GenericEntityException e) {
     Debug.logWarning(e, module);
   }
   return partyIds;
 }
示例#29
0
 @Override
 public void createGame() {
   if (this._locked) {
     return;
   }
   this.removeInactiveTeams();
   int teamsSize = this.getPlayersInTeam() * 2;
   if (this._parties.size() < teamsSize || this._games.size() >= this.getMaxGamesCount()) {
     this.check();
     return;
   }
   FastList players = new FastList();
   this.setIsTemporaryLocked(true);
   try {
     for (RegistrationData team : this._parties) {
       if (team.isChosen() || players.size() >= teamsSize) continue;
       team.setIsChosen(true);
       players.add(team);
       if (players.size() < teamsSize) continue;
       this.launchGame(players.toArray(new RegistrationData[players.size()]), null);
       this.setIsTemporaryLocked(false);
       break;
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   for (RegistrationData p : this._parties) {
     if (!p.isChosen()) continue;
     this._parties.remove(p);
   }
   this.setIsTemporaryLocked(false);
   this.check();
 }
示例#30
0
  private static List<Map<Object, Object>> getListMapsFromXmlFile(String XmlFilePath) {
    List<Map<Object, Object>> listMaps = FastList.newInstance();
    InputStream ins = null;
    URL xmlFileUrl = null;
    Document xmlDocument = null;
    try {
      if (UtilValidate.isNotEmpty(XmlFilePath)) {
        xmlFileUrl = UtilURL.fromFilename(XmlFilePath);
        if (xmlFileUrl != null) ins = xmlFileUrl.openStream();
        if (ins != null) {
          xmlDocument = UtilXml.readXmlDocument(ins, xmlFileUrl.toString());
          List<? extends Node> nodeList =
              UtilXml.childNodeList(xmlDocument.getDocumentElement().getFirstChild());
          for (Node node : nodeList) {
            if (node.getNodeType() == Node.ELEMENT_NODE) {
              Map<Object, Object> fields = FastMap.newInstance();
              fields.put(node.getNodeName(), UtilXml.elementValue((Element) node));
              Map<Object, Object> attrFields = getAttributeNameValueMap(node);
              Set<Object> keys = attrFields.keySet();
              Iterator<Object> attrFieldsIter = keys.iterator();
              while (attrFieldsIter.hasNext()) {
                Object key = attrFieldsIter.next();
                fields.put(key, attrFields.get(key));
              }

              List<? extends Node> childNodeList = UtilXml.childNodeList(node.getFirstChild());
              for (Node childNode : childNodeList) {
                fields.put(childNode.getNodeName(), UtilXml.elementValue((Element) childNode));
                attrFields = getAttributeNameValueMap(childNode);
                keys = attrFields.keySet();
                attrFieldsIter = keys.iterator();
                while (attrFieldsIter.hasNext()) {
                  Object key = attrFieldsIter.next();
                  fields.put(key, attrFields.get(key));
                }
              }
              listMaps.add(fields);
            }
          }
        }
      }
    } catch (Exception exc) {
      Debug.logError(exc, "Error reading xml file", module);
    } finally {
      try {
        if (ins != null) ins.close();
      } catch (Exception exc) {
        Debug.logError(exc, "Error reading xml file", module);
      }
    }
    return listMaps;
  }