Ejemplo n.º 1
1
 private void addIndexnode(final MainFrame frame) {
   String result =
       (String)
           JOptionPane.showInputDialog(
               null,
               "Enter the URL of the new indexnode:",
               "New Indexnode",
               JOptionPane.QUESTION_MESSAGE,
               null,
               null,
               "");
   if (result == null) return;
   try {
     if (!result.toLowerCase().startsWith("http://")) result = "http://" + result;
     final URL resURL = new URL(result);
     Thread elsewhere =
         new Thread(
             new Runnable() {
               @Override
               public void run() {
                 comm.registerNewIndexNode(resURL);
               }
             });
     elsewhere.setDaemon(true);
     elsewhere.setName("Add new indexnode thread");
     elsewhere.start();
     frame.setStatusHint("Added: " + result + "... It might take a few seconds to show up...");
   } catch (MalformedURLException e1) {
     frame.setStatusHint(
         new StatusHint(
             frame.getGui().getUtil().getImage("error"),
             "Invalid new indexnode URL! (" + e1.getMessage() + ")"));
     Logger.log("Invalid new indexnode url: " + e1);
   }
 }
Ejemplo n.º 2
0
  public Map<String, String> getCatchSizeList(Long channelId) {
    Map<String, String> map = null;
    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

    try {
      List<Channel> list = new ChannelDao().getChannels(channelId);
      if (list != null && !list.isEmpty()) {
        conn = OracleUtil.getConnection();
        map = new HashMap<String, String>();
        String sql =
            "select nvl(sum(a.log_catch_count),0) from twap_app_log_webcrawler a where exists(select 1 from twap_public_channel b where a.log_channel_id = b.channel_id start with b.channel_id=? connect by prior b.channel_id=b.channel_pid) and (to_char(a.create_time,'yyyy-mm-dd')=to_char(sysdate,'yyyy-mm-dd') )";
        for (Channel channel : list) {
          pst = conn.prepareStatement(sql);
          pst.setLong(1, channel.getChannelId());
          log.debug(sql.replaceAll("\\?", channel.getChannelId().toString()));
          rs = pst.executeQuery();
          if (rs.next()) {
            map.put(channel.getChannelName(), String.valueOf(rs.getLong(1)));
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error(e);
    } finally {
      close(conn, pst, rs);
    }

    return map;
  }
Ejemplo n.º 3
0
  public int update(int oid, String quantity, String memo) { // 更新揀貨單的揀貨數量
    logger.debug(
        "OrderPlaceDDAO.update: "
            + "pickId: "
            + oid
            + ", quantity: "
            + quantity
            + ", memo: "
            + memo);

    EntityManager em = XPersistence.getManager();
    OrderPlaceD bean = em.find(OrderPlaceD.class, oid);
    logger.debug("OrderPlaceD.update: orderPlaceD: " + bean);
    if (bean != null) {
      //			bean.setQuantity(quantity);
      bean.setRemark(memo);
      try {
        em.merge(bean);
        XPersistence.commit();
      } catch (Exception e) {
        logger.error("OrderPlaceD.update: " + e);
      }
      return 1; // 1:成功
    }
    return 0; // 0:失敗
  }
Ejemplo n.º 4
0
 @PostConstruct
 public void loadData() {
   games = gameService.findAllGames();
   logger.info("Retreaving all games ...");
   for (Game game : games) {
     logger.info("Game ..." + game.getName() + "  date " + game.getStartTime());
   }
 }
Ejemplo n.º 5
0
  private void dispatchLoop() {
    while (true) {
      long lastIteration = System.currentTimeMillis();

      try {
        // Logger.log("dispatch: "+lastIteration);

        if (mustShutdown) return;
        // 1) kill downloads over the limits
        clipDownloadCount();

        if (mustShutdown) return;

        int canQueue = maxActiveSlots - getActiveSlotCount();
        // only consider dispatching another if there are free slots:
        while (canQueue > 0) {
          // 2) dispatch another file: (this means we prefer to give slots to new files rather than
          // split existing chunks)
          if (!dispatchFile()) break; // stop iterating if the queue is empty.

          if (mustShutdown) return;
          canQueue--;
        }

        if (mustShutdown) return;

        if (canQueue > 0) { // if there are potentially still slots:
          // 3) find chunks ripe for splitting and split and dispatch them:
          chunkWorkers();
        }

        if (mustShutdown) return;

      } catch (Exception e) {
        Logger.warn("Dispatch iteration failed: " + e);
        Logger.log(e);
      }

      // Throttle this loop so that it does not spin exceedinly fast if there is nothing to do.
      long now = System.currentTimeMillis();
      long remaining =
          (lastIteration + FS2Constants.CLIENT_DOWNLOAD_DISPATCH_ITERATION_THROTTLE) - now;
      try {
        if (remaining > 0 && !wereCompleteItemsInQueue) {
          synchronized (this) {
            this.wait(remaining);
          }
        }
        wereCompleteItemsInQueue = false;
      } catch (InterruptedException e) {
        if (mustShutdown) return;
      }
    }
  }
Ejemplo n.º 6
0
 /**
  * Called by the queue to notify us that some chunk of the download queue has been erased so this
  * should un-dispatch those items contained within it.
  */
 synchronized void queueItemCancelled(DownloadItem cancelled) {
   for (DownloadWorker w : workers) {
     try {
       if (Util.isWithin(w.info.file.getFile(), cancelled.getFile())) {
         w.cancel();
       }
     } catch (IOException e) {
       Logger.severe("Couldn't determine file locations: " + e);
       Logger.log(e);
     }
   }
 }
Ejemplo n.º 7
0
  /**
   * Checks if the downloadFile specified has been completed already. This returns true iff: ) file
   * exists ) is expected size ) hashes to the same fs2 hash.
   *
   * @param f
   * @return
   */
  private boolean downloadFileCompleteOnDisk(DownloadFile f) {
    try {
      File onDisk = f.getFile();
      if (!onDisk.isFile()) return false;
      if (onDisk.length() != f.size) return false;
      if (!ThrottledFileDigester.fs2DigestFile(onDisk, null).equals(f.hash)) return false;
    } catch (Exception e) {
      Logger.warn("Couldn't test for file completion on disk: " + e);
      Logger.log(e);
      return false;
    }

    return true; // it's already complete!
  }
Ejemplo n.º 8
0
 /**
  * 删除 应用系统权限分配记录
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  * @throws IOException
  */
 public ActionForward delRARInfo(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws IOException {
   String rarid = request.getParameter("rarid");
   if (HtmlFactory.isNotEmpty(rarid)) {
     String falg = "成功!";
     try {
       RoleAssignRecords rar = roleAssignRecordsService.findById(Integer.valueOf(rarid));
       roleAssignRecordsService.delete(rar);
     } catch (Exception e) {
       falg = "失败!";
     } finally {
       try {
         systemlogservice.saveSystemLog(
             LogUtil.userName,
             LogUtil.roleName,
             SystemModelInfo.MOD_SYSM_user_other,
             "删除应用系统权限分配记录",
             new Timestamp(System.currentTimeMillis()),
             falg);
       } catch (Exception e) {
         logger.debug("连接日志出错", e);
       }
     }
   }
   return null;
 }
Ejemplo n.º 9
0
  public Long getCatchSize(Long channelId, String startDate, String endDate) {
    Long size = 0L;

    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

    try {
      conn = OracleUtil.getConnection();
      pst =
          conn.prepareStatement(
              "select nvl(sum(a.log_catch_count),0) from twap_app_log_webcrawler a where exists(select 1 from twap_public_channel b where a.log_channel_id = b.channel_id start with b.channel_id=? connect by prior b.channel_id=b.channel_pid) and (to_char(a.create_time,'yyyy-mm-dd')<=? and to_char(a.create_time,'yyyy-mm-dd')>=?)");
      pst.setLong(1, channelId);
      pst.setString(3, startDate);
      pst.setString(2, endDate);
      rs = pst.executeQuery();
      if (rs.next()) size = rs.getLong(1);
    } catch (Exception e) {
      e.printStackTrace();
      log.error(e);
    } finally {
      close(conn, pst, rs);
    }

    return size;
  }
Ejemplo n.º 10
0
  public void settingUpGame(javax.faces.event.ActionEvent event) {
    settingGame = true;
    int selectedRowIndex = gamesTable.getRowIndex();
    actualGame = games.get(selectedRowIndex);
    logger.info("selected game " + actualGame.getName());

    transformToActualUnits();
  }
Ejemplo n.º 11
0
  public Stock getStockByItem(int itemid) { // 用 商品編號 查出 該商品所在的某一貨架
    Query query =
        XPersistence.getManager()
            .createQuery(
                "FROM Stock o WHERE o.item.oid = :itemid order by o.volume desc"); // JPQL query
    query.setParameter("itemid", itemid);

    List<Stock> beans = query.getResultList();
    logger.debug("OrderPlaceDDAO.getStockByItem beans: " + beans);

    return beans.get(0);
  }
Ejemplo n.º 12
0
  public Collection<Stock> getStocksByPlaceId(int placeid) { // 用上架單編號(單頭)查出明細檔
    Query query =
        XPersistence.getManager()
            .createQuery(
                "FROM Stock o WHERE o.item.oid IN (SELECT p.item.oid FROM OrderPlaceD p WHERE p.orderPlace.oid = :placeid ORDER BY p.oid DESC) )"); // JPQL query
    query.setParameter("placeid", placeid);
    // select * FROM Stock o WHERE o.itemid IN (SELECT p.itemid FROM OrderPlaceD p WHERE
    // p.orderPlace_oid = '1' ORDER BY p.oid DESC)
    Collection stocks = query.getResultList();

    logger.debug("OrderPlaceDDAO.getStocksByPlaceId stocks: " + stocks);

    return stocks;
  }
Ejemplo n.º 13
0
 /**
  * 添加 应用系统权限分配记录
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  * @throws IOException
  */
 public ActionForward addRARInfo(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws IOException {
   String asrid = request.getParameter("asrid");
   String asiid = request.getParameter("asid");
   String name = request.getParameter("name");
   String operator = request.getParameter("operator");
   if (HtmlFactory.isNotEmpty(asiid)) {
     AppSysRole asr = new AppSysRole();
     AppSysInfo asi = new AppSysInfo();
     asi.setId(Integer.valueOf(asiid));
     if (HtmlFactory.isNotEmpty(asrid)) {
       asr.setId(Integer.valueOf(asrid));
     }
     if (HtmlFactory.isNotEmpty(name)) {
       name = HtmlFactory.conversionCoding(name, "GBK");
     }
     if (HtmlFactory.isNotEmpty(operator)) {
       operator = HtmlFactory.conversionCoding(operator, "GBK");
     }
     String falg = "成功!";
     try {
       RoleAssignRecords rar = new RoleAssignRecords();
       rar.setRole(asr);
       rar.setUser(name);
       rar.setOperator(operator);
       rar.setAppSys(asi);
       rar.setCreateTime(new Timestamp(new Date().getTime()));
       roleAssignRecordsService.add(rar);
     } catch (Exception e) {
       falg = "失败!";
     } finally {
       try {
         systemlogservice.saveSystemLog(
             LogUtil.userName,
             LogUtil.roleName,
             SystemModelInfo.MOD_SYSM_user_other,
             "添加应用系统权限分配记录",
             new Timestamp(System.currentTimeMillis()),
             falg);
       } catch (Exception e) {
         logger.debug("连接日志出错", e);
       }
     }
   }
   return null;
 }
Ejemplo n.º 14
0
 // TODO this requires redesign for writables
 public static boolean perform(WebHandle handle, WebDriver driver) {
   WebElement we = handle.findElement(driver);
   if (we == null) {
     // TODO this place strongly interferes with driver's implicitly wait. So, I think, personal
     // fails counter per handle needed.
     log.error(
         handle.url.graphUrl()
             + " | "
             + handle.xpath
             + "\n"
             + "Unable to .perform(WebDriver), cause search of element by stored selector is failed.");
     return false;
   }
   if (!we.isDisplayed() || !we.isEnabled()) {
     log.error(
         handle.url.graphUrl()
             + " | "
             + handle.xpath
             + "\n"
             + "Failed to .perform(WebDriver), cause element not displayed or not enabled.");
     return false;
   }
   switch (handle.eltype) {
     case clickable:
       we.click();
       break;
       //            case writable: we.sendKeys(context); break;
     case terminal:
       if (handle.isRoot()) return true;
       assert false : "terminal elements was touched";
       break;
     default:
       assert false : "this shouldn't have happened???";
       break;
   }
   return true;
 }
Ejemplo n.º 15
0
  /**
   * Given a file and a source this will start a worker-less file downloading.
   *
   * @param nF
   * @param bestSource
   */
  private void startFileDownloading(DownloadFile nF, DownloadSource bestSource) {
    // first ensure that the file is not already complete on disk:
    if (downloadFileCompleteOnDisk(nF)) {
      Logger.warn("Complete download: " + nF + " was in the queue. Issueing completion.");
      nF.downloadComplete(); // issue completion
      wereCompleteItemsInQueue = true;
      return;
    }

    // Create a new info container for the file (if it has never been started before, or if for some
    // reason there are no chunks in it (corrupt for some reason? broken code in the past probably))
    if (nF.active == null) {
      if (nF.getSize() == 0) {
        // zero byte files do not need downloading. (and indeed they will fail to dispatch correctly
        // as they will never have any incomplete chunks)
        try {
          nF.getFile().createNewFile();
          nF.downloadComplete();
          wereCompleteItemsInQueue = true;
          return;
        } catch (IOException e) {
          Logger.severe(
              "Empty file: " + nF.getFile().getPath() + " couldn't be created on disk: " + e);
        }
      }
      nF.active = new DownloadInfo(nF);
    } else {
      if (nF.active.isComplete()) {
        Logger.warn("Complete download: " + nF + " was in the queue. Issueing completion.");
        nF.downloadComplete();
        wereCompleteItemsInQueue = true;
        return;
      } else if (nF.active.chunks.size() == 0) {
        Logger.warn(
            "Active download '"
                + nF
                + "' in queue with no chunks. Restarting download from the beginning.");
        nF.active = new DownloadInfo(nF);
      }
    }

    try {
      // Create the new worker:
      DownloadWorker w = DownloadWorker.getDownloadWorker(this, nF.active);
      nF.active.worker = w;
      workers.add(w);

      // Start one of the download chunks present in the info:
      for (DownloadChunk c : w.getIncompleteInactiveChunks()) {
        w.downloadChunk(c, bestSource, downloadThreadPool);
        break;
      }
    } catch (IOException e) {
      Logger.severe("Unable to dispatch a download: " + e);
      Logger.log(e);
    }
  }
Ejemplo n.º 16
0
  @Override
  public void messageReturn(ChatMessage result) {
    if (result.id == -1) {
      ChatDocument doc = (ChatDocument) chatLog.getDocument();

      try {
        if (result.message.length() > 0) {
          doc.insertCommandResponse(
              doc.getLength(), /*"You requested some information: \n" +*/ result.message + "\n");
          chatLogScrollPane
              .getVerticalScrollBar()
              .setValue(chatLogScrollPane.getVerticalScrollBar().getMaximum());
        }
      } catch (BadLocationException e) {
        Logger.log(e);
      }
    }
  }
Ejemplo n.º 17
0
  @Override
  public void newMessages(LinkedList<ChatMessage> messages) {
    ChatDocument doc = (ChatDocument) chatLog.getDocument();

    for (ChatMessage m : messages) {
      if (m.id != -1) { // Only print non-commands
        try {
          doc.insertChatMessage(
              doc.getLength(), m.message + "\n", indexNode.getStats().getPeers().values());

          if (!owner.isActiveTab()) {
            missedMessageCount++;
          } else {
            missedMessageCount = 0;
          }

          if (owner.displayChatNotifications()) {
            // Only show messages if we're not focused on the tab

            // Currently pops up messages intended for the user only
            // If we don't trim the username out of the string then it will pop up every time the
            // user sends a message
            //						if (m.message.replaceFirst(".*:",
            // "").contains(frame.getGui().getShareServer().getAlias())){
            toaster.showToaster(
                frame.getGui().getUtil().getImageFullname("chat.png"),
                indexNode.getName(),
                m.message); // "There are "+missedMessageCount+" unread chat messages.");
            //						}

            // toaster.showToaster(m.message);
          }

          chatLogScrollPane
              .getVerticalScrollBar()
              .setValue(chatLogScrollPane.getVerticalScrollBar().getMaximum());
        } catch (BadLocationException e) {
          Logger.log(e);
        }
      }
    }
  }
Ejemplo n.º 18
0
  public void changeTimeUnit(ValueChangeEvent event) {
    logger.info(
        "UI Component Id " + event.getComponent().getId() + " new value " + event.getNewValue());

    String idComponent = event.getComponent().getId();
    String unit = event.getNewValue().toString();

    if (idComponent.startsWith("somGameDuration")) {
      this.durationUnit = unit;
    }

    if (idComponent.startsWith("somProductionTime")) {
      this.productionTimeUnit = unit;
    }

    if (idComponent.startsWith("somEnventTime")) {
      this.thresholdEventsUnit = unit;
    }

    transformToActualUnits();
  }
Ejemplo n.º 19
0
  public List<AppLog> getAppLogList(Long channelId, String startDate, String endDate) {
    List<AppLog> list = null;

    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

    try {
      conn = OracleUtil.getConnection();
      pst =
          conn.prepareStatement(
              "select rownum row_num,a.log_message,(select channel_name from twap_public_channel t where t.channel_id = a.log_channel_id) channel_name,a.log_channel_id,a.log_url,a.log_catch_count,to_char(a.create_time,'yy/mm/dd hh24:mi:ss') create_time  from twap_app_log_webcrawler a where exists(select 1 from twap_public_channel b where a.log_channel_id = b.channel_id start with b.channel_id=? connect by prior b.channel_id=b.channel_pid) and (to_char(a.create_time,'yyyy-mm-dd')<=? and to_char(a.create_time,'yyyy-mm-dd')>=?) order by a.create_time desc");
      pst.setLong(1, channelId);
      pst.setString(3, startDate);
      pst.setString(2, endDate);
      rs = pst.executeQuery();
      list = new ArrayList<AppLog>();
      while (rs.next()) {
        AppLog appLog =
            new AppLog(
                rs.getString("log_message"),
                rs.getLong("log_channel_id"),
                rs.getString("log_url"),
                rs.getLong("log_catch_count"));
        appLog.setChannelName(rs.getString("channel_name"));
        appLog.setCreateTime(rs.getString("create_time"));
        appLog.setLogId(rs.getLong("row_num"));
        list.add(appLog);
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error(e);
      rollback(conn);
    } finally {
      close(conn, pst, rs);
    }

    return list;
  }
Ejemplo n.º 20
0
/** Stores the options and measurements from the Page Setup dialog box */
class SetupRecord extends WritableRecordData {
  /** The logger */
  Logger logger = Logger.getLogger(SetupRecord.class);

  /** The binary data for output to file */
  private byte[] data;

  /** The header margin */
  private double headerMargin;

  /** The footer margin */
  private double footerMargin;

  /** The page orientation */
  private PageOrientation orientation;

  /** The paper size */
  private int paperSize;

  /** The scale factor */
  private int scaleFactor;

  /** The page start */
  private int pageStart;

  /** The fit width */
  private int fitWidth;

  /** The fit height */
  private int fitHeight;

  /** The horizontal print resolution */
  private int horizontalPrintResolution;

  /** The vertical print resolution */
  private int verticalPrintResolution;

  /** The number of copies */
  private int copies;

  /** Indicates whether the setup data should be initiliazed in the setup box */
  private boolean initialized;

  /**
   * Constructor, taking the sheet settings. This object just takes the various fields from the bean
   * in which it is interested
   *
   * @param the sheet settings
   */
  public SetupRecord(SheetSettings s) {
    super(Type.SETUP);

    orientation = s.getOrientation();
    headerMargin = s.getHeaderMargin();
    footerMargin = s.getFooterMargin();
    paperSize = s.getPaperSize().getValue();
    horizontalPrintResolution = s.getHorizontalPrintResolution();
    verticalPrintResolution = s.getVerticalPrintResolution();
    fitWidth = s.getFitWidth();
    fitHeight = s.getFitHeight();
    pageStart = s.getPageStart();
    scaleFactor = s.getScaleFactor();
    copies = s.getCopies();
    initialized = true;
  }

  /**
   * Sets the orientation
   *
   * @param o the orientation
   */
  public void setOrientation(PageOrientation o) {
    orientation = o;
  }

  /**
   * Sets the header and footer margins
   *
   * @param hm the header margin
   * @param fm the footer margin
   */
  public void setMargins(double hm, double fm) {
    headerMargin = hm;
    footerMargin = fm;
  }

  /**
   * Sets the paper size
   *
   * @param ps the paper size
   */
  public void setPaperSize(PaperSize ps) {
    paperSize = ps.getValue();
  }

  /**
   * Gets the binary data for output to file
   *
   * @return the binary data
   */
  public byte[] getData() {
    data = new byte[34];

    // Paper size
    IntegerHelper.getTwoBytes(paperSize, data, 0);

    // Scale factor
    IntegerHelper.getTwoBytes(scaleFactor, data, 2);

    // Page start
    IntegerHelper.getTwoBytes(pageStart, data, 4);

    // Fit width
    IntegerHelper.getTwoBytes(fitWidth, data, 6);

    // Fit height
    IntegerHelper.getTwoBytes(fitHeight, data, 8);

    // grbit
    int options = 0;
    if (orientation == PageOrientation.PORTRAIT) {
      options |= 0x02;
    }

    if (pageStart != 0) {
      options |= 0x80;
    }

    if (!initialized) {
      options |= 0x04;
    }

    IntegerHelper.getTwoBytes(options, data, 10);

    // print resolution
    IntegerHelper.getTwoBytes(horizontalPrintResolution, data, 12);

    // vertical print resolution
    IntegerHelper.getTwoBytes(verticalPrintResolution, data, 14);

    // header margin
    DoubleHelper.getIEEEBytes(headerMargin, data, 16);

    // footer margin
    DoubleHelper.getIEEEBytes(footerMargin, data, 24);

    // Number of copies
    IntegerHelper.getTwoBytes(copies, data, 32);

    return data;
  }
}
Ejemplo n.º 21
0
/*
 * author [email protected]
 */
@SuppressWarnings("unchecked")
public class OrderPlaceDDAO {
  private static Logger logger = Logger.getLogger(OrderPlaceDDAO.class);

  public OrderPlaceDDAO() {}

  public Collection<Stock> getStocksByPlaceId(int placeid) { // 用上架單編號(單頭)查出明細檔
    Query query =
        XPersistence.getManager()
            .createQuery(
                "FROM Stock o WHERE o.item.oid IN (SELECT p.item.oid FROM OrderPlaceD p WHERE p.orderPlace.oid = :placeid ORDER BY p.oid DESC) )"); // JPQL query
    query.setParameter("placeid", placeid);
    // select * FROM Stock o WHERE o.itemid IN (SELECT p.itemid FROM OrderPlaceD p WHERE
    // p.orderPlace_oid = '1' ORDER BY p.oid DESC)
    Collection stocks = query.getResultList();

    logger.debug("OrderPlaceDDAO.getStocksByPlaceId stocks: " + stocks);

    return stocks;
  }

  public Stock getStockByItem(int itemid) { // 用 商品編號 查出 該商品所在的某一貨架
    Query query =
        XPersistence.getManager()
            .createQuery(
                "FROM Stock o WHERE o.item.oid = :itemid order by o.volume desc"); // JPQL query
    query.setParameter("itemid", itemid);

    List<Stock> beans = query.getResultList();
    logger.debug("OrderPlaceDDAO.getStockByItem beans: " + beans);

    return beans.get(0);
  }

  //	public OrderPlaceD getPlaceD(int id) {
  //		for (Iterator<OrderPlaceD> iterator = pickDList.iterator(); iterator.hasNext();) {
  //			OrderPlaceD st = (OrderPlaceD) iterator.next();
  //			if (st.getOid() == id)
  //				return st;
  //		}
  //		return new OrderPlaceD();
  //	}

  //	public boolean delete(OrderStoreD beanD){
  //		Connection conn = null;
  //		Statement stmt = null;
  //		boolean result = false;
  //		try {
  //			// get connection
  //			conn = DriverManager.getConnection(url, user, pwd);
  //			stmt = conn.createStatement();
  //			if (stmt.executeUpdate("delete from beanD where id = '" + beanD.getOid() + "'") > 0);
  //			result = true;
  //
  //		} catch (SQLException e) {
  //			e.printStackTrace();
  //		}finally {
  //			try {
  //				stmt.close();
  //			} catch (SQLException e) {
  //				e.printStackTrace();
  //			}
  //			try {
  //				conn.close();
  //			} catch (SQLException e) {
  //				e.printStackTrace();
  //			}
  //		}
  //
  //		return result;
  //	}

  public boolean insert(OrderStoreD beanD) {
    XPersistence.getManager().persist(beanD);
    XPersistence
        .commit(); // 若 UUID 重複,會有例外: org.hibernate.PersistentObjectException: detached entity
                   // passed to persist: com.kaijung.jpa.OrderStoreD
    // XHibernate.commit();
    return true;
  }

  //	public boolean insert(OrderStoreD beanD){
  //		Connection conn = null;
  //		Statement stmt = null;
  //		boolean result = false;
  //		try {
  //			conn = DriverManager.getConnection(url, user, pwd);
  //			stmt = conn.createStatement();
  //			log.debug( "UUID.randomUUID(): " + UUID.randomUUID());
  ////			java.lang.System.out.println( "insert into OrderStoreD(oid,quantity) " +
  ////					"values ('" + UUID.randomUUID().toString() +
  ////					"','" + beanD.getQuantity() + "')" );
  //			final String uuid = UUID.randomUUID().toString().replaceAll("-", "");
  //			if (stmt.executeUpdate("insert into OrderStoreD(oid,quantity) " +
  //					"values ('" + uuid +
  //					"','" + beanD.getQuantity() + "')") > 0);
  //			result = true;
  //		} catch (SQLException e) {
  //			e.printStackTrace();
  //		}finally{
  //			try {
  //				stmt.close();
  //			} catch (SQLException e) {
  //				e.printStackTrace();
  //			}
  //			try {
  //				conn.close();
  //			} catch (SQLException e) {
  //				e.printStackTrace();
  //			}
  //		}
  //
  //		return result;
  //	}

  public int update(int oid, String quantity, String memo) { // 更新揀貨單的揀貨數量
    logger.debug(
        "OrderPlaceDDAO.update: "
            + "pickId: "
            + oid
            + ", quantity: "
            + quantity
            + ", memo: "
            + memo);

    EntityManager em = XPersistence.getManager();
    OrderPlaceD bean = em.find(OrderPlaceD.class, oid);
    logger.debug("OrderPlaceD.update: orderPlaceD: " + bean);
    if (bean != null) {
      //			bean.setQuantity(quantity);
      bean.setRemark(memo);
      try {
        em.merge(bean);
        XPersistence.commit();
      } catch (Exception e) {
        logger.error("OrderPlaceD.update: " + e);
      }
      return 1; // 1:成功
    }
    return 0; // 0:失敗
  }
}
Ejemplo n.º 22
0
/** The data for this blip store entry. Typically this is the raw image data */
class BlipStoreEntry extends EscherAtom {
  /** The logger */
  private static Logger logger = Logger.getLogger(BlipStoreEntry.class);

  /** The type of the blip */
  private BlipType type;

  /** The image data read in */
  private byte[] data;

  /** The length of the image data */
  private int imageDataLength;

  /** The reference count on this blip */
  private int referenceCount;

  /** Flag to indicate that this entry was specified by the API, and not read in */
  private boolean write;

  /** The start of the image data within this blip entry */
  private static final int IMAGE_DATA_OFFSET = 61;

  /**
   * Constructor
   *
   * @param erd the escher record data
   */
  public BlipStoreEntry(EscherRecordData erd) {
    super(erd);
    type = BlipType.getType(getInstance());
    write = false;
    byte[] bytes = getBytes();
    referenceCount =
        IntegerHelper.getInt(
            bytes[24], bytes[25],
            bytes[26], bytes[27]);
  }

  /**
   * Constructor
   *
   * @param d the drawing
   * @exception IOException
   */
  public BlipStoreEntry(Drawing d) throws IOException {
    super(EscherRecordType.BSE);
    type = BlipType.PNG;
    setVersion(2);
    setInstance(type.getValue());

    byte[] imageData = d.getImageBytes();
    imageDataLength = imageData.length;
    data = new byte[imageDataLength + IMAGE_DATA_OFFSET];
    System.arraycopy(imageData, 0, data, IMAGE_DATA_OFFSET, imageDataLength);
    referenceCount = d.getReferenceCount();
    write = true;
  }

  /**
   * Accessor for the blip type
   *
   * @return the blip type
   */
  public BlipType getBlipType() {
    return type;
  }

  /**
   * Gets the data for this blip so that it can be written out
   *
   * @return the data for the blip
   */
  public byte[] getData() {
    if (write) {
      // Drawing has been specified by API

      // Type on win32
      data[0] = (byte) type.getValue();

      // Type on MacOs
      data[1] = (byte) type.getValue();

      // The blip identifier
      //    IntegerHelper.getTwoBytes(0xfce1, data, 2);

      // Unused tags - 18 bytes
      //    System.arraycopy(stuff, 0, data, 2, stuff.length);

      // The size of the file
      IntegerHelper.getFourBytes(imageDataLength + 8 + 17, data, 20);

      // The reference count on the blip
      IntegerHelper.getFourBytes(referenceCount, data, 24);

      // Offset in the delay stream
      IntegerHelper.getFourBytes(0, data, 28);

      // Usage byte
      data[32] = (byte) 0;

      // Length of the blip name
      data[33] = (byte) 0;

      // Last two bytes unused
      data[34] = (byte) 0x7e;
      data[35] = (byte) 0x01;

      // The blip itself
      data[36] = (byte) 0;
      data[37] = (byte) 0x6e;

      // The blip identifier
      IntegerHelper.getTwoBytes(0xf01e, data, 38);

      // The length of the blip.  This is the length of the image file plus
      // 16 bytes
      IntegerHelper.getFourBytes(imageDataLength + 17, data, 40);

      // Unknown stuff
      //    System.arraycopy(stuff, 0, data, 44, stuff.length);
    } else {
      // drawing has been read in
      data = getBytes();
    }

    return setHeaderData(data);
  }

  /** Reduces the reference count in this blip. Called when a drawing is removed */
  void dereference() {
    referenceCount--;
    Assert.verify(referenceCount >= 0);
  }

  /**
   * Accessor for the reference count on the blip
   *
   * @return the reference count on the blip
   */
  int getReferenceCount() {
    return referenceCount;
  }

  /**
   * Accessor for the image data.
   *
   * @return the image data
   */
  byte[] getImageData() {
    byte[] allData = getBytes();
    byte[] imageData = new byte[allData.length - IMAGE_DATA_OFFSET];
    System.arraycopy(allData, IMAGE_DATA_OFFSET, imageData, 0, imageData.length);
    return imageData;
  }
}
Ejemplo n.º 23
0
 public void settingUpPlayers(javax.faces.event.ActionEvent event) {
   int selectedRowIndex = gamesTable.getRowIndex();
   actualGame = games.get(selectedRowIndex);
   logger.info("selected game " + actualGame.getName());
 }
Ejemplo n.º 24
0
/**
 * @author dongq
 *     <p>create time : 2009-12-11 ионГ10:02:58
 */
public class AppLogDao extends Dao {

  private static final Logger log = Logger.getLogger(AppLogDao.class);

  public Map<String, String> getCatchSizeList(Long channelId) {
    Map<String, String> map = null;
    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

    try {
      List<Channel> list = new ChannelDao().getChannels(channelId);
      if (list != null && !list.isEmpty()) {
        conn = OracleUtil.getConnection();
        map = new HashMap<String, String>();
        String sql =
            "select nvl(sum(a.log_catch_count),0) from twap_app_log_webcrawler a where exists(select 1 from twap_public_channel b where a.log_channel_id = b.channel_id start with b.channel_id=? connect by prior b.channel_id=b.channel_pid) and (to_char(a.create_time,'yyyy-mm-dd')=to_char(sysdate,'yyyy-mm-dd') )";
        for (Channel channel : list) {
          pst = conn.prepareStatement(sql);
          pst.setLong(1, channel.getChannelId());
          log.debug(sql.replaceAll("\\?", channel.getChannelId().toString()));
          rs = pst.executeQuery();
          if (rs.next()) {
            map.put(channel.getChannelName(), String.valueOf(rs.getLong(1)));
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error(e);
    } finally {
      close(conn, pst, rs);
    }

    return map;
  }

  public Long getCatchSize(Long channelId, String startDate, String endDate) {
    Long size = 0L;

    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

    try {
      conn = OracleUtil.getConnection();
      pst =
          conn.prepareStatement(
              "select nvl(sum(a.log_catch_count),0) from twap_app_log_webcrawler a where exists(select 1 from twap_public_channel b where a.log_channel_id = b.channel_id start with b.channel_id=? connect by prior b.channel_id=b.channel_pid) and (to_char(a.create_time,'yyyy-mm-dd')<=? and to_char(a.create_time,'yyyy-mm-dd')>=?)");
      pst.setLong(1, channelId);
      pst.setString(3, startDate);
      pst.setString(2, endDate);
      rs = pst.executeQuery();
      if (rs.next()) size = rs.getLong(1);
    } catch (Exception e) {
      e.printStackTrace();
      log.error(e);
    } finally {
      close(conn, pst, rs);
    }

    return size;
  }

  public List<AppLog> getAppLogList(Long channelId, String startDate, String endDate) {
    List<AppLog> list = null;

    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

    try {
      conn = OracleUtil.getConnection();
      pst =
          conn.prepareStatement(
              "select rownum row_num,a.log_message,(select channel_name from twap_public_channel t where t.channel_id = a.log_channel_id) channel_name,a.log_channel_id,a.log_url,a.log_catch_count,to_char(a.create_time,'yy/mm/dd hh24:mi:ss') create_time  from twap_app_log_webcrawler a where exists(select 1 from twap_public_channel b where a.log_channel_id = b.channel_id start with b.channel_id=? connect by prior b.channel_id=b.channel_pid) and (to_char(a.create_time,'yyyy-mm-dd')<=? and to_char(a.create_time,'yyyy-mm-dd')>=?) order by a.create_time desc");
      pst.setLong(1, channelId);
      pst.setString(3, startDate);
      pst.setString(2, endDate);
      rs = pst.executeQuery();
      list = new ArrayList<AppLog>();
      while (rs.next()) {
        AppLog appLog =
            new AppLog(
                rs.getString("log_message"),
                rs.getLong("log_channel_id"),
                rs.getString("log_url"),
                rs.getLong("log_catch_count"));
        appLog.setChannelName(rs.getString("channel_name"));
        appLog.setCreateTime(rs.getString("create_time"));
        appLog.setLogId(rs.getLong("row_num"));
        list.add(appLog);
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error(e);
      rollback(conn);
    } finally {
      close(conn, pst, rs);
    }

    return list;
  }
}
Ejemplo n.º 25
0
/**
 * A single record from an Escher stream. Basically this a container for the header data for each
 * Escher record
 */
final class EscherRecordData {
  /** The logger */
  private static Logger logger = Logger.getLogger(EscherRecordData.class);

  /** The byte position of this record in the escher stream */
  private int pos;

  /** The instance value */
  private int instance;

  /** The version value */
  private int version;

  /** The record id */
  private int recordId;

  /** The length of the record, excluding the 8 byte header */
  private int length;

  /** The length of the stream */
  private int streamLength;

  /** Indicates whether this record is a container */
  private boolean container;

  /** The type of this record */
  private EscherRecordType type;

  /** A handle back to the drawing group, which contains the entire escher stream byte data */
  private EscherStream escherStream;

  /**
   * Constructor
   *
   * @param dg the escher stream data
   * @param p the current position in the stream
   */
  public EscherRecordData(EscherStream dg, int p) {
    escherStream = dg;
    pos = p;
    byte[] data = escherStream.getData();

    streamLength = data.length;

    // First two bytes contain instance and version
    int value = IntegerHelper.getInt(data[pos], data[pos + 1]);

    // Instance value is the first 12 bits
    instance = (value & 0xfff0) >> 4;

    // Version is the last four bits
    version = value & 0xf;

    // Bytes 2 and 3 are the record id
    recordId = IntegerHelper.getInt(data[pos + 2], data[pos + 3]);

    // Length is bytes 4,5,6 and 7
    length =
        IntegerHelper.getInt(
            data[pos + 4], data[pos + 5],
            data[pos + 6], data[pos + 7]);

    if (version == 0x0f) {
      container = true;
    } else {
      container = false;
    }
  }

  /**
   * Constructor
   *
   * @param t the type of the escher record
   */
  public EscherRecordData(EscherRecordType t) {
    type = t;
    recordId = type.getValue();
  }

  /**
   * Determines whether this record is a container
   *
   * @return TRUE if this is a container, FALSE otherwise
   */
  public boolean isContainer() {
    return container;
  }

  /**
   * Accessor for the length, excluding the 8 byte header
   *
   * @return the length excluding the 8 byte header
   */
  public int getLength() {
    return length;
  }

  /**
   * Accessor for the record id
   *
   * @return the record id
   */
  public int getRecordId() {
    return recordId;
  }

  /**
   * Accessor for the drawing group stream
   *
   * @return the drawing group stream
   */
  EscherStream getDrawingGroup() {
    return escherStream;
  }

  /**
   * Gets the position in the stream
   *
   * @return the position in the stream
   */
  int getPos() {
    return pos;
  }

  /**
   * Gets the escher type of this record
   *
   * @return the escher type
   */
  EscherRecordType getType() {
    if (type == null) {
      type = EscherRecordType.getType(recordId);
    }

    return type;
  }

  /**
   * Gets the instance value
   *
   * @return the instance value
   */
  int getInstance() {
    return instance;
  }

  /**
   * Sets whether or not this is a container - called when writing out an escher stream
   *
   * @param c TRUE if this is a container, FALSE otherwise
   */
  void setContainer(boolean c) {
    container = c;
  }

  /**
   * Called from the subclass when writing to set the instance value
   *
   * @param inst the instance
   */
  void setInstance(int inst) {
    instance = inst;
  }

  /**
   * Called when writing to set the length of this record
   *
   * @param l the length
   */
  void setLength(int l) {
    length = l;
  }

  /**
   * Called when writing to set the version of this record
   *
   * @param v the version
   */
  void setVersion(int v) {
    version = v;
  }

  /**
   * Adds the 8 byte header data on the value data passed in, returning the modified data
   *
   * @param d the value data
   * @return the value data with the header information
   */
  byte[] setHeaderData(byte[] d) {
    byte[] data = new byte[d.length + 8];
    System.arraycopy(d, 0, data, 8, d.length);

    if (container) {
      version = 0x0f;
    }

    // First two bytes contain instance and version
    int value = instance << 4;
    value |= version;
    IntegerHelper.getTwoBytes(value, data, 0);

    // Bytes 2 and 3 are the record id
    IntegerHelper.getTwoBytes(recordId, data, 2);

    // Length is bytes 4,5,6 and 7
    IntegerHelper.getFourBytes(d.length, data, 4);

    return data;
  }

  /**
   * Accessor for the header stream
   *
   * @return the escher stream
   */
  EscherStream getEscherStream() {
    return escherStream;
  }

  /**
   * Gets the data that was read in, excluding the header data
   *
   * @return the value data that was read in
   */
  byte[] getBytes() {
    byte[] d = new byte[length];
    System.arraycopy(escherStream.getData(), pos + 8, d, 0, length);
    return d;
  }

  /**
   * Accessor for the stream length
   *
   * @return the stream length
   */
  int getStreamLength() {
    return streamLength;
  }
}
Ejemplo n.º 26
0
  /**
   * Check all the merged cells for borders. If the merge record has borders, then we need to rejig
   * the cell formats to take account of this. This is called by the write method of the
   * WritableWorkbookImpl, so that any new XFRecords that are created may be written out with the
   * others
   */
  void checkMergedBorders() {
    Range[] mcells = mergedCells.getMergedCells();
    ArrayList borderFormats = new ArrayList();
    for (int mci = 0; mci < mcells.length; mci++) {
      Range range = mcells[mci];
      Cell topLeft = range.getTopLeft();
      XFRecord tlformat = (XFRecord) topLeft.getCellFormat();

      if (tlformat != null && tlformat.hasBorders() == true && !tlformat.isRead()) {
        try {
          CellXFRecord cf1 = new CellXFRecord(tlformat);
          Cell bottomRight = range.getBottomRight();

          cf1.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
          cf1.setBorder(
              Border.LEFT,
              tlformat.getBorderLine(Border.LEFT),
              tlformat.getBorderColour(Border.LEFT));
          cf1.setBorder(
              Border.TOP, tlformat.getBorderLine(Border.TOP), tlformat.getBorderColour(Border.TOP));

          if (topLeft.getRow() == bottomRight.getRow()) {
            cf1.setBorder(
                Border.BOTTOM,
                tlformat.getBorderLine(Border.BOTTOM),
                tlformat.getBorderColour(Border.BOTTOM));
          }

          if (topLeft.getColumn() == bottomRight.getColumn()) {
            cf1.setBorder(
                Border.RIGHT,
                tlformat.getBorderLine(Border.RIGHT),
                tlformat.getBorderColour(Border.RIGHT));
          }

          int index = borderFormats.indexOf(cf1);
          if (index != -1) {
            cf1 = (CellXFRecord) borderFormats.get(index);
          } else {
            borderFormats.add(cf1);
          }
          ((WritableCell) topLeft).setCellFormat(cf1);

          // Handle the bottom left corner
          if (bottomRight.getRow() > topLeft.getRow()) {
            // Handle the corner cell
            if (bottomRight.getColumn() != topLeft.getColumn()) {
              CellXFRecord cf2 = new CellXFRecord(tlformat);
              cf2.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf2.setBorder(
                  Border.LEFT,
                  tlformat.getBorderLine(Border.LEFT),
                  tlformat.getBorderColour(Border.LEFT));
              cf2.setBorder(
                  Border.BOTTOM,
                  tlformat.getBorderLine(Border.BOTTOM),
                  tlformat.getBorderColour(Border.BOTTOM));

              index = borderFormats.indexOf(cf2);
              if (index != -1) {
                cf2 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf2);
              }

              sheet.addCell(new Blank(topLeft.getColumn(), bottomRight.getRow(), cf2));
            }

            // Handle the cells down the left hand side (and along the
            // right too, if necessary)
            for (int i = topLeft.getRow() + 1; i < bottomRight.getRow(); i++) {
              CellXFRecord cf3 = new CellXFRecord(tlformat);
              cf3.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf3.setBorder(
                  Border.LEFT,
                  tlformat.getBorderLine(Border.LEFT),
                  tlformat.getBorderColour(Border.LEFT));

              if (topLeft.getColumn() == bottomRight.getColumn()) {
                cf3.setBorder(
                    Border.RIGHT,
                    tlformat.getBorderLine(Border.RIGHT),
                    tlformat.getBorderColour(Border.RIGHT));
              }

              index = borderFormats.indexOf(cf3);
              if (index != -1) {
                cf3 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf3);
              }

              sheet.addCell(new Blank(topLeft.getColumn(), i, cf3));
            }
          }

          // Handle the top right corner
          if (bottomRight.getColumn() > topLeft.getColumn()) {
            if (bottomRight.getRow() != topLeft.getRow()) {
              // Handle the corner cell
              CellXFRecord cf6 = new CellXFRecord(tlformat);
              cf6.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf6.setBorder(
                  Border.RIGHT,
                  tlformat.getBorderLine(Border.RIGHT),
                  tlformat.getBorderColour(Border.RIGHT));
              cf6.setBorder(
                  Border.TOP,
                  tlformat.getBorderLine(Border.TOP),
                  tlformat.getBorderColour(Border.TOP));
              index = borderFormats.indexOf(cf6);
              if (index != -1) {
                cf6 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf6);
              }

              sheet.addCell(new Blank(bottomRight.getColumn(), topLeft.getRow(), cf6));
            }

            // Handle the cells along the right
            for (int i = topLeft.getRow() + 1; i < bottomRight.getRow(); i++) {
              CellXFRecord cf7 = new CellXFRecord(tlformat);
              cf7.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf7.setBorder(
                  Border.RIGHT,
                  tlformat.getBorderLine(Border.RIGHT),
                  tlformat.getBorderColour(Border.RIGHT));

              index = borderFormats.indexOf(cf7);
              if (index != -1) {
                cf7 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf7);
              }

              sheet.addCell(new Blank(bottomRight.getColumn(), i, cf7));
            }

            // Handle the cells along the top, and along the bottom too
            for (int i = topLeft.getColumn() + 1; i < bottomRight.getColumn(); i++) {
              CellXFRecord cf8 = new CellXFRecord(tlformat);
              cf8.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf8.setBorder(
                  Border.TOP,
                  tlformat.getBorderLine(Border.TOP),
                  tlformat.getBorderColour(Border.TOP));

              if (topLeft.getRow() == bottomRight.getRow()) {
                cf8.setBorder(
                    Border.BOTTOM,
                    tlformat.getBorderLine(Border.BOTTOM),
                    tlformat.getBorderColour(Border.BOTTOM));
              }

              index = borderFormats.indexOf(cf8);
              if (index != -1) {
                cf8 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf8);
              }

              sheet.addCell(new Blank(i, topLeft.getRow(), cf8));
            }
          }

          // Handle the bottom right corner
          if (bottomRight.getColumn() > topLeft.getColumn()
              || bottomRight.getRow() > topLeft.getRow()) {
            // Handle the corner cell
            CellXFRecord cf4 = new CellXFRecord(tlformat);
            cf4.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
            cf4.setBorder(
                Border.RIGHT,
                tlformat.getBorderLine(Border.RIGHT),
                tlformat.getBorderColour(Border.RIGHT));
            cf4.setBorder(
                Border.BOTTOM,
                tlformat.getBorderLine(Border.BOTTOM),
                tlformat.getBorderColour(Border.BOTTOM));

            if (bottomRight.getRow() == topLeft.getRow()) {
              cf4.setBorder(
                  Border.TOP,
                  tlformat.getBorderLine(Border.TOP),
                  tlformat.getBorderColour(Border.TOP));
            }

            if (bottomRight.getColumn() == topLeft.getColumn()) {
              cf4.setBorder(
                  Border.LEFT,
                  tlformat.getBorderLine(Border.LEFT),
                  tlformat.getBorderColour(Border.LEFT));
            }

            index = borderFormats.indexOf(cf4);
            if (index != -1) {
              cf4 = (CellXFRecord) borderFormats.get(index);
            } else {
              borderFormats.add(cf4);
            }

            sheet.addCell(new Blank(bottomRight.getColumn(), bottomRight.getRow(), cf4));

            // Handle the cells along the bottom (and along the top
            // as well, if appropriate)
            for (int i = topLeft.getColumn() + 1; i < bottomRight.getColumn(); i++) {
              CellXFRecord cf5 = new CellXFRecord(tlformat);
              cf5.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf5.setBorder(
                  Border.BOTTOM,
                  tlformat.getBorderLine(Border.BOTTOM),
                  tlformat.getBorderColour(Border.BOTTOM));

              if (topLeft.getRow() == bottomRight.getRow()) {
                cf5.setBorder(
                    Border.TOP,
                    tlformat.getBorderLine(Border.TOP),
                    tlformat.getBorderColour(Border.TOP));
              }

              index = borderFormats.indexOf(cf5);
              if (index != -1) {
                cf5 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf5);
              }

              sheet.addCell(new Blank(i, bottomRight.getRow(), cf5));
            }
          }
        } catch (WriteException e) {
          // just log e.toString(), not the whole stack trace
          logger.warn(e.toString());
        }
      }
    }
  }
Ejemplo n.º 27
0
  @Override
  public void update() {
    logger.info("Updating gamecontroller");

    this.loadData();
  }
Ejemplo n.º 28
0
/**
 * Contains the functionality necessary for writing out a sheet. Originally this was incorporated in
 * WritableSheetImpl, but was moved out into a dedicated class in order to reduce the over bloated
 * nature of that class
 */
final class SheetWriter {
  /** The logger */
  private static Logger logger = Logger.getLogger(SheetWriter.class);

  /** A handle to the output file which the binary data is written to */
  private File outputFile;

  /** The rows within this sheet */
  private RowRecord[] rows;

  /** A number of rows. This is a count of the maximum row number + 1 */
  private int numRows;

  /** The number of columns. This is a count of the maximum column number + 1 */
  private int numCols;

  /** The page header */
  private HeaderRecord header;
  /** The page footer */
  private FooterRecord footer;
  /** The settings for the sheet */
  private SheetSettings settings;
  /** The settings for the workbook */
  private WorkbookSettings workbookSettings;
  /** Array of row page breaks */
  private ArrayList rowBreaks;
  /** Array of column page breaks */
  private ArrayList columnBreaks;
  /** Array of hyperlinks */
  private ArrayList hyperlinks;
  /** Array of conditional formats */
  private ArrayList conditionalFormats;
  /** The autofilter info */
  private AutoFilter autoFilter;
  /** Array of validated cells */
  private ArrayList validatedCells;
  /** The data validation validations */
  private DataValidation dataValidation;

  /** The list of merged ranges */
  private MergedCells mergedCells;

  /** The environment specific print record */
  private PLSRecord plsRecord;

  /** The button property ste */
  private ButtonPropertySetRecord buttonPropertySet;

  /** The workspace options */
  private WorkspaceInformationRecord workspaceOptions;
  /** The column format overrides */
  private TreeSet columnFormats;

  /** The list of drawings */
  private SheetDrawingWriter drawingWriter;

  /** Flag indicates that this sheet contains just a chart, and nothing else */
  private boolean chartOnly;

  /** The maximum row outline level */
  private int maxRowOutlineLevel;

  /** The maximum column outline level */
  private int maxColumnOutlineLevel;

  /**
   * A handle back to the writable sheet, in order for this class to invoke the get accessor methods
   */
  private WritableSheetImpl sheet;

  /**
   * Creates a new <code>SheetWriter</code> instance.
   *
   * @param of the output file
   */
  public SheetWriter(File of, WritableSheetImpl wsi, WorkbookSettings ws) {
    outputFile = of;
    sheet = wsi;
    workspaceOptions = new WorkspaceInformationRecord();
    workbookSettings = ws;
    chartOnly = false;
    drawingWriter = new SheetDrawingWriter(ws);
  }

  /**
   * Writes out this sheet. First writes out the standard sheet information then writes out each row
   * in turn. Once all the rows have been written out, it retrospectively adjusts the offset
   * references in the file
   *
   * @exception IOException
   */
  public void write() throws IOException {
    Assert.verify(rows != null);

    // This worksheet consists of just one chart, so write it and return
    if (chartOnly) {
      drawingWriter.write(outputFile);
      return;
    }

    BOFRecord bof = new BOFRecord(BOFRecord.sheet);
    outputFile.write(bof);

    // Compute the number of blocks of 32 rows that will be needed
    int numBlocks = numRows / 32;
    if (numRows - numBlocks * 32 != 0) {
      numBlocks++;
    }

    int indexPos = outputFile.getPos();

    // Write the index record out now in order to serve as a place holder
    // The bof passed in is the bof of the workbook, not this sheet
    IndexRecord indexRecord = new IndexRecord(0, numRows, numBlocks);
    outputFile.write(indexRecord);

    if (settings.getAutomaticFormulaCalculation()) {
      CalcModeRecord cmr = new CalcModeRecord(CalcModeRecord.automatic);
      outputFile.write(cmr);
    } else {
      CalcModeRecord cmr = new CalcModeRecord(CalcModeRecord.manual);
      outputFile.write(cmr);
    }

    CalcCountRecord ccr = new CalcCountRecord(0x64);
    outputFile.write(ccr);

    RefModeRecord rmr = new RefModeRecord();
    outputFile.write(rmr);

    IterationRecord itr = new IterationRecord(false);
    outputFile.write(itr);

    DeltaRecord dtr = new DeltaRecord(0.001);
    outputFile.write(dtr);

    SaveRecalcRecord srr = new SaveRecalcRecord(settings.getRecalculateFormulasBeforeSave());
    outputFile.write(srr);

    PrintHeadersRecord phr = new PrintHeadersRecord(settings.getPrintHeaders());
    outputFile.write(phr);

    PrintGridLinesRecord pglr = new PrintGridLinesRecord(settings.getPrintGridLines());
    outputFile.write(pglr);

    GridSetRecord gsr = new GridSetRecord(true);
    outputFile.write(gsr);

    GuttersRecord gutr = new GuttersRecord();
    gutr.setMaxColumnOutline(maxColumnOutlineLevel + 1);
    gutr.setMaxRowOutline(maxRowOutlineLevel + 1);

    outputFile.write(gutr);

    DefaultRowHeightRecord drhr =
        new DefaultRowHeightRecord(
            settings.getDefaultRowHeight(),
            settings.getDefaultRowHeight() != SheetSettings.DEFAULT_DEFAULT_ROW_HEIGHT);
    outputFile.write(drhr);

    if (maxRowOutlineLevel > 0) {
      workspaceOptions.setRowOutlines(true);
    }

    if (maxColumnOutlineLevel > 0) {
      workspaceOptions.setColumnOutlines(true);
    }

    workspaceOptions.setFitToPages(settings.getFitToPages());
    outputFile.write(workspaceOptions);

    if (rowBreaks.size() > 0) {
      int[] rb = new int[rowBreaks.size()];

      for (int i = 0; i < rb.length; i++) {
        rb[i] = ((Integer) rowBreaks.get(i)).intValue();
      }

      HorizontalPageBreaksRecord hpbr = new HorizontalPageBreaksRecord(rb);
      outputFile.write(hpbr);
    }

    if (columnBreaks.size() > 0) {
      int[] rb = new int[columnBreaks.size()];

      for (int i = 0; i < rb.length; i++) {
        rb[i] = ((Integer) columnBreaks.get(i)).intValue();
      }

      VerticalPageBreaksRecord hpbr = new VerticalPageBreaksRecord(rb);
      outputFile.write(hpbr);
    }

    HeaderRecord header = new HeaderRecord(settings.getHeader().toString());
    outputFile.write(header);

    FooterRecord footer = new FooterRecord(settings.getFooter().toString());
    outputFile.write(footer);

    HorizontalCentreRecord hcr = new HorizontalCentreRecord(settings.isHorizontalCentre());
    outputFile.write(hcr);

    VerticalCentreRecord vcr = new VerticalCentreRecord(settings.isVerticalCentre());
    outputFile.write(vcr);

    // Write out the margins if they don't equal the default
    if (settings.getLeftMargin() != settings.getDefaultWidthMargin()) {
      MarginRecord mr = new LeftMarginRecord(settings.getLeftMargin());
      outputFile.write(mr);
    }

    if (settings.getRightMargin() != settings.getDefaultWidthMargin()) {
      MarginRecord mr = new RightMarginRecord(settings.getRightMargin());
      outputFile.write(mr);
    }

    if (settings.getTopMargin() != settings.getDefaultHeightMargin()) {
      MarginRecord mr = new TopMarginRecord(settings.getTopMargin());
      outputFile.write(mr);
    }

    if (settings.getBottomMargin() != settings.getDefaultHeightMargin()) {
      MarginRecord mr = new BottomMarginRecord(settings.getBottomMargin());
      outputFile.write(mr);
    }

    if (plsRecord != null) {
      outputFile.write(plsRecord);
    }

    SetupRecord setup = new SetupRecord(settings);
    outputFile.write(setup);

    if (settings.isProtected()) {
      ProtectRecord pr = new ProtectRecord(settings.isProtected());
      outputFile.write(pr);

      ScenarioProtectRecord spr = new ScenarioProtectRecord(settings.isProtected());
      outputFile.write(spr);

      ObjectProtectRecord opr = new ObjectProtectRecord(settings.isProtected());
      outputFile.write(opr);

      if (settings.getPassword() != null) {
        PasswordRecord pw = new PasswordRecord(settings.getPassword());
        outputFile.write(pw);
      } else if (settings.getPasswordHash() != 0) {
        PasswordRecord pw = new PasswordRecord(settings.getPasswordHash());
        outputFile.write(pw);
      }
    }

    indexRecord.setDataStartPosition(outputFile.getPos());
    DefaultColumnWidth dcw = new DefaultColumnWidth(settings.getDefaultColumnWidth());
    outputFile.write(dcw);

    // Get a handle to the normal styles
    WritableCellFormat normalStyle = sheet.getWorkbook().getStyles().getNormalStyle();
    WritableCellFormat defaultDateFormat = sheet.getWorkbook().getStyles().getDefaultDateFormat();

    // Write out all the column formats
    ColumnInfoRecord cir = null;
    for (Iterator colit = columnFormats.iterator(); colit.hasNext(); ) {
      cir = (ColumnInfoRecord) colit.next();

      // Writing out the column info with index 0x100 causes excel to crash
      if (cir.getColumn() < 0x100) {
        outputFile.write(cir);
      }

      XFRecord xfr = cir.getCellFormat();

      if (xfr != normalStyle && cir.getColumn() < 0x100) {
        // Make this the format for every cell in the column
        Cell[] cells = getColumn(cir.getColumn());

        for (int i = 0; i < cells.length; i++) {
          if (cells[i] != null
              && (cells[i].getCellFormat() == normalStyle
                  || cells[i].getCellFormat() == defaultDateFormat)) {
            // The cell has no overriding format specified, so
            // set it to the column default
            ((WritableCell) cells[i]).setCellFormat(xfr);
          }
        }
      }
    }

    // Write out the auto filter
    if (autoFilter != null) {
      autoFilter.write(outputFile);
    }

    DimensionRecord dr = new DimensionRecord(numRows, numCols);
    outputFile.write(dr);

    // Write out all the rows, in blocks of 32
    for (int block = 0; block < numBlocks; block++) {
      DBCellRecord dbcell = new DBCellRecord(outputFile.getPos());

      int blockRows = Math.min(32, numRows - block * 32);
      boolean firstRow = true;

      // First write out all the row records
      for (int i = block * 32; i < block * 32 + blockRows; i++) {
        if (rows[i] != null) {
          rows[i].write(outputFile);
          if (firstRow) {
            dbcell.setCellOffset(outputFile.getPos());
            firstRow = false;
          }
        }
      }

      // Now write out all the cells
      for (int i = block * 32; i < block * 32 + blockRows; i++) {
        if (rows[i] != null) {
          dbcell.addCellRowPosition(outputFile.getPos());
          rows[i].writeCells(outputFile);
        }
      }

      // Now set the current file position in the index record
      indexRecord.addBlockPosition(outputFile.getPos());

      // Set the position of the file pointer and write out the DBCell
      // record
      dbcell.setPosition(outputFile.getPos());
      outputFile.write(dbcell);
    }

    // Do the drawings and charts if enabled
    if (!workbookSettings.getDrawingsDisabled()) {
      drawingWriter.write(outputFile);
    }

    Window2Record w2r = new Window2Record(settings);
    outputFile.write(w2r);

    // Handle the frozen panes
    if (settings.getHorizontalFreeze() != 0 || settings.getVerticalFreeze() != 0) {
      PaneRecord pr = new PaneRecord(settings.getHorizontalFreeze(), settings.getVerticalFreeze());
      outputFile.write(pr);

      // Handle the selection record.  First, there will always be a top left
      SelectionRecord sr = new SelectionRecord(SelectionRecord.upperLeft, 0, 0);
      outputFile.write(sr);

      // Top right
      if (settings.getHorizontalFreeze() != 0) {
        sr = new SelectionRecord(SelectionRecord.upperRight, settings.getHorizontalFreeze(), 0);
        outputFile.write(sr);
      }

      // Bottom left
      if (settings.getVerticalFreeze() != 0) {
        sr = new SelectionRecord(SelectionRecord.lowerLeft, 0, settings.getVerticalFreeze());
        outputFile.write(sr);
      }

      // Bottom right
      if (settings.getHorizontalFreeze() != 0 && settings.getVerticalFreeze() != 0) {
        sr =
            new SelectionRecord(
                SelectionRecord.lowerRight,
                settings.getHorizontalFreeze(),
                settings.getVerticalFreeze());
        outputFile.write(sr);
      }

      Weird1Record w1r = new Weird1Record();
      outputFile.write(w1r);
    } else {
      // No frozen panes - just write out the selection record for the
      // whole sheet
      SelectionRecord sr = new SelectionRecord(SelectionRecord.upperLeft, 0, 0);
      outputFile.write(sr);
    }

    // Handle the zoom factor
    if (settings.getZoomFactor() != 100) {
      SCLRecord sclr = new SCLRecord(settings.getZoomFactor());
      outputFile.write(sclr);
    }

    // Now write out all the merged cells
    mergedCells.write(outputFile);

    // Write out all the hyperlinks
    Iterator hi = hyperlinks.iterator();
    WritableHyperlink hlr = null;
    while (hi.hasNext()) {
      hlr = (WritableHyperlink) hi.next();
      outputFile.write(hlr);
    }

    if (buttonPropertySet != null) {
      outputFile.write(buttonPropertySet);
    }

    // Write out the data validations
    if (dataValidation != null || validatedCells.size() > 0) {
      writeDataValidation();
    }

    // Write out the conditional formats
    if (conditionalFormats != null && conditionalFormats.size() > 0) {
      for (Iterator i = conditionalFormats.iterator(); i.hasNext(); ) {
        ConditionalFormat cf = (ConditionalFormat) i.next();
        cf.write(outputFile);
      }
    }

    EOFRecord eof = new EOFRecord();
    outputFile.write(eof);

    // Now the various cross reference offsets have been calculated,
    // retrospectively set the values in the output file
    outputFile.setData(indexRecord.getData(), indexPos + 4);
  }

  /**
   * Gets the header. Called when copying sheets
   *
   * @return the page header
   */
  final HeaderRecord getHeader() {
    return header;
  }

  /**
   * Gets the footer. Called when copying sheets
   *
   * @return the page footer
   */
  final FooterRecord getFooter() {
    return footer;
  }

  /**
   * Sets the data necessary for writing out the sheet. This method must be called immediately prior
   * to writing
   *
   * @param rws the rows in the spreadsheet
   */
  void setWriteData(
      RowRecord[] rws,
      ArrayList rb,
      ArrayList cb,
      ArrayList hl,
      MergedCells mc,
      TreeSet cf,
      int mrol,
      int mcol) {
    rows = rws;
    rowBreaks = rb;
    columnBreaks = cb;
    hyperlinks = hl;
    mergedCells = mc;
    columnFormats = cf;
    maxRowOutlineLevel = mrol;
    maxColumnOutlineLevel = mcol;
  }

  /**
   * Sets the dimensions of this spreadsheet. This method must be called immediately prior to
   * writing
   *
   * @param rws the number of rows
   * @param cls the number of columns
   */
  void setDimensions(int rws, int cls) {
    numRows = rws;
    numCols = cls;
  }

  /**
   * Sets the sheet settings for this particular sheet. Must be called immediately prior to writing
   *
   * @param sr the sheet settings
   */
  void setSettings(SheetSettings sr) {
    settings = sr;
  }

  /**
   * Accessor for the workspace options
   *
   * @return the workspace options
   */
  WorkspaceInformationRecord getWorkspaceOptions() {
    return workspaceOptions;
  }

  /**
   * Accessor for the workspace options
   *
   * @param wo the workspace options
   */
  void setWorkspaceOptions(WorkspaceInformationRecord wo) {
    if (wo != null) {
      workspaceOptions = wo;
    }
  }

  /**
   * Sets the charts for this sheet
   *
   * @param ch the charts
   */
  void setCharts(Chart[] ch) {
    drawingWriter.setCharts(ch);
  }

  /**
   * Sets the drawings on this sheet
   *
   * @param dr the list of drawings
   * @param mod a modified flag
   */
  void setDrawings(ArrayList dr, boolean mod) {
    drawingWriter.setDrawings(dr, mod);
  }

  /**
   * Accessor for the charts on this sheet
   *
   * @return the charts
   */
  Chart[] getCharts() {
    return drawingWriter.getCharts();
  }

  /**
   * Check all the merged cells for borders. If the merge record has borders, then we need to rejig
   * the cell formats to take account of this. This is called by the write method of the
   * WritableWorkbookImpl, so that any new XFRecords that are created may be written out with the
   * others
   */
  void checkMergedBorders() {
    Range[] mcells = mergedCells.getMergedCells();
    ArrayList borderFormats = new ArrayList();
    for (int mci = 0; mci < mcells.length; mci++) {
      Range range = mcells[mci];
      Cell topLeft = range.getTopLeft();
      XFRecord tlformat = (XFRecord) topLeft.getCellFormat();

      if (tlformat != null && tlformat.hasBorders() == true && !tlformat.isRead()) {
        try {
          CellXFRecord cf1 = new CellXFRecord(tlformat);
          Cell bottomRight = range.getBottomRight();

          cf1.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
          cf1.setBorder(
              Border.LEFT,
              tlformat.getBorderLine(Border.LEFT),
              tlformat.getBorderColour(Border.LEFT));
          cf1.setBorder(
              Border.TOP, tlformat.getBorderLine(Border.TOP), tlformat.getBorderColour(Border.TOP));

          if (topLeft.getRow() == bottomRight.getRow()) {
            cf1.setBorder(
                Border.BOTTOM,
                tlformat.getBorderLine(Border.BOTTOM),
                tlformat.getBorderColour(Border.BOTTOM));
          }

          if (topLeft.getColumn() == bottomRight.getColumn()) {
            cf1.setBorder(
                Border.RIGHT,
                tlformat.getBorderLine(Border.RIGHT),
                tlformat.getBorderColour(Border.RIGHT));
          }

          int index = borderFormats.indexOf(cf1);
          if (index != -1) {
            cf1 = (CellXFRecord) borderFormats.get(index);
          } else {
            borderFormats.add(cf1);
          }
          ((WritableCell) topLeft).setCellFormat(cf1);

          // Handle the bottom left corner
          if (bottomRight.getRow() > topLeft.getRow()) {
            // Handle the corner cell
            if (bottomRight.getColumn() != topLeft.getColumn()) {
              CellXFRecord cf2 = new CellXFRecord(tlformat);
              cf2.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf2.setBorder(
                  Border.LEFT,
                  tlformat.getBorderLine(Border.LEFT),
                  tlformat.getBorderColour(Border.LEFT));
              cf2.setBorder(
                  Border.BOTTOM,
                  tlformat.getBorderLine(Border.BOTTOM),
                  tlformat.getBorderColour(Border.BOTTOM));

              index = borderFormats.indexOf(cf2);
              if (index != -1) {
                cf2 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf2);
              }

              sheet.addCell(new Blank(topLeft.getColumn(), bottomRight.getRow(), cf2));
            }

            // Handle the cells down the left hand side (and along the
            // right too, if necessary)
            for (int i = topLeft.getRow() + 1; i < bottomRight.getRow(); i++) {
              CellXFRecord cf3 = new CellXFRecord(tlformat);
              cf3.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf3.setBorder(
                  Border.LEFT,
                  tlformat.getBorderLine(Border.LEFT),
                  tlformat.getBorderColour(Border.LEFT));

              if (topLeft.getColumn() == bottomRight.getColumn()) {
                cf3.setBorder(
                    Border.RIGHT,
                    tlformat.getBorderLine(Border.RIGHT),
                    tlformat.getBorderColour(Border.RIGHT));
              }

              index = borderFormats.indexOf(cf3);
              if (index != -1) {
                cf3 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf3);
              }

              sheet.addCell(new Blank(topLeft.getColumn(), i, cf3));
            }
          }

          // Handle the top right corner
          if (bottomRight.getColumn() > topLeft.getColumn()) {
            if (bottomRight.getRow() != topLeft.getRow()) {
              // Handle the corner cell
              CellXFRecord cf6 = new CellXFRecord(tlformat);
              cf6.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf6.setBorder(
                  Border.RIGHT,
                  tlformat.getBorderLine(Border.RIGHT),
                  tlformat.getBorderColour(Border.RIGHT));
              cf6.setBorder(
                  Border.TOP,
                  tlformat.getBorderLine(Border.TOP),
                  tlformat.getBorderColour(Border.TOP));
              index = borderFormats.indexOf(cf6);
              if (index != -1) {
                cf6 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf6);
              }

              sheet.addCell(new Blank(bottomRight.getColumn(), topLeft.getRow(), cf6));
            }

            // Handle the cells along the right
            for (int i = topLeft.getRow() + 1; i < bottomRight.getRow(); i++) {
              CellXFRecord cf7 = new CellXFRecord(tlformat);
              cf7.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf7.setBorder(
                  Border.RIGHT,
                  tlformat.getBorderLine(Border.RIGHT),
                  tlformat.getBorderColour(Border.RIGHT));

              index = borderFormats.indexOf(cf7);
              if (index != -1) {
                cf7 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf7);
              }

              sheet.addCell(new Blank(bottomRight.getColumn(), i, cf7));
            }

            // Handle the cells along the top, and along the bottom too
            for (int i = topLeft.getColumn() + 1; i < bottomRight.getColumn(); i++) {
              CellXFRecord cf8 = new CellXFRecord(tlformat);
              cf8.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf8.setBorder(
                  Border.TOP,
                  tlformat.getBorderLine(Border.TOP),
                  tlformat.getBorderColour(Border.TOP));

              if (topLeft.getRow() == bottomRight.getRow()) {
                cf8.setBorder(
                    Border.BOTTOM,
                    tlformat.getBorderLine(Border.BOTTOM),
                    tlformat.getBorderColour(Border.BOTTOM));
              }

              index = borderFormats.indexOf(cf8);
              if (index != -1) {
                cf8 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf8);
              }

              sheet.addCell(new Blank(i, topLeft.getRow(), cf8));
            }
          }

          // Handle the bottom right corner
          if (bottomRight.getColumn() > topLeft.getColumn()
              || bottomRight.getRow() > topLeft.getRow()) {
            // Handle the corner cell
            CellXFRecord cf4 = new CellXFRecord(tlformat);
            cf4.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
            cf4.setBorder(
                Border.RIGHT,
                tlformat.getBorderLine(Border.RIGHT),
                tlformat.getBorderColour(Border.RIGHT));
            cf4.setBorder(
                Border.BOTTOM,
                tlformat.getBorderLine(Border.BOTTOM),
                tlformat.getBorderColour(Border.BOTTOM));

            if (bottomRight.getRow() == topLeft.getRow()) {
              cf4.setBorder(
                  Border.TOP,
                  tlformat.getBorderLine(Border.TOP),
                  tlformat.getBorderColour(Border.TOP));
            }

            if (bottomRight.getColumn() == topLeft.getColumn()) {
              cf4.setBorder(
                  Border.LEFT,
                  tlformat.getBorderLine(Border.LEFT),
                  tlformat.getBorderColour(Border.LEFT));
            }

            index = borderFormats.indexOf(cf4);
            if (index != -1) {
              cf4 = (CellXFRecord) borderFormats.get(index);
            } else {
              borderFormats.add(cf4);
            }

            sheet.addCell(new Blank(bottomRight.getColumn(), bottomRight.getRow(), cf4));

            // Handle the cells along the bottom (and along the top
            // as well, if appropriate)
            for (int i = topLeft.getColumn() + 1; i < bottomRight.getColumn(); i++) {
              CellXFRecord cf5 = new CellXFRecord(tlformat);
              cf5.setBorder(Border.ALL, BorderLineStyle.NONE, Colour.BLACK);
              cf5.setBorder(
                  Border.BOTTOM,
                  tlformat.getBorderLine(Border.BOTTOM),
                  tlformat.getBorderColour(Border.BOTTOM));

              if (topLeft.getRow() == bottomRight.getRow()) {
                cf5.setBorder(
                    Border.TOP,
                    tlformat.getBorderLine(Border.TOP),
                    tlformat.getBorderColour(Border.TOP));
              }

              index = borderFormats.indexOf(cf5);
              if (index != -1) {
                cf5 = (CellXFRecord) borderFormats.get(index);
              } else {
                borderFormats.add(cf5);
              }

              sheet.addCell(new Blank(i, bottomRight.getRow(), cf5));
            }
          }
        } catch (WriteException e) {
          // just log e.toString(), not the whole stack trace
          logger.warn(e.toString());
        }
      }
    }
  }

  /**
   * Get the cells in the column. Don't use the interface method getColumn for this as this will
   * create loads of empty cells, and we could do without that overhead
   */
  private Cell[] getColumn(int col) {
    // Find the last non-null cell
    boolean found = false;
    int row = numRows - 1;

    while (row >= 0 && !found) {
      if (rows[row] != null && rows[row].getCell(col) != null) {
        found = true;
      } else {
        row--;
      }
    }

    // Only create entries for non-empty cells
    Cell[] cells = new Cell[row + 1];

    for (int i = 0; i <= row; i++) {
      cells[i] = rows[i] != null ? rows[i].getCell(col) : null;
    }

    return cells;
  }

  /** Sets a flag to indicate that this sheet contains a chart only */
  void setChartOnly() {
    chartOnly = true;
  }

  /**
   * Sets the environment specific print record
   *
   * @param pls the print record
   */
  void setPLS(PLSRecord pls) {
    plsRecord = pls;
  }

  /**
   * Sets the button property set record
   *
   * @param bps the button property set
   */
  void setButtonPropertySet(ButtonPropertySetRecord bps) {
    buttonPropertySet = bps;
  }

  /**
   * Sets the data validations
   *
   * @param dv the read-in list of data validations
   * @param vc the api manipulated set of data validations
   */
  void setDataValidation(DataValidation dv, ArrayList vc) {
    dataValidation = dv;
    validatedCells = vc;
  }

  /**
   * Sets the conditional formats
   *
   * @param cf the conditonal formats
   */
  void setConditionalFormats(ArrayList cf) {
    conditionalFormats = cf;
  }

  /**
   * Sets the auto filter
   *
   * @param af the autofilter
   */
  void setAutoFilter(AutoFilter af) {
    autoFilter = af;
  }

  /** Writes out the data validations */
  private void writeDataValidation() throws IOException {
    if (dataValidation != null && validatedCells.size() == 0) {
      // only data validations are those read in
      dataValidation.write(outputFile);
      return;
    }

    if (dataValidation == null && validatedCells.size() > 0) {
      int comboBoxId =
          sheet.getComboBox() != null
              ? sheet.getComboBox().getObjectId()
              : DataValidation.DEFAULT_OBJECT_ID;
      dataValidation =
          new DataValidation(
              comboBoxId, sheet.getWorkbook(), sheet.getWorkbook(), workbookSettings);

      for (Iterator i = validatedCells.iterator(); i.hasNext(); ) {
        CellValue cv = (CellValue) i.next();
        CellFeatures cf = cv.getCellFeatures();
        DataValiditySettingsRecord dvsr = new DataValiditySettingsRecord(cf.getDVParser());
        dataValidation.add(dvsr);
      }
      dataValidation.write(outputFile);
      return;
    }

    // Read and write validations
    for (Iterator i = validatedCells.iterator(); i.hasNext(); ) {
      CellValue cv = (CellValue) i.next();
      CellFeatures cf = cv.getCellFeatures();
      DataValiditySettingsRecord dvsr = new DataValiditySettingsRecord(cf.getDVParser());
      dataValidation.add(dvsr);
    }
    dataValidation.write(outputFile);
    return;
  }
}
Ejemplo n.º 29
0
/**
 * WARNING! All factories of instances of this class guarantee, that there won't be generated two
 * different instances with equal handles and equal contexts. Actually all factories are lazy, and
 * class contains it's own implementation of memory management above native one. Also all
 * constructors are private.
 *
 * <p>Box for determining an element (by it's WebHandle) and what exactly to do with it. Aka node in
 * EFG. .equals(obj) and .hashCode() are overrided Created by user on 7/23/15.
 */
public class Event extends Tickable {
  private static Logger log = Logger.get(new Event(new WebHandle(JetURL.createOwn404(), ""), null));
  /** This implements "memory-management" claimed above. */
  private static HashMap<Event, Event> memory = new HashMap<>();

  private final int
      hash; // should be stored until all affecting values (context and handle) are final
  /** To do smth with element we have to find it. WebHandle helps to find=) */
  public final WebHandle handle;
  /** If element is writable, this string contains, what we are going to type in. */
  public final String context;

  /** Should be called in the end of every public factory */
  private static Event creationFinalizer(Event event) {
    if (memory.containsKey(event)) return memory.get(event);
    memory.put(event, event);
    return event;
  }

  /** Just a constructor. Fills hash field. */
  private Event(WebHandle handle, String context) {
    this.handle = handle;
    this.context = context;
    hash = handle.hashCode() + Utils.hashString(context) * 239;
  }

  /** Factory method for convenient creating of root element. Will be terminal */
  public static Event createRoot(String url) {
    return create(WebHandle.createRootHandle(new JetURL(url)), "");
  }

  public static Event create(WebHandle handle, String context) {
    return creationFinalizer(new Event(handle, context));
  }

  /**
   * @param list handles to operate with in Event-s
   * @return List of Event-s, consisting of operations with web-elements specified by handles. E.g.
   *     "click" or "write abacaba"
   */
  public static List<Event> generateTestEvents(List<WebHandle> list) {
    // TODO here parameters of generated events can be specified
    // TODO writable are determined as clickable for a while
    List<Event> result = new ArrayList<>();
    for (WebHandle handle : list) result.add(creationFinalizer(new Event(handle, "")));
    return result;
  }

  /**
   * Performs event in specified WebDriver
   *
   * @param driver WebDriver to perform in
   * @return true in case of success (Element existed and was visible)
   */
  public boolean perform(WebDriver driver) {
    return perform(handle, driver);
  }

  /**
   * This static one is pretty useful for using from inside of checker in Scanner, cause Event can't
   * be constructed in that moment. For other usage refer to {@link #perform(WebDriver)}
   *
   * @param driver WebDriver to perform in
   * @param handle handle with which event will be performed
   * @return true in case of success (Element existed and was visible)
   */
  // TODO this requires redesign for writables
  public static boolean perform(WebHandle handle, WebDriver driver) {
    WebElement we = handle.findElement(driver);
    if (we == null) {
      // TODO this place strongly interferes with driver's implicitly wait. So, I think, personal
      // fails counter per handle needed.
      log.error(
          handle.url.graphUrl()
              + " | "
              + handle.xpath
              + "\n"
              + "Unable to .perform(WebDriver), cause search of element by stored selector is failed.");
      return false;
    }
    if (!we.isDisplayed() || !we.isEnabled()) {
      log.error(
          handle.url.graphUrl()
              + " | "
              + handle.xpath
              + "\n"
              + "Failed to .perform(WebDriver), cause element not displayed or not enabled.");
      return false;
    }
    switch (handle.eltype) {
      case clickable:
        we.click();
        break;
        //            case writable: we.sendKeys(context); break;
      case terminal:
        if (handle.isRoot()) return true;
        assert false : "terminal elements was touched";
        break;
      default:
        assert false : "this shouldn't have happened???";
        break;
    }
    return true;
  }

  @Override
  public int hashCode() {
    return hash;
  }

  @Override
  public boolean equals(Object obj) {
    return obj instanceof Event
        && context.equals(((Event) obj).context)
        && handle.equals(((Event) obj).handle);
  }

  @Override
  public String toString() {
    return handle + (context.length() == 0 ? "" : " (" + context + ")");
  }
}
Ejemplo n.º 30
0
public class GameController implements UpdateableView {

  private Game actualGame = new Game();
  private GameService gameService;
  private List<SelectItem> units;
  private List<SelectItem> configurables;
  private boolean editingGame = false;
  private boolean settingGame = false;

  private long productionTime = 0;
  private long duration = 0;
  private long lowerThreshold = 0;
  private long upperThreshold = 0;

  private long durationUnitDivider = 1000;
  private long productionUnitDivider = 1000;
  private long lowerThresholdUnitDivider = 1000;
  private long upperThresholdUnitDivider = 1000;

  private UIData gamesTable;
  private List<Game> games = new ArrayList<Game>();

  private static final String SEGS = "segs";
  private static final String MINS = "mins";
  private static final String HRS = "hrs";
  private static final String DAYS = "días";

  private String durationUnit = SEGS;
  private String productionTimeUnit = SEGS;
  private String thresholdEventsUnit = SEGS;

  private static final String FACTORES_LABEL = "Factores";
  private static final String RECURSOS_LABEL = "Materiales";
  private static final String POBLACION_LABEL = "Población";
  private static final String EVENTS_LABEL = "Eventos";

  private Logger logger = Logger.getLogger(GameController.class);

  private String[] unitsNames = {SEGS, MINS, HRS, DAYS};
  private String[] configurableThings = {
    FACTORES_LABEL, RECURSOS_LABEL, POBLACION_LABEL, EVENTS_LABEL
  };

  public List<SelectItem> getUnits() {
    units = UtopiaUtil.getItems(unitsNames);

    return units;
  }

  @PostConstruct
  public void loadData() {
    games = gameService.findAllGames();
    logger.info("Retreaving all games ...");
    for (Game game : games) {
      logger.info("Game ..." + game.getName() + "  date " + game.getStartTime());
    }
  }

  public void newGame(javax.faces.event.ActionEvent event) {
    editingGame = true;
    actualGame = new Game();

    clearTemporalValues();
  }

  public void saveGame(javax.faces.event.ActionEvent event) {
    editingGame = false;
    long result = 0;

    result = getMilsec(durationUnit, duration);

    actualGame.setDuration(result);

    result = getMilsec(thresholdEventsUnit, lowerThreshold);

    actualGame.setLowerThreshold(result);

    result = getMilsec(thresholdEventsUnit, upperThreshold);

    actualGame.setUpperThreshold(result);

    result = getMilsec(productionTimeUnit, productionTime);

    actualGame.setProductionTime(result);

    gameService.save(actualGame);
    actualGame = new Game();
    games = gameService.findAllGames();

    clearTemporalValues();
  }

  private void clearTemporalValues() {
    productionTime = 0;
    upperThreshold = 0;
    lowerThreshold = 0;
    duration = 0;
  }

  private long getMilsec(String unit, long time) {
    long result = 0;

    if (unit == null || time <= 0) return 0;

    if (SEGS.equalsIgnoreCase(unit)) {
      result = TimeUnit.SECONDS.toMillis(time);
      return result;
    }

    if (MINS.equalsIgnoreCase(unit)) {
      result = TimeUnit.MINUTES.toMillis(time);
      return result;
    }

    if (HRS.equalsIgnoreCase(unit)) {
      result = TimeUnit.HOURS.toMillis(time);
      return result;
    }

    if (DAYS.equalsIgnoreCase(unit)) {
      result = TimeUnit.DAYS.toMillis(time);
      return result;
    }

    return 0;
  }

  public void settingUpGame(javax.faces.event.ActionEvent event) {
    settingGame = true;
    int selectedRowIndex = gamesTable.getRowIndex();
    actualGame = games.get(selectedRowIndex);
    logger.info("selected game " + actualGame.getName());

    transformToActualUnits();
  }

  public void settingUpPlayers(javax.faces.event.ActionEvent event) {
    int selectedRowIndex = gamesTable.getRowIndex();
    actualGame = games.get(selectedRowIndex);
    logger.info("selected game " + actualGame.getName());
  }

  public void listGames(javax.faces.event.ActionEvent event) {
    settingGame = false;
    games = gameService.findAllGames();
  }

  public void changeTimeUnit(ValueChangeEvent event) {
    logger.info(
        "UI Component Id " + event.getComponent().getId() + " new value " + event.getNewValue());

    String idComponent = event.getComponent().getId();
    String unit = event.getNewValue().toString();

    if (idComponent.startsWith("somGameDuration")) {
      this.durationUnit = unit;
    }

    if (idComponent.startsWith("somProductionTime")) {
      this.productionTimeUnit = unit;
    }

    if (idComponent.startsWith("somEnventTime")) {
      this.thresholdEventsUnit = unit;
    }

    transformToActualUnits();
  }

  private long calculateUnitDivider(String unit) {
    long result = 1;

    if (unit == null) return 1;

    if (SEGS.equalsIgnoreCase(unit)) {
      result = 1000;
      return result;
    }

    if (MINS.equalsIgnoreCase(unit)) {
      result = 1000 * 60;
      return result;
    }

    if (HRS.equalsIgnoreCase(unit)) {
      result = 1000 * 60 * 60;
      return result;
    }

    if (DAYS.equalsIgnoreCase(unit)) {
      result = 1000 * 60 * 60 * 24;
      return result;
    }

    return result;
  }

  public void editGame(javax.faces.event.ActionEvent event) {
    editingGame = true;
    int selectedRowIndex = gamesTable.getRowIndex();
    actualGame = games.get(selectedRowIndex);

    transformToActualUnits();
  }

  private void transformToActualUnits() {
    durationUnitDivider = calculateUnitDivider(durationUnit);
    productionUnitDivider = calculateUnitDivider(productionTimeUnit);
    upperThresholdUnitDivider =
        lowerThresholdUnitDivider = calculateUnitDivider(thresholdEventsUnit);

    duration = actualGame.getDuration() / durationUnitDivider;
    lowerThreshold = actualGame.getLowerThreshold() / productionUnitDivider;
    upperThreshold = actualGame.getUpperThreshold() / upperThresholdUnitDivider;
    productionTime = actualGame.getProductionTime() / upperThresholdUnitDivider;
  }

  public void deleteGame(javax.faces.event.ActionEvent event) {
    editingGame = false;
    int selectedRowIndex = gamesTable.getRowIndex();
    actualGame = games.get(selectedRowIndex);
    gameService.delete(actualGame);
    actualGame = new Game();
    games = gameService.findAllGames();
  }

  public void cancelEditing(javax.faces.event.ActionEvent event) {
    editingGame = false;
    actualGame = new Game();
  }

  public void setActualGame(Game actualGame) {
    this.actualGame = actualGame;
  }

  public Game getActualGame() {

    return (this.actualGame);
  }

  public String[] getUnitsNames() {

    return (this.unitsNames);
  }

  public void setUnitsNames(String[] unitsNames) {
    this.unitsNames = unitsNames;
  }

  public void setUnits(List<SelectItem> units) {
    this.units = units;
  }

  public void setEditingGame(boolean editingGame) {
    this.editingGame = editingGame;
  }

  public boolean isEditingGame() {

    return (this.editingGame);
  }

  public void setGamesTable(UIData gamesTable) {
    this.gamesTable = gamesTable;
  }

  public UIData getGamesTable() {

    return (this.gamesTable);
  }

  public void setGames(List<Game> games) {
    this.games = games;
  }

  public List<Game> getGames() {

    return (this.games);
  }

  public void setGameService(GameService gameService) {
    this.gameService = gameService;
  }

  public GameService getGameService() {

    return (this.gameService);
  }

  public void setSettingGame(boolean settingGame) {
    this.settingGame = settingGame;
  }

  public boolean isSettingGame() {

    return (this.settingGame);
  }

  public void setConfigurables(List<SelectItem> configurables) {
    this.configurables = configurables;
  }

  public List<SelectItem> getConfigurables() {
    configurables = UtopiaUtil.getItems(configurableThings);

    return configurables;
  }

  public void setProductionTime(long productionTime) {
    this.productionTime = productionTime;
  }

  public long getProductionTime() {

    return (this.productionTime);
  }

  public void setDuration(long duration) {
    this.duration = duration;
  }

  public long getDuration() {

    return (this.duration);
  }

  public void setDurationUnit(String durationUnit) {
    this.durationUnit = durationUnit;
  }

  public String getDurationUnit() {

    return (this.durationUnit);
  }

  public void setProductionTimeUnit(String productionTimeUnit) {
    this.productionTimeUnit = productionTimeUnit;
  }

  public String getProductionTimeUnit() {

    return (this.productionTimeUnit);
  }

  public void setThresholdEventsUnit(String thresholdEventsUnit) {
    this.thresholdEventsUnit = thresholdEventsUnit;
  }

  public String getThresholdEventsUnit() {

    return (this.thresholdEventsUnit);
  }

  public void setLowerThreshold(long lowerThreshold) {
    this.lowerThreshold = lowerThreshold;
  }

  public long getLowerThreshold() {

    return (this.lowerThreshold);
  }

  public void setUpperThreshold(long upperThreshold) {
    this.upperThreshold = upperThreshold;
  }

  public long getUpperThreshold() {

    return (this.upperThreshold);
  }

  public long getDurationUnitDivider() {

    return (this.durationUnitDivider);
  }

  public long getProductionUnitDivider() {

    return (this.productionUnitDivider);
  }

  public long getLowerThresholdUnitDivider() {

    return (this.lowerThresholdUnitDivider);
  }

  public long getUpperThresholdUnitDivider() {

    return (this.upperThresholdUnitDivider);
  }

  public void setDurationUnitDivider(long durationUnitDivider) {
    this.durationUnitDivider = durationUnitDivider;
  }

  public void setProductionUnitDivider(long productionUnitDivider) {
    this.productionUnitDivider = productionUnitDivider;
  }

  public void setLowerThresholdUnitDivider(long lowerThresholdUnitDivider) {
    this.lowerThresholdUnitDivider = lowerThresholdUnitDivider;
  }

  public void setUpperThresholdUnitDivider(long upperThresholdUnitDivider) {
    this.upperThresholdUnitDivider = upperThresholdUnitDivider;
  }

  @Override
  public void update() {
    logger.info("Updating gamecontroller");

    this.loadData();
  }
}