Esempio n. 1
0
  /* 初始化action */
  private void initActions(Config config) {
    ComponentScaner componentScaner = new ComponentScaner();

    /* 初始化action */
    logger.info("\n");
    logger.info(
        ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> start matching url ... <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
    ActionDetector ad = new ActionDetector();
    ad.awareActionMethodFromBeans(componentScaner.getActionBeans(config));

    this.urlMapMap.put("GET", ad.getUrlMap);
    this.urlMapMap.put("POST", ad.postUrlMap);
    this.urlMapMap.put("PUT", ad.putUrlMap);
    this.urlMapMap.put("DELETE", ad.deleteUrlMap);

    /*
     * TODO 检查相同的uri有没有匹配不同action 方法
     */
    this.matchersMap.put("GET", ad.getUrlMap.keySet().toArray(new UrlMatcher[ad.getUrlMap.size()]));
    this.matchersMap.put(
        "POST", ad.postUrlMap.keySet().toArray(new UrlMatcher[ad.postUrlMap.size()]));
    this.matchersMap.put("PUT", ad.putUrlMap.keySet().toArray(new UrlMatcher[ad.putUrlMap.size()]));
    this.matchersMap.put(
        "DELETE", ad.deleteUrlMap.keySet().toArray(new UrlMatcher[ad.deleteUrlMap.size()]));

    logger.info(
        ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> end matching url <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
  }
Esempio n. 2
0
 void init(Config config) throws ServletException {
   logger.info("Init Dispatcher...");
   try {
     initAll(config);
   } catch (ServletException e) {
     throw e;
   } catch (Exception e) {
     throw new ServletException("Dispatcher init failed.", e);
   }
 }
public class UserInfoAction extends DispatchAction {
  Logger log = Logger.getLogger(this.getClass());

  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    String username = request.getParameter("username");
    // test/////////////////////////////////////////////
    Mongo mongo = new Mongo("127.0.0.1", 27017);
    DB db = mongo.getDB("user");
    // Set<String> collections = db.getCollectionNames();
    DBCollection collection = db.getCollection("user");
    BasicDBObject searchQuery = new BasicDBObject();
    System.out.println(username);
    searchQuery.put("user", username);
    // 使用collection的find方法查找document
    DBObject dbo = collection.findOne(searchQuery);
    String info = "";
    String phone = "";
    String favourite = "";
    if (dbo == null) {

    } else {
      log.info("23333");
      System.out.println(dbo);
      // 循环输出结果
      // String info = "";
      UserProfile profile = new UserProfile();
      profile = BeanUtil.dbObject2Bean(dbo, profile);
      info = profile.getInfo();
      phone = profile.getPhone();
      favourite = profile.getFavourite();
    }
    // System.out.println(info);
    HttpSession session = request.getSession(true);
    session.setAttribute("info", info);
    session.setAttribute("phone", phone);
    session.setAttribute("favourite", favourite);
    // System.out.println(collectionName);
    // 查询所有的Database
    // test/////////////////////////////////////////////
    ActionForward forward = new ActionForward();
    forward = mapping.findForward(Constants.SUCCESS_KEY);

    // Finish with
    return (forward);
  }
}
 public int loginBranchAdmin(BranchAdminTO branchAdminTO)
     throws MMSApplicationException, MMSBusinessException {
   System.out.println("BO : BranchAdminBO : loginBranchAdmin : start");
   LOG.info("Inside BO.... UserName = "******"Invalid Username");
   } else if (result == -1) {
     throw new MMSBusinessException("Username/password does not match");
   }
   System.out.println("BO : BranchAdminBO : loginBranchAdmin : end");
   return result;
 }
public class PicasaClientApp extends Application {

  private Logger log = Logger.getLogger(PicasaClientApp.class);

  @Override
  public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/picasaClient.fxml"));
    Parent root = loader.load();

    primaryStage.setTitle("Blitz Picasa Client");
    primaryStage.setScene(new Scene(root, 800, 600));
    primaryStage.show();
  }

  public static void main(String[] args) {
    launch(args);
  }
}
/**
 * Similar to TrevathanStrategy, except starts bidding later, and makes bids that are not always the
 * minimum required. Does not start bidding of no one else has bid. Therefore, may not bid at all in
 * an auction (by a collaborating seller).
 */
public class WaitStartStrategy implements Strategy {

  private static final Logger logger = Logger.getLogger(WaitStartStrategy.class);

  private final double theta;
  private final double alpha;
  private final double mu;

  private final Random r = new Random();

  public WaitStartStrategy(double theta, double alpha, double mu) {
    this.theta = theta;
    this.alpha = alpha;
    this.mu = mu;
  }

  @Override
  public long wait(Auction auction) {
    return r.nextInt(50) + 50;
  }

  @Override
  public boolean shouldBid(Auction shillAuction, long currentTime) {
    if (shillAuction
        .hasNoBids()) { // wait if no one else has bid yet, don't bid until 70% of auction has
                        // elapsed
      return false;
    }

    boolean d3success = directive3(theta, shillAuction, currentTime);
    boolean d4success = directive4(alpha, shillAuction);
    boolean d5success = directive5(mu, theta, currentTime, shillAuction);
    return d3success && d4success && d5success;
  }

  @Override
  /** Bid the minimum amount possible. */
  public int bidAmount(Auction auction) {
    int amount = auction.minimumBid();
    if (r.nextDouble() > 0.98) {
      int change =
          Math.max(
              0, (int) ((1 - auction.proportionOfTrueValuation()) * 0.1 * auction.trueValue()));
      amount += change;
    }
    return amount;
  }

  /** D3 of Simple Shilling Agent by Trevathan; don't bid too close to auction end */
  private static boolean directive3(double theta, Auction auction, long time) {
    double proportionRemaining =
        proportionRemaining(auction.getStartTime(), auction.getEndTime(), time);
    //		System.out.println("proportionRemaining: " + proportionRemaining);
    return proportionRemaining <= theta;
  }

  /** D4 of Simple Shilling Agent by Trevathan; bid until target price is reached */
  private static boolean directive4(double alpha, Auction auction) {
    double proportionPrice = auction.getCurrentPrice() / auction.trueValue();
    //		System.out.println("proportionPrice: " + proportionPrice);
    return alpha > proportionPrice;
  }

  /**
   * D5 of Simple Shilling Agent by Trevathan; bid when bid volume is high
   *
   * @param mu
   * @param auction
   * @return true if should bid, else false
   */
  private static boolean directive5(double mu, double theta, long currentTime, Auction auction) {
    if (auction.getBidCount() == 0) return true;

    double muTime =
        proportionToTime(
            1 - mu,
            auction.getStartTime(),
            currentTime); // D5, how far back to look when counting bids
    double thetaTime =
        proportionToTime(
            theta, auction.getStartTime(), auction.getEndTime()); // D3, don't bid too close to end
    int numberOfBids = numberOfBids(auction.getBidHistory(), (long) (muTime + 0.5));
    //		System.out.println("numberOfBids: " + numberOfBids);
    if (numberOfBids > 1) {
      return true;
    } else if (numberOfBids == 1) {
      // find the proportion of time time left available for the shill bidder to act
      double normalisedTime = proportionRemaining(auction.getStartTime(), thetaTime, currentTime);
      //			System.out.println("normalisedTime: " + normalisedTime);
      if (normalisedTime < 0.85) return true;
    }
    return false;
  }

  /**
   * Counts the number of bids that were made after the timeLimit by bidders who are not shill
   * bidders from this controller.
   *
   * @param bidHistory
   * @param time
   */
  private static int numberOfBids(List<Bid> bidHistory, long timeLimit) {
    int count = 0;
    for (int i = bidHistory.size() - 1; i >= 0 && bidHistory.get(i).getTime() >= timeLimit; i--) {
      count++;
    }
    return count;
  }

  private static double proportionRemaining(long start, double end, long current) {
    return ((double) current - start) / (end - start);
  }

  private static double proportionToTime(double proportion, long start, long end) {
    return proportion * (end - start) + start;
  }

  @Override
  public String toString() {
    return this.getClass().getSimpleName() + "." + theta + "." + alpha + "." + mu;
  }
}
public class BuyBookAction extends DispatchAction {
  protected BookDAO bookDAO;

  Logger log = Logger.getLogger(this.getClass());

  public BookDAO getBookDAO() {
    return bookDAO;
  }

  public void setBookDAO(BookDAO bookDAO) {
    this.bookDAO = bookDAO;
  }

  public ActionForward init(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    ActionForward forward = mapping.findForward(Constants.FAILURE_KEY);
    return (forward);
  }

  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    ActionErrors errors = new ActionErrors();
    ActionForward forward = new ActionForward();
    // BookForm bookForm = (BookForm) form;

    try {
      // get parameters
      HttpSession session = request.getSession(true);
      String name = request.getParameter("name");
      Book book = (Book) getBookDAO().getBookfromName(name).get(0);
      if (book == null) {
        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("Buy book failed"));
      }
      List books = (List) session.getAttribute("cart");
      if (books == null) {
        books = new ArrayList();
      }
      books.add(book);
      session.setAttribute("cart", books);

    } catch (Exception e) {
      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("register.message.failed"));
      e.printStackTrace();
    }

    if (!errors.isEmpty()) {
      saveErrors(request, errors);
      forward = mapping.findForward(Constants.FAILURE_KEY);
    } else {
      forward = mapping.findForward(Constants.SUCCESS_KEY);
    }

    // Finish with
    return (forward);
  }
}
public class BranchAdminBO {

  private static final Logger LOG = Logger.getLogger(BranchAdminBO.class);

  public int loginBranchAdmin(BranchAdminTO branchAdminTO)
      throws MMSApplicationException, MMSBusinessException {
    System.out.println("BO : BranchAdminBO : loginBranchAdmin : start");
    LOG.info("Inside BO.... UserName = "******"Invalid Username");
    } else if (result == -1) {
      throw new MMSBusinessException("Username/password does not match");
    }
    System.out.println("BO : BranchAdminBO : loginBranchAdmin : end");
    return result;
  }

  public String registerBranchAdmin(BranchAdminTO branchAdminTO, List<BranchTO> branchTOs)
      throws MMSApplicationException, MMSBusinessException {
    System.out.println("BO : BranchAdminBO : registerBranchAdmin : start");
    String branchAdminId;
    BranchAdminDAO branchAdminDAO = new BranchAdminDAO();
    BranchBO branchBO = new BranchBO();
    StatusBO statusBO = new StatusBO();

    validateRegistrationDetails(branchAdminTO, branchTOs);
    StatusTO statusTO = statusBO.getStatusByDOB(branchAdminTO.getDateOfBirth());
    branchAdminTO.setStatusTO(statusTO);

    branchBO.validateBranches(branchTOs);
    branchAdminId = branchAdminDAO.registerBranchAdmin(branchAdminTO);
    branchBO.setBranchAdminId(branchAdminId, branchTOs);

    System.out.println("BO : BranchAdminBO : registerBranchAdmin : end");
    return branchAdminId;
  }

  private void validateRegistrationDetails(BranchAdminTO branchAdminTO, List<BranchTO> branchTOs)
      throws MMSBusinessException, MMSApplicationException {
    System.out.println("BO : BranchAdminBO : validateRegistrationDetails : start");
    boolean errorFlag = false;
    HashMap<String, String> errorMap = new HashMap<String, String>();
    errorMap.put("firstName", "");
    errorMap.put("lastName", "");
    errorMap.put("address", "");
    errorMap.put("country", "");
    errorMap.put("state", "");
    errorMap.put("email", "");
    errorMap.put("password", "");
    errorMap.put("gender", "");
    errorMap.put("maritalStatus", "");
    errorMap.put("contactNo", "");
    errorMap.put("dateOfBirth", "");
    errorMap.put("idDocument", "");
    errorMap.put("branch", "");

    StateDAO stateDAO = new StateDAO();
    IdDocumentDAO idDocumentDAO = new IdDocumentDAO();

    String firstName = branchAdminTO.getFirstName();
    String LastName = branchAdminTO.getLastName();
    String address = branchAdminTO.getAddress();
    StateTO stateTO = branchAdminTO.getStateTO();
    String email = branchAdminTO.getEmail();
    String password = branchAdminTO.getPassword();
    String gender = branchAdminTO.getGender();
    String maritalStatus = branchAdminTO.getMaritalStatus();
    String contactNo = branchAdminTO.getContactNo();
    String dateOfBirth = branchAdminTO.getDateOfBirth();
    IdDocumentTO idDocumentTO = branchAdminTO.getIdDocumentTO();

    if (firstName == null || firstName.isEmpty()) {
      errorFlag = true;
      errorMap.put("firstName", "Please enter first name.");
    } else if (!firstName.matches("[a-zA-Z ]+")) {
      errorFlag = true;
      errorMap.put("firstName", "First Name can contain only alphabets and space");
    } else if (firstName.length() > 50) {
      errorFlag = true;
      errorMap.put("firstName", "First Name length must be less than 50 character");
    }

    if (LastName == null || LastName.isEmpty()) {
      errorFlag = true;
      errorMap.put("lastName", "Please enter last name");
    } else if (!LastName.matches("[a-zA-Z ]+")) {
      errorFlag = true;
      errorMap.put("lastName", "Last Name can contain only alphabets and space");
    } else if (LastName.length() > 50) {
      errorFlag = true;
      errorMap.put("lastName", "Last Name length must be less than 50 character ");
    }

    if (address == null || address.isEmpty()) {
      errorFlag = true;
      errorMap.put("address", "Please enter address");

    } else if (address.length() > 200) {
      errorFlag = true;
      errorMap.put("address", "Address length must be less than 200 character");
    }

    if (stateTO.getCountryTO().getCountryId() == null
        || stateTO.getCountryTO().getCountryId().isEmpty()) {
      errorFlag = true;
      errorMap.put("country", "Please select country");
    }

    if (stateTO.getStateId() == null || stateTO.getStateId().isEmpty()) {
      errorFlag = true;
      errorMap.put("state", "Please select state");
    } else if (!stateDAO.validateState(stateTO)) {
      errorFlag = true;
      errorMap.put("state", "Please select state from given states");
    }

    if (email == null || email.isEmpty()) {
      errorFlag = true;
      errorMap.put("email", "Please Enter email address");
    } else if (!Validator.validateEmailAddress(email).equals("Success")) {
      errorFlag = true;
      errorMap.put("email", Validator.validateEmailAddress(email));
    }

    if (password == null || password.isEmpty()) {
      errorFlag = true;
      errorMap.put("password", "Please enter password");
    } else if (!Validator.validatePassword(password).equals("Success")) {
      errorFlag = true;
      errorMap.put("password", Validator.validatePassword(password));
    }
    if (gender == null || gender.isEmpty()) {
      errorFlag = true;
      errorMap.put("gender", "Please select gender");
    } else if (!(gender.equals("male") || gender.equals("female"))) {
      errorFlag = true;
      errorMap.put("gender", "Please select gender from the given genders");
    }

    if (maritalStatus == null || maritalStatus.isEmpty()) {
      errorFlag = true;
      errorMap.put("maritalStatus", "Please select marital status");
    }

    if (contactNo == null || contactNo.isEmpty()) {
      errorFlag = true;
      errorMap.put("contactNo", "Please enter contact number");
    } else if (!Validator.validateContactNumber(contactNo).equals("Success")) {
      errorFlag = true;
      errorMap.put("contactNo", Validator.validateContactNumber(contactNo));
    }

    if (dateOfBirth == null || dateOfBirth.isEmpty()) {
      errorFlag = true;
      errorMap.put("dateOfBirth", "Please select date of birth");
    } else if (dateOfBirth.matches("[0-9]{4}[-][0-9]{2}[-][0-9]{2}")) {
      System.out.println(dateOfBirth);
      if (!Validator.validateDate(dateOfBirth, "yyyy-MM-dd").equals("Success")) {
        errorFlag = true;
        errorMap.put("dateOfBirth", Validator.validateDate(dateOfBirth, "yyyy-MM-dd"));
      } else {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dob = null;
        try {
          dob = simpleDateFormat.parse(dateOfBirth);
        } catch (ParseException e) {
          errorFlag = true;
          errorMap.put("dateOfBirth", "Please enter date of birth in valid format");
        }
        Date currentDay = new Date();
        if (dob.after(currentDay)) {
          errorFlag = true;
          errorMap.put("dateOfBirth", "You can not select future date as date of birth");
        }
      }
    } else {
      errorFlag = true;
      errorMap.put("dateOfBirth", "Please select valid date");
    }

    if (idDocumentTO.getIdDocumentId() == null || idDocumentTO.getIdDocumentId().isEmpty()) {
      errorFlag = true;
      errorMap.put("idDocument", "Please Select id Document");
    } else if (!idDocumentDAO.validateIdentityProof(idDocumentTO)) {
      errorFlag = true;
      errorMap.put("idDocument", "Please select Id from given Ids");
    }

    if (branchTOs == null || branchTOs.size() == 0) {
      errorFlag = true;
      errorMap.put("branch", "Please select branches");
    }

    if (errorFlag) {
      MMSBusinessException mmsBusinessException = new MMSBusinessException();
      mmsBusinessException.setErrorMap(errorMap);
      throw mmsBusinessException;
    }

    System.out.println("BO : BranchAdminBO : validateRegistrationDetails : end");
  }

  private void validateLoginDetail(BranchAdminTO branchAdminTO) throws MMSBusinessException {
    System.out.println("BO : BranchAdminBO : validateLoginDetails : start");
    String branchAdminId = branchAdminTO.getBranchAdminId();
    String password = branchAdminTO.getPassword();

    if ((branchAdminId == null || branchAdminId.isEmpty())
        && (password == null || password.isEmpty())) {
      throw new MMSBusinessException("Please enter username and password");
    }
    if (branchAdminId == null || branchAdminId.isEmpty()) {
      throw new MMSBusinessException("Username can not be blank");
    }
    if (password == null || password.isEmpty()) {
      throw new MMSBusinessException("Password can not be blank");
    }
    System.out.println("BO : BranchAdminBO : validateLoginDetails : end");
  }
}
Esempio n. 9
0
/**
 * Dispatcher handles ALL requests from clients, and dispatches to appropriate handler to handle
 * each request.
 *
 * @author Michael Liao ([email protected])
 * @author LiangWei([email protected])
 * @date 2015年3月13日 下午9:07:16
 */
class Dispatcher {
  private final Logger logger = Logger.getLogger(this.getClass());

  private Map<String, Map<UrlMatcher, ActionConfig>> urlMapMap =
      new HashMap<String, Map<UrlMatcher, ActionConfig>>();
  private Map<String, UrlMatcher[]> matchersMap = new HashMap<String, UrlMatcher[]>();

  void init(Config config) throws ServletException {
    logger.info("Init Dispatcher...");
    try {
      initAll(config);
    } catch (ServletException e) {
      throw e;
    } catch (Exception e) {
      throw new ServletException("Dispatcher init failed.", e);
    }
  }

  /**
   * http://example.com:8080/over/there?name=ferret#nose \__/ \______________/\_________/
   * \_________/ \__/ | | | | | scheme authority path query fragment
   *
   * <p>OR
   *
   * <p>[scheme:][//authority][path][?query][#fragment]
   *
   * @param request
   * @param response
   * @return
   * @throws ServletException
   * @throws IOException
   */
  Action dispatch(HttpServletRequest request) throws ServletException, IOException {
    String path = request.getRequestURI();
    String ctxP = request.getContextPath();

    if (ctxP.length() > 0) {
      path = path.substring(ctxP.length());
    }

    // set default character encoding to "utf-8" if encoding is not set:
    if (request.getCharacterEncoding() == null) {
      request.setCharacterEncoding("UTF-8");
    }

    String reqMethod = request.getMethod().toUpperCase();
    ActionConfig actionConfig = null;
    String[] urlArgs = null;

    /* 寻找处理请求的程序(方法) */
    for (UrlMatcher m : this.matchersMap.get(reqMethod)) {
      urlArgs = m.getUrlParameters(path);
      if (urlArgs != null) {
        actionConfig = urlMapMap.get(reqMethod).get(m);
        break;
      }
    }

    if (actionConfig != null) {
      return new Action(actionConfig, urlArgs, path);
    }

    return null;
  }

  /**
   * @param config
   * @throws Exception
   */
  private void initAll(Config config) throws Exception {
    initActions(config);
  }

  /* 初始化action */
  private void initActions(Config config) {
    ComponentScaner componentScaner = new ComponentScaner();

    /* 初始化action */
    logger.info("\n");
    logger.info(
        ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> start matching url ... <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
    ActionDetector ad = new ActionDetector();
    ad.awareActionMethodFromBeans(componentScaner.getActionBeans(config));

    this.urlMapMap.put("GET", ad.getUrlMap);
    this.urlMapMap.put("POST", ad.postUrlMap);
    this.urlMapMap.put("PUT", ad.putUrlMap);
    this.urlMapMap.put("DELETE", ad.deleteUrlMap);

    /*
     * TODO 检查相同的uri有没有匹配不同action 方法
     */
    this.matchersMap.put("GET", ad.getUrlMap.keySet().toArray(new UrlMatcher[ad.getUrlMap.size()]));
    this.matchersMap.put(
        "POST", ad.postUrlMap.keySet().toArray(new UrlMatcher[ad.postUrlMap.size()]));
    this.matchersMap.put("PUT", ad.putUrlMap.keySet().toArray(new UrlMatcher[ad.putUrlMap.size()]));
    this.matchersMap.put(
        "DELETE", ad.deleteUrlMap.keySet().toArray(new UrlMatcher[ad.deleteUrlMap.size()]));

    logger.info(
        ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> end matching url <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
  }

  void destroy() {
    logger.info("Destroy Dispatcher...");
  }
}
Esempio n. 10
0
 void destroy() {
   logger.info("Destroy Dispatcher...");
 }
 } catch (Exception ex){
 Logger.getLogger(MiEstacion.class.getName()).log(Level.SEVERE,null, ex);
 }