/**
   * Returns date in the format: neededDatePattern, in case if year or month isn't entered, current
   * year/month is put.
   *
   * @return correct date.
   */
  private Date getCorrectedDate(String enteredDate) {
    Queue<String> dateParts = new ArrayDeque<>(3);
    StringBuilder number = new StringBuilder();
    for (char symbol : enteredDate.toCharArray()) {
      if (Character.isDigit(symbol)) {
        number.append(symbol);
      } else if (number.length() > 0) {
        dateParts.add(number.toString());
        number = new StringBuilder();
      }
    }
    if (number.length() > 0) {
      dateParts.add(number.toString());
    }

    Calendar currentDate = Calendar.getInstance();
    switch (dateParts.size()) {
      case 1:
        dateParts.add(Integer.toString(currentDate.get(Calendar.MONTH) + 1));
      case 2:
        dateParts.add(Integer.toString(currentDate.get(Calendar.YEAR)));
    }

    try {
      return new SimpleDateFormat("dd.MM.yyyy")
          .parse(dateParts.remove() + '.' + dateParts.remove() + '.' + dateParts.remove());

    } catch (ParseException e) {
      throw new RuntimeException(e); // todo change exception
    }
  }
 private void initCalPanel() {
   int year = cal.get(Calendar.YEAR);
   int month = cal.get(Calendar.MONTH);
   int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
   int mark = 1;
   int firstDayOfWeek = new GregorianCalendar(year, month, 1).get(Calendar.DAY_OF_WEEK);
   panel.setLayout(null);
   panel.setBackground(Color.WHITE);
   String[] week = {"日", "一", "二", "三", "四", "五", "六"};
   for (int i = 0; i < 7; i++) {
     addLabelOnPanel(i, week[i], false);
   }
   for (int i = 1; i < firstDayOfWeek; i++) {
     startPoint_x += 40;
   }
   for (int i = firstDayOfWeek - 1; i < 7; i++) {
     addLabelOnPanel(i, "" + mark++, true);
   }
   while (mark <= maxDay) {
     for (int i = 0; i < 7; i++) {
       addLabelOnPanel(i, "" + mark++, true);
       if (mark >= maxDay) break;
     }
   }
 }
Пример #3
1
  /** Initializes contained components. */
  private void initComponents() {
    final SimpleDateFormat format = new SimpleDateFormat("mm:ss");
    final Calendar c = Calendar.getInstance();
    final JLabel counter = new JLabel();

    counter.setForeground(Color.red);
    counter.setFont(counter.getFont().deriveFont((float) (counter.getFont().getSize() + 5)));

    setLayout(new GridBagLayout());
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    GridBagConstraints constraints = new GridBagConstraints();

    JLabel messageLabel =
        new JLabel(
            GuiActivator.getResources().getI18NString("service.gui.security.SECURITY_ALERT"));

    messageLabel.setForeground(Color.WHITE);

    constraints.anchor = GridBagConstraints.CENTER;
    constraints.fill = GridBagConstraints.NONE;
    constraints.gridx = 0;
    constraints.gridy = 0;
    add(messageLabel, constraints);

    constraints.anchor = GridBagConstraints.CENTER;
    constraints.fill = GridBagConstraints.NONE;
    constraints.gridx = 0;
    constraints.gridy = 1;
    add(counter, constraints);

    ZrtpControl zrtpControl = null;
    if (securityControl instanceof ZrtpControl) zrtpControl = (ZrtpControl) securityControl;

    long initialSeconds = 0;

    if (zrtpControl != null) initialSeconds = zrtpControl.getTimeoutValue();

    c.setTimeInMillis(initialSeconds);

    counter.setText(format.format(c.getTime()));

    if (initialSeconds > 0)
      timer.schedule(
          new TimerTask() {
            @Override
            public void run() {
              if (c.getTimeInMillis() - 1000 > 0) {
                c.add(Calendar.SECOND, -1);
                counter.setText(format.format(c.getTime()));
              }
            }
          },
          1000,
          1000);
  }
  /** Resets controls to their initial state */
  private void reset(ActionEvent event) {
    this.queryTime.setTime(new Date());
    String day = String.format("%02d", queryTime.get(queryTime.DAY_OF_MONTH));
    String month = String.format("%02d", queryTime.get(queryTime.MONTH) + 1);
    jTextDate.setText(day + "-" + month + "-" + queryTime.get(queryTime.YEAR));

    this.jButtonSetFound.setEnabled(false);
    this.jButtonSetLost.setEnabled(false);
    this.jListPackages.setListData(new Vector());
    this.jListScans.setListData(new Vector());
  }
Пример #5
1
 /**
  * Updates the data set for both charts with the contents of the supplied Hashtable. The Hashtable
  * is expected to contain the following items:
  *
  * <ul>
  *   <li>down - The number of links currently in a down state
  *   <li>up - The number of links currently in an up state
  *   <li>unknown - The number of links currently in an unknown state
  * </ul>
  *
  * @param linkStats The hashtable containing the entries indicating current link statistics.
  */
 public void updateData(Hashtable<String, Integer> linkStats) {
   dpdCurrentData.insertValue(0, "Link Down", linkStats.get("down"));
   dpdCurrentData.insertValue(1, "Link Up", linkStats.get("up"));
   dpdCurrentData.insertValue(2, "Link State Unknown", linkStats.get("unknown"));
   dcdPreviousData.addValue(
       linkStats.get("down"), "Link Down", Calendar.getInstance().getTime().toString());
   dcdPreviousData.addValue(
       linkStats.get("up"), "Link Up", Calendar.getInstance().getTime().toString());
   dcdPreviousData.addValue(
       linkStats.get("unknown"),
       "Link State Unknown",
       Calendar.getInstance().getTime().toString());
 }
 public ArtifactView(DataProvider provider) {
   this(
       new Artifact(
           new DateTime(
               Calendar.getInstance().getTime(), DateFormat.getDateInstance(DateFormat.MEDIUM)),
           new DateTime(
               Calendar.getInstance().getTime(), DateFormat.getDateInstance(DateFormat.MEDIUM)),
           "",
           "",
           "",
           "",
           ""),
       provider);
 }
Пример #7
0
 public static <T extends BaseEntity> T create(Class<T> baseEntityClass) {
   T obj = null;
   try {
     obj = baseEntityClass.newInstance();
   } catch (Exception e) {
     logger.log(Level.SEVERE, "Instantiating " + baseEntityClass.getName(), e);
     return (null);
   }
   obj.setId(rand.nextInt(5000));
   Calendar cal = Calendar.getInstance();
   cal.setTime(new Date());
   obj.setCreatedDate(cal);
   obj.setModifiedDate(cal);
   return (obj);
 }
    @Override
    protected void done() {
      final TargetProductSelectorModel model = getTargetProductSelector().getModel();
      try {
        final Date now = Calendar.getInstance().getTime();
        final long diff = (now.getTime() - executeStartTime.getTime()) / 1000;
        if (diff > 120) {
          final float minutes = diff / 60f;
          statusLabel.setText("Processing completed in " + minutes + " minutes");
        } else {
          statusLabel.setText("Processing completed in " + diff + " seconds");
        }

        final Product targetProduct = get();
        if (model.isOpenInAppSelected()) {
          appContext.getProductManager().addProduct(targetProduct);
          // showSaveAndOpenInAppInfo(saveTime);
        } else {
          // showSaveInfo(saveTime);
        }
      } catch (InterruptedException e) {
        // ignore
      } catch (ExecutionException e) {
        handleProcessingError(e.getCause());
      } catch (Throwable t) {
        handleProcessingError(t);
      }
    }
  private void addLabelOnPanel(int i, String str, boolean listenerSign) {
    final JLabel label = new JLabel(str);
    label.setBackground(Color.WHITE);
    label.setBounds(startPoint_x, startPoint_y, 20, 20);
    startPoint_x += 40;
    if (i == 6) {
      startPoint_x = 20;
      startPoint_y += 35;
    }
    panel.add(label);
    if (listenerSign) {
      //// ????????????????????????????
      if (getNum(7 - i) == 1) {
        int selected = Integer.parseInt(str);
        if (cal.get(Calendar.DAY_OF_MONTH) == selected) {
          lastLabel = label;
          lastLabel.setForeground(Color.RED);
        }
        label.addMouseListener(
            new MouseAdapter() {

              @Override
              public void mouseClicked(MouseEvent e) {
                lastLabel.setForeground(Color.BLACK);
                label.setForeground(Color.RED);
                lastLabel = label;
              }
            });
      } else {
        int selected = Integer.parseInt(str);
        if (cal.get(Calendar.DAY_OF_MONTH) == selected) {
          lastLabel = label;
          lastLabel.setForeground(Color.BLUE);
        }
        label.addMouseListener(
            new MouseAdapter() {

              @Override
              public void mouseClicked(MouseEvent e) {
                lastLabel.setForeground(Color.BLACK);
                label.setForeground(Color.BLUE);
                lastLabel = label;
              }
            });
      }
    }
  }
  private void doTakeout(String titcketType) {
    Application application = Application.getInstance();

    Ticket ticket = new Ticket();
    // ticket.setPriceIncludesTax(application.isPriceIncludesTax());
    ticket.setTableNumber(-1);
    ticket.setTicketType(titcketType);
    ticket.setTerminal(application.getTerminal());
    ticket.setOwner(Application.getCurrentUser());
    ticket.setShift(application.getCurrentShift());

    Calendar currentTime = Calendar.getInstance();
    ticket.setCreateDate(currentTime.getTime());
    ticket.setCreationHour(currentTime.get(Calendar.HOUR_OF_DAY));

    OrderView.getInstance().setCurrentTicket(ticket);
    RootView.getInstance().showView(OrderView.VIEW_NAME);
  }
Пример #11
0
  /**
   * DOCUMENT ME!
   *
   * @param evt DOCUMENT ME!
   */
  private void btnThisMonthActionPerformed(final java.awt.event.ActionEvent evt) {
    final Calendar calendar = Calendar.getInstance();

    final Date toDate = calendar.getTime();

    calendar.set(Calendar.DAY_OF_MONTH, 1);
    final Date fromDate = calendar.getTime();

    try {
      lockDateButtons = true;
      dpiFrom.setDate(fromDate);
      dpiTo.setDate(toDate);
    } finally {
      lockDateButtons = false;
    }

    periodChanged();
    refreshFortfuehrungsList();
  }
    @Override
    protected Product doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
      final TargetProductSelectorModel model = getTargetProductSelector().getModel();
      pm.beginTask("Writing...", model.isOpenInAppSelected() ? 100 : 95);
      ProgressMonitorList.instance().add(pm); // NESTMOD
      saveTime = 0L;
      Product product = null;
      try {
        // free cache	// NESTMOD
        JAI.getDefaultInstance().getTileCache().flush();
        System.gc();

        executeStartTime = Calendar.getInstance().getTime();
        long t0 = System.currentTimeMillis();
        Operator operator = null;
        if (targetProduct.getProductReader() instanceof OperatorProductReader) {
          final OperatorProductReader opReader =
              (OperatorProductReader) targetProduct.getProductReader();
          if (opReader.getOperatorContext().getOperator() instanceof Output) {
            operator = opReader.getOperatorContext().getOperator();
          }
        }
        if (operator == null) {
          WriteOp writeOp =
              new WriteOp(targetProduct, model.getProductFile(), model.getFormatName());
          writeOp.setDeleteOutputOnFailure(true);
          writeOp.setWriteEntireTileRows(true);
          writeOp.setClearCacheAfterRowWrite(false);
          operator = writeOp;
        }
        final OperatorExecutor executor = OperatorExecutor.create(operator);
        executor.execute(SubProgressMonitor.create(pm, 95));

        saveTime = System.currentTimeMillis() - t0;
        File targetFile = model.getProductFile();
        if (model.isOpenInAppSelected() && targetFile.exists()) {
          product = ProductIO.readProduct(targetFile);
          if (product == null) {
            product = targetProduct; // todo - check - this cannot be ok!!! (nf)
          }
          pm.worked(5);
        }
      } finally {
        // free cache
        JAI.getDefaultInstance().getTileCache().flush();
        System.gc();

        pm.done();
        ProgressMonitorList.instance().remove(pm); // NESTMOD
        if (product != targetProduct) {
          targetProduct.dispose();
        }
      }
      return product;
    }
Пример #13
0
  /** Creates a new instance of {@link JCalendar} */
  public JCalendar() {
    intervalChangedListener = new ArrayList<IntervalChangedListener>();
    config = new Config();
    formater = new DefaultCalendarEventFormat();
    selectedDay = Calendar.getInstance();

    initGui();
    bindListeners();

    EventCollectionRepository.register(this);
  }
  private static Date raidDate(Bombed bombed) {
    final Calendar instance = Calendar.getInstance();
    instance.set(Calendar.YEAR, bombed.year());
    instance.set(Calendar.MONTH, bombed.month());
    instance.set(Calendar.DAY_OF_MONTH, bombed.day());
    instance.set(Calendar.HOUR_OF_DAY, bombed.time());
    instance.set(Calendar.MINUTE, 0);

    return instance.getTime();
  }
 /** Requests and displays all packages older than the date in the text field */
 private void buttonOldPackagesActionPerformed(ActionEvent event) {
   try {
     queryTime.setTime(dateFormatter.parse(jTextDate.getText().replace("-", "") + "2359"));
     this.packages = DataAdapter.getOlderPackages(queryTime);
     jListPackages.setListData(new Vector(this.packages));
     jButtonSetLost.setEnabled(this.packages.size() > 0);
     jButtonSetFound.setEnabled(false);
     jListScans.setListData(new Vector());
   } catch (Exception ex) {
     JOptionPane.showMessageDialog(this, "Invalid date entered");
   }
 }
  public MySimpleCal(JFrame owner, JTextField text, int t) {
    super(owner, true);
    this.plane_scheduler = t;
    System.out.println(plane_scheduler + "班期");
    this.owner = owner;
    this.text = text;
    cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);

    panel = new JPanel();
    initCalPanel();

    JPanel southPanel = new JPanel();
    btn = new JButton("确定");
    southPanel.add(btn);

    SpinnerNumberModel snm = new SpinnerNumberModel(year, year - 10, year + 10, 1);

    yearSpi = new JSpinner(snm);
    //		yearSpi.getEditor().setEnabled(false);
    String[] str = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"};
    monthBox = new JComboBox(str);

    JPanel northPanel = new JPanel();
    northPanel.add(yearSpi);
    northPanel.add(monthBox);
    monthBox.setSelectedIndex(month);

    this.setLayout(new BorderLayout());
    this.add(northPanel, BorderLayout.NORTH);
    this.add(panel, BorderLayout.CENTER);
    this.add(southPanel, BorderLayout.SOUTH);
    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    this.setResizable(false);
    this.setSize(310, 350);
    this.setMiddle();
    this.addEventListener();
  }
  private void doClockOut() {
    int option =
        JOptionPane.showOptionDialog(
            this,
            POSConstants.CONFIRM_CLOCK_OUT,
            POSConstants.CONFIRM,
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            null,
            null);
    if (option != JOptionPane.YES_OPTION) {
      return;
    }

    User user = Application.getCurrentUser();
    AttendenceHistoryDAO attendenceHistoryDAO = new AttendenceHistoryDAO();
    AttendenceHistory attendenceHistory = attendenceHistoryDAO.findHistoryByClockedInTime(user);
    if (attendenceHistory == null) {
      attendenceHistory = new AttendenceHistory();
      Date lastClockInTime = user.getLastClockInTime();
      Calendar c = Calendar.getInstance();
      c.setTime(lastClockInTime);
      attendenceHistory.setClockInTime(lastClockInTime);
      attendenceHistory.setClockInHour((short) c.get(Calendar.HOUR));
      attendenceHistory.setUser(user);
      attendenceHistory.setTerminal(Application.getInstance().getTerminal());
      attendenceHistory.setShift(user.getCurrentShift());
    }

    Shift shift = user.getCurrentShift();
    Calendar calendar = Calendar.getInstance();

    user.doClockOut(attendenceHistory, shift, calendar);

    Application.getInstance().logout();
  }
Пример #18
0
  // Вид формы при добавлении нового сотрудника
  public void sotrDiaInsert() {
    label_id_hidden.setText("Новый сотрудник");
    textField_familiya.setText("");
    textField_imya.setText("");
    textField_otchestvo.setText("");
    textField_phone.setText("");
    comboBox_doljnost.removeAllItems();
    comboBox_kvalification.removeAllItems();

    Calendar calend = Calendar.getInstance();
    if (calend.get(Calendar.MONTH) <= 9) {
      textField_date.setText(
          String.valueOf(
              (calend.get(Calendar.YEAR) + "-" + ("0" + (1 + calend.get(Calendar.MONTH))) + "-")
                  + (calend.get(Calendar.DATE))));
    } else
      textField_date.setText(
          String.valueOf(
              ((calend.get(Calendar.YEAR)) + "-" + (1 + calend.get(Calendar.MONTH)) + "-")
                  + (calend.get(Calendar.DATE))));
    textField_date.setEnabled(false);

    try {
      DBClass db = new DBClass();
      ArrayList<Doljnost> d = db.doljnostFromDB();
      for (int i = 0; i < d.size(); i++) {
        comboBox_doljnost.addItem(d.get(i));
      }
      DBClass db2 = new DBClass();
      ArrayList<Kvalification> k = db2.kvalificationFromDB();
      for (int i = 0; i < k.size(); i++) {
        comboBox_kvalification.addItem(k.get(i));
      }
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(panelException, e.getMessage());
    } catch (SQLException ee) {
      ee.printStackTrace();
      JOptionPane.showMessageDialog(panelException, ee.getMessage());
    }
  }
 public void actionPerformed(ActionEvent a) {
   int monthNum = month.getSelectedIndex();
   int dayNum = Integer.parseInt(day.getText());
   int yearNum = Integer.parseInt(year.getText());
   Calendar c = Calendar.getInstance();
   c.set(Calendar.MONTH, monthNum);
   c.set(Calendar.DAY_OF_MONTH, monthNum);
   c.set(Calendar.YEAR, yearNum);
   Date date = c.getTime();
   String dayOfWeek = (new SimpleDateFormat("EEE")).format(date);
   outputLabel.setText(dayOfWeek);
 }
  private void loadState(Element parentNode) {
    Element versionElement = parentNode.getChild(ELEMENT_VERSION);
    if (versionElement != null) {
      myMajorVersion = versionElement.getAttributeValue(ATTRIBUTE_MAJOR);
      myMinorVersion = versionElement.getAttributeValue(ATTRIBUTE_MINOR);
      myMicroVersion = versionElement.getAttributeValue(ATTRIBUTE_MICRO);
      myPatchVersion = versionElement.getAttributeValue(ATTRIBUTE_PATCH);
      myFullVersionFormat = versionElement.getAttributeValue(ATTRIBUTE_FULL);
      myCodeName = versionElement.getAttributeValue(ATTRIBUTE_CODENAME);
      myEAP = Boolean.parseBoolean(versionElement.getAttributeValue(ATTRIBUTE_EAP));
    }

    Element companyElement = parentNode.getChild(ELEMENT_COMPANY);
    if (companyElement != null) {
      myCompanyName = companyElement.getAttributeValue(ATTRIBUTE_NAME, myCompanyName);
      myShortCompanyName =
          companyElement.getAttributeValue("shortName", shortenCompanyName(myCompanyName));
      myCompanyUrl = companyElement.getAttributeValue(ATTRIBUTE_URL, myCompanyUrl);
    }

    Element buildElement = parentNode.getChild(ELEMENT_BUILD);
    if (buildElement != null) {
      myBuildNumber = buildElement.getAttributeValue(ATTRIBUTE_NUMBER);
      myApiVersion = buildElement.getAttributeValue(ATTRIBUTE_API_VERSION);
      setBuildNumber(myApiVersion, myBuildNumber);

      String dateString = buildElement.getAttributeValue(ATTRIBUTE_DATE);
      if (dateString.equals("__BUILD_DATE__")) {
        myBuildDate = new GregorianCalendar();
        try {
          final JarFile bootJar =
              new JarFile(
                  PathManager.getHomePath() + File.separator + "lib" + File.separator + "boot.jar");
          try {
            final JarEntry jarEntry =
                bootJar.entries().nextElement(); // /META-INF is always updated on build
            myBuildDate.setTime(new Date(jarEntry.getTime()));
          } finally {
            bootJar.close();
          }
        } catch (Exception ignore) {
        }
      } else {
        myBuildDate = parseDate(dateString);
      }
      String majorReleaseDateString = buildElement.getAttributeValue(ATTRIBUTE_MAJOR_RELEASE_DATE);
      if (majorReleaseDateString != null) {
        myMajorReleaseBuildDate = parseDate(majorReleaseDateString);
      }
    }

    Thread currentThread = Thread.currentThread();
    currentThread.setName(
        currentThread.getName()
            + " "
            + myMajorVersion
            + "."
            + myMinorVersion
            + "#"
            + myBuildNumber
            + " "
            + ApplicationNamesInfo.getInstance().getProductName()
            + ", eap:"
            + myEAP
            + ", os:"
            + SystemInfoRt.OS_NAME
            + " "
            + SystemInfoRt.OS_VERSION
            + ", java-version:"
            + SystemProperties.getJavaVendor()
            + " "
            + SystemInfo.JAVA_RUNTIME_VERSION);

    Element logoElement = parentNode.getChild(ELEMENT_LOGO);
    if (logoElement != null) {
      mySplashImageUrl = logoElement.getAttributeValue(ATTRIBUTE_URL);
      mySplashTextColor = parseColor(logoElement.getAttributeValue(ATTRIBUTE_TEXT_COLOR));
      String v = logoElement.getAttributeValue(ATTRIBUTE_PROGRESS_COLOR);
      if (v != null) {
        myProgressColor = parseColor(v);
      }

      v = logoElement.getAttributeValue(ATTRIBUTE_PROGRESS_TAIL_ICON);
      if (v != null) {
        myProgressTailIconName = v;
      }

      v = logoElement.getAttributeValue(ATTRIBUTE_PROGRESS_HEIGHT);
      if (v != null) {
        myProgressHeight = Integer.parseInt(v);
      }

      v = logoElement.getAttributeValue(ATTRIBUTE_PROGRESS_X);
      if (v != null) {
        myProgressX = Integer.parseInt(v);
      }

      v = logoElement.getAttributeValue(ATTRIBUTE_PROGRESS_Y);
      if (v != null) {
        myProgressY = Integer.parseInt(v);
      }

      v = logoElement.getAttributeValue(ATTRIBUTE_LICENSE_TEXT_OFFSET_Y);
      if (v != null) {
        myLicenseOffsetY = Integer.parseInt(v);
      }
    }

    Element aboutLogoElement = parentNode.getChild(ELEMENT_ABOUT);
    if (aboutLogoElement != null) {
      myAboutImageUrl = aboutLogoElement.getAttributeValue(ATTRIBUTE_URL);

      String v = aboutLogoElement.getAttributeValue(ATTRIBUTE_ABOUT_FOREGROUND_COLOR);
      if (v != null) {
        myAboutForeground = parseColor(v);
      }
      v = aboutLogoElement.getAttributeValue(ATTRIBUTE_ABOUT_COPYRIGHT_FOREGROUND_COLOR);
      if (v != null) {
        myCopyrightForeground = parseColor(v);
      }

      String c = aboutLogoElement.getAttributeValue(ATTRIBUTE_ABOUT_LINK_COLOR);
      if (c != null) {
        myAboutLinkColor = parseColor(c);
      }

      String logoX = aboutLogoElement.getAttributeValue("logoX");
      String logoY = aboutLogoElement.getAttributeValue("logoY");
      String logoW = aboutLogoElement.getAttributeValue("logoW");
      String logoH = aboutLogoElement.getAttributeValue("logoH");
      if (logoX != null && logoY != null && logoW != null && logoH != null) {
        try {
          myAboutLogoRect =
              new Rectangle(
                  Integer.parseInt(logoX),
                  Integer.parseInt(logoY),
                  Integer.parseInt(logoW),
                  Integer.parseInt(logoH));
        } catch (NumberFormatException nfe) {
          // ignore
        }
      }
    }

    Element iconElement = parentNode.getChild(ELEMENT_ICON);
    if (iconElement != null) {
      myIconUrl = iconElement.getAttributeValue(ATTRIBUTE_SIZE32);
      mySmallIconUrl = iconElement.getAttributeValue(ATTRIBUTE_SIZE16);
      myBigIconUrl = iconElement.getAttributeValue(ATTRIBUTE_SIZE128, (String) null);
      final String toolWindowIcon = iconElement.getAttributeValue(ATTRIBUTE_SIZE12);
      if (toolWindowIcon != null) {
        myToolWindowIconUrl = toolWindowIcon;
      }
    }

    Element packageElement = parentNode.getChild(ELEMENT_PACKAGE);
    if (packageElement != null) {
      myPackageCode = packageElement.getAttributeValue(ATTRIBUTE_CODE);
    }

    Element showLicensee = parentNode.getChild(ELEMENT_LICENSEE);
    if (showLicensee != null) {
      myShowLicensee =
          Boolean.valueOf(showLicensee.getAttributeValue(ATTRIBUTE_SHOW)).booleanValue();
    }

    Element welcomeScreen = parentNode.getChild(WELCOME_SCREEN_ELEMENT_NAME);
    if (welcomeScreen != null) {
      myWelcomeScreenLogoUrl = welcomeScreen.getAttributeValue(LOGO_URL_ATTR);
    }

    Element wizardSteps = parentNode.getChild(CUSTOMIZE_IDE_WIZARD_STEPS);
    if (wizardSteps != null) {
      myCustomizeIDEWizardStepsProvider = wizardSteps.getAttributeValue(STEPS_PROVIDER);
    }

    Element editor = parentNode.getChild(ELEMENT_EDITOR);
    if (editor != null) {
      myEditorBackgroundImageUrl = editor.getAttributeValue(BACKGROUND_URL_ATTR);
    }

    Element helpElement = parentNode.getChild(HELP_ELEMENT_NAME);
    if (helpElement != null) {
      myHelpFileName = helpElement.getAttributeValue(ATTRIBUTE_HELP_FILE);
      myHelpRootName = helpElement.getAttributeValue(ATTRIBUTE_HELP_ROOT);
      final String webHelpUrl = helpElement.getAttributeValue(ATTRIBUTE_WEBHELP_URL);
      if (webHelpUrl != null) {
        myWebHelpUrl = webHelpUrl;
      }

      String attValue = helpElement.getAttributeValue(ATTRIBUTE_HAS_HELP);
      myHasHelp = attValue == null || Boolean.parseBoolean(attValue); // Default is true

      attValue = helpElement.getAttributeValue(ATTRIBUTE_HAS_CONTEXT_HELP);
      myHasContextHelp = attValue == null || Boolean.parseBoolean(attValue); // Default is true
    }

    Element updateUrls = parentNode.getChild(UPDATE_URLS_ELEMENT_NAME);
    myUpdateUrls = new UpdateUrlsImpl(updateUrls);

    Element documentationElement = parentNode.getChild(ELEMENT_DOCUMENTATION);
    if (documentationElement != null) {
      myDocumentationUrl = documentationElement.getAttributeValue(ATTRIBUTE_URL);
    }

    Element supportElement = parentNode.getChild(ELEMENT_SUPPORT);
    if (supportElement != null) {
      mySupportUrl = supportElement.getAttributeValue(ATTRIBUTE_URL);
    }

    Element feedbackElement = parentNode.getChild(ELEMENT_FEEDBACK);
    if (feedbackElement != null) {
      myEAPFeedbackUrl = feedbackElement.getAttributeValue(ATTRIBUTE_EAP_URL);
      myReleaseFeedbackUrl = feedbackElement.getAttributeValue(ATTRIBUTE_RELEASE_URL);
    }

    Element whatsnewElement = parentNode.getChild(ELEMENT_WHATSNEW);
    if (whatsnewElement != null) {
      myWhatsNewUrl = whatsnewElement.getAttributeValue(ATTRIBUTE_URL);
    }

    Element pluginsElement = parentNode.getChild(ELEMENT_PLUGINS);
    if (pluginsElement != null) {
      String url = pluginsElement.getAttributeValue(ATTRIBUTE_URL);
      myPluginManagerUrl = url != null ? url : DEFAULT_PLUGINS_HOST;
      boolean closed = StringUtil.endsWith(myPluginManagerUrl, "/");

      String listUrl = pluginsElement.getAttributeValue(ATTRIBUTE_LIST_URL);
      myPluginsListUrl =
          listUrl != null ? listUrl : myPluginManagerUrl + (closed ? "" : "/") + "plugins/list/";

      String channelListUrl = pluginsElement.getAttributeValue(ATTRIBUTE_CHANNEL_LIST_URL);
      myChannelsListUrl =
          channelListUrl != null
              ? channelListUrl
              : myPluginManagerUrl + (closed ? "" : "/") + "channels/list/";

      String downloadUrl = pluginsElement.getAttributeValue(ATTRIBUTE_DOWNLOAD_URL);
      myPluginsDownloadUrl =
          downloadUrl != null
              ? downloadUrl
              : myPluginManagerUrl + (closed ? "" : "/") + "pluginManager/";

      if (!getBuild().isSnapshot()) {
        myBuiltinPluginsUrl = pluginsElement.getAttributeValue(ATTRIBUTE_BUILTIN_URL);
      }
    } else {
      myPluginManagerUrl = DEFAULT_PLUGINS_HOST;
      myPluginsListUrl = DEFAULT_PLUGINS_HOST + "/plugins/list/";
      myChannelsListUrl = DEFAULT_PLUGINS_HOST + "/channels/list/";
      myPluginsDownloadUrl = DEFAULT_PLUGINS_HOST + "/pluginManager/";
    }

    final String pluginsHost = System.getProperty("idea.plugins.host");
    if (pluginsHost != null) {
      myPluginsListUrl = myPluginsListUrl.replace(DEFAULT_PLUGINS_HOST, pluginsHost);
      myChannelsListUrl = myChannelsListUrl.replace(DEFAULT_PLUGINS_HOST, pluginsHost);
      myPluginsDownloadUrl = myPluginsDownloadUrl.replace(DEFAULT_PLUGINS_HOST, pluginsHost);
    }

    Element keymapElement = parentNode.getChild(ELEMENT_KEYMAP);
    if (keymapElement != null) {
      myWinKeymapUrl = keymapElement.getAttributeValue(ATTRIBUTE_WINDOWS_URL);
      myMacKeymapUrl = keymapElement.getAttributeValue(ATTRIBUTE_MAC_URL);
    }

    myPluginChooserPages = new ArrayList<PluginChooserPage>();
    final List children = parentNode.getChildren(PLUGINS_PAGE_ELEMENT_NAME);
    for (Object child : children) {
      myPluginChooserPages.add(new PluginChooserPageImpl((Element) child));
    }

    List<Element> essentialPluginsElements = JDOMUtil.getChildren(parentNode, ESSENTIAL_PLUGIN);
    Collection<String> essentialPluginsIds =
        ContainerUtil.mapNotNull(
            essentialPluginsElements,
            new Function<Element, String>() {
              @Override
              public String fun(Element element) {
                String id = element.getTextTrim();
                return StringUtil.isNotEmpty(id) ? id : null;
              }
            });
    myEssentialPluginsIds = ArrayUtil.toStringArray(essentialPluginsIds);

    Element statisticsElement = parentNode.getChild(ELEMENT_STATISTICS);
    if (statisticsElement != null) {
      myStatisticsSettingsUrl = statisticsElement.getAttributeValue(ATTRIBUTE_STATISTICS_SETTINGS);
      myStatisticsServiceUrl = statisticsElement.getAttributeValue(ATTRIBUTE_STATISTICS_SERVICE);
      myStatisticsServiceKey =
          statisticsElement.getAttributeValue(ATTRIBUTE_STATISTICS_SERVICE_KEY);
    } else {
      myStatisticsSettingsUrl = "https://www.jetbrains.com/idea/statistics/stat-assistant.xml";
      myStatisticsServiceUrl = "https://www.jetbrains.com/idea/statistics/index.jsp";
      myStatisticsServiceKey = null;
    }

    Element thirdPartyElement = parentNode.getChild(ELEMENT_THIRD_PARTY);
    if (thirdPartyElement != null) {
      myThirdPartySoftwareUrl = thirdPartyElement.getAttributeValue(ATTRIBUTE_URL);
    }

    Element tvElement = parentNode.getChild(ELEMENT_JB_TV);
    if (tvElement != null) {
      myJetbrainsTvUrl = tvElement.getAttributeValue(ATTRIBUTE_URL);
    }

    Element evaluationElement = parentNode.getChild(ELEMENT_EVALUATION);
    if (evaluationElement != null) {
      final String url = evaluationElement.getAttributeValue(ATTRIBUTE_EVAL_LICENSE_URL);
      if (url != null && !url.isEmpty()) {
        myEvalLicenseUrl = url.trim();
      }
    }

    Element licensingElement = parentNode.getChild(ELEMENT_LICENSING);
    if (licensingElement != null) {
      final String url = licensingElement.getAttributeValue(ATTRIBUTE_KEY_CONVERSION_URL);
      if (url != null && !url.isEmpty()) {
        myKeyConversionUrl = url.trim();
      }
    }

    Element subscriptionsElement = parentNode.getChild(ELEMENT_SUBSCRIPTIONS);
    if (subscriptionsElement != null) {
      mySubscriptionFormId =
          subscriptionsElement.getAttributeValue(ATTRIBUTE_SUBSCRIPTIONS_FORM_ID);
      mySubscriptionNewsKey =
          subscriptionsElement.getAttributeValue(ATTRIBUTE_SUBSCRIPTIONS_NEWS_KEY);
      mySubscriptionNewsValue =
          subscriptionsElement.getAttributeValue(ATTRIBUTE_SUBSCRIPTIONS_NEWS_VALUE, "yes");
      mySubscriptionTipsKey =
          subscriptionsElement.getAttributeValue(ATTRIBUTE_SUBSCRIPTIONS_TIPS_KEY);
      mySubscriptionTipsAvailable =
          Boolean.parseBoolean(
              subscriptionsElement.getAttributeValue(ATTRIBUTE_SUBSCRIPTIONS_TIPS_AVAILABLE));
      mySubscriptionAdditionalFormData =
          subscriptionsElement.getAttributeValue(ATTRIBUTE_SUBSCRIPTIONS_ADDITIONAL_FORM_DATA);
    }
  }
 /** Return the maximum number of days in a month. For example, Feb 2004 has 29 days. */
 private int maxDaysInMonth(int year, int month) {
   Calendar calendar = new GregorianCalendar(year, month, 1);
   return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
 }
Пример #22
0
 /**
  * Returns the selected day in the calendar
  *
  * @return
  */
 public Date getSelectedDay() {
   return selectedDay.getTime();
 }
Пример #23
0
/** Teton Cay Group, Inc. User: allen Date: Aug 21, 2013 Time: 5:07:46 PM */
public class Race extends RaceResources implements Serializable {

  private static transient Race instance = null;

  private static final transient int trainingMode =
      0; // todo If this is one then AUTO increment of runs happens, CANT USE IN RACE
  // or last racer in first runs has thte run number in race set to 2 before they finish == NO
  // MATCHING
  // Run on FINISH//  e.g Run 1 for last racer doesn't == run 2 iteration for auto incremented  race
  // 1;
  private transient int MAX_RUNS_ALLOWED = 2; // 99;//2;

  // Race Configuration
  private transient Calendar cal = Calendar.getInstance();

  public PhotoCellAgent getPhotoCellAgent() {
    return photoCellAgent;
  }

  public ImageIcon getPhotoCellTinyII() {
    if (timyEnabled) {
      return tagHeuerTinyII;
    }
    if (tagHeuerEnabled) {
      return tagHeuerTinyII;
    }
    //      if (microgateEnabled) {
    return microgateII;
    //      }
    //      return null;

  }

  private transient PhotoCellAgent photoCellAgent; // Calendar cal = Calendar.getInstance();
  // private transient PhotoCellAgent agent;

  public boolean isPHOTO_EYE_AUTOMATIC() {
    return PHOTO_EYE_AUTOMATIC;
  }

  // PHOTO_EYE_AUTOMATIC mode requires only verification of timing device impulses, and doesn't use
  // the START / FINISH button manual backup timing
  private transient boolean PHOTO_EYE_AUTOMATIC = false; // TODO parameterize true;

  Date date = cal.getTime();

  private String name;
  private String location;
  private Integer nbrGates;
  private List<Integer> upstreamGates;
  private ArrayList<JudgingSection> judgingSections;
  private List<Racer> racers;
  private boolean icfPenalties = false;

  // Race Status
  private RaceRun pendingRerun; // = null;
  private RaceRun pendingAdjustment;
  private List<BoatEntry> startList =
      null; // todo on Crash recovery don't have an yet-to-be-started list, only all racers
  private ArrayList<RaceRun> activeRuns = null;
  private long runsStartedOrCompletedCnt = 0;
  private int currentRunIteration; // are we on 1st runs, or 2nd runs ?
  private ArrayList<RaceRun> completedRuns = null;

  // Transient Objects

  // Move these to SlalomApp or elsewhere in a device handler object
  private transient Thread photoEyeThread; // Thread to get input from Photocells
  private transient PhotoEyeListener
      photoEyeListener; // Tag Heuer CP 520/540 listener/command processor

  private transient ArrayList<Result> results = new ArrayList<Result>();
  private transient LastRace lastRace;

  public Boolean getTagHeuerEnabled() {
    return tagHeuerEnabled;
  }

  public Boolean getMicrogateEnabled() {
    return microgateEnabled;
  }

  public void setTagHeuerEnabled(Boolean tagHeuerEnabled) {
    this.tagHeuerEnabled = tagHeuerEnabled;
  }

  public void setMicrogateEnabled(Boolean microgateEnabled) {
    this.microgateEnabled = microgateEnabled;
  }

  public void setTimyEnabled(Boolean timyEnabled) {
    this.timyEnabled = timyEnabled;
  }

  private Boolean tagHeuerEnabled = false;
  private Boolean microgateEnabled = false;
  private Boolean timyEnabled = false;

  private transient Boolean tagHeuerConnected;
  private transient Boolean microgateConnected;
  private transient Log log;
  //    private transient XStream xstream;
  // private transient SlalomResultsHTTP_Save resultsHTTP;
  // D161004
  private transient SlalomRacerResultsHTTP racerResultsHTTP;
  private transient SlalomResultsScoringHTTP scoreboardResultsHTTP_New;
  private transient SlalomResultsHTTP someResultsHTTP;

  public static synchronized Race getInstance() {
    if (instance == null) {
      instance = new Race();
    }
    return instance;
  }

  public static int getTrainingMode() {
    return trainingMode;
  }

  public int getMaxRunsAllowed() {
    return MAX_RUNS_ALLOWED;
  }

  //    public boolean isTagHeuerEmulation() {
  //        return tagHeuerEmulation;
  //    }
  //
  //    public void setTagHeuerEmulation(boolean tagHeuerEmulation) {
  //        this.tagHeuerEmulation = tagHeuerEmulation;
  //    }

  public Boolean getTagHeuerConnected() {
    return tagHeuerConnected;
  }

  public Boolean getMicrogateConnected() {
    return microgateConnected;
  }

  public void setTagHeuerConnected(Boolean tagHeuerConnected) {
    this.tagHeuerConnected = tagHeuerConnected;
  }

  public void setPhotoCellAgent(PhotoCellAgent photoCellAgent) {
    this.photoCellAgent = photoCellAgent;
  }

  public void setMicrogateConnected(Boolean microgateConnected) {
    this.microgateConnected = microgateConnected;
  }

  public boolean isIcfPenalties() {
    return icfPenalties;
  }

  public void setIcfPenalties(boolean icfPenalties) {
    this.icfPenalties = icfPenalties;
  }

  //    public Thread getPhotoCellThread() {
  //        return photoEyeThread;
  //    }

  //    public void setPhotoCellThread(Thread photoEyeThread) {
  //        this.photoEyeThread = photoEyeThread;
  //    }

  public boolean TODOKludgeStartFRomPhotoEye(String bibNumber) {
    boolean started = false;
    RaceTimingUI timingUI = RaceTimingUI.getInstance();
    if (timingUI.startButtonActionHandlerFromPhotoEye(bibNumber)) {
      started = true;
    }
    return started;
  }

  public boolean TODOKludgeFinishFRomPhotoEye(String bibNumber) {
    boolean stopped = false;
    RaceTimingUI timingUI = RaceTimingUI.getInstance();
    if (timingUI.stopButtonActionHandlerFromPhotoEye(bibNumber)) {
      stopped = true;
    }
    return stopped;
  }

  public JudgingSection updateSectionOnline(Integer section) {
    JudgingSection found = null;
    for (JudgingSection js : judgingSections) {
      if (js.getSectionNbr().compareTo(section) == 0) {
        js.setClientDeviceAttached(true);
        found = js;
        break;
      }
    }
    return found;
  }

  public void maybeStartPhotoCellInterface() {

    if (photoEyeThread == null) {

      photoEyeListener = new PhotoEyeListener();
      photoEyeThread = new Thread(photoEyeListener);
      photoEyeThread.start();

      photoCellAgent = photoEyeListener.getAgent();

    } else {
      log.info("ALREADY HAVE A THREAD HERE !!!");
    }
  }

  public void setUpstreamGates(List<Integer> upstreamGates) {
    this.upstreamGates = upstreamGates;
  }

  public PhotoEyeListener getPhotoEyeListener() {
    return photoEyeListener;
  }

  public void setPhotoEyeListener(PhotoEyeListener photoEyeListener) {
    this.photoEyeListener = photoEyeListener;
  }

  public ArrayList<Result> getTempResults() {
    return results;
  }

  // todo investigate changing to string return
  public int getCurrentRunIteration() { // Run #1, #2, etc.  for all racers
    return currentRunIteration;
  }

  public String getRunTitle() {
    return (getCurrentRunIterationOrdinal() + " Runs");
  }

  public RaceRun getPendingRerun() {
    RaceRun r = pendingRerun;

    pendingRerun = null;
    return r;
  }

  public void setPendingRerun(RaceRun newRun) {

    pendingRerun = newRun;
  }

  public void setPendingAdjustment(RaceRun adjustRun) {

    pendingAdjustment = adjustRun;
  }

  public RaceRun getPendingAdjustment() {
    RaceRun r = pendingAdjustment;

    pendingAdjustment = null;
    return r;
  }

  public String getCurrentRunIterationOrdinal() {
    String ordinal = " ?? ";
    switch (currentRunIteration) {
      case 1:
        ordinal = FIRST;
        break;
      case 2:
        ordinal = SECOND;
        break;
      default:
        ordinal = new Integer(currentRunIteration).toString();
        break;
    }

    return ordinal;
  }

  protected void clearRace() {
    racers = new ArrayList<Racer>();
    startList = new ArrayList<BoatEntry>();
    activeRuns = new ArrayList<RaceRun>();
    completedRuns = new ArrayList<RaceRun>();
    judgingSections = new ArrayList<JudgingSection>();
    upstreamGates = new ArrayList<Integer>();
    location = "";
    pendingRerun = null;
    name = UNNAMED_RACE;
    currentRunIteration = 1;
    runsStartedOrCompletedCnt = 0;
    lastRace = new LastRace();
    nbrGates = DEFAULT_NBR_GATES;

    // resettable transient members
    results = new ArrayList<Result>();
    // todo ?? lastRace;
  }

  private Race() {
    if (trainingMode == 1) {
      MAX_RUNS_ALLOWED = 99;
    }

    log = Log.getInstance();
    //  xstream = initXML();   D20160407 RIO CAUSING CRASH
    clearRace();

    lastRace = new LastRace();
    tagHeuerConnected = false; // new Boolean(false);
    microgateConnected = false;
    // D161004        resultsHTTP = new SlalomResultsHTTP_Save();
    // todo set up on timing page to test and then enable CP520
    // C160315        Thread t = new Thread( photoEyeListener = new PhotoEyeListener());
    // C160315        t.start();

    // TODO - determine if any photo eyes in use, add appropriate handler/listener
    // D20160305maybeStartPhotoCellInterface();  Was being called in ClietnPenalty App

    // D161004
    racerResultsHTTP = new SlalomRacerResultsHTTP();
    scoreboardResultsHTTP_New = new SlalomResultsScoringHTTP();
    someResultsHTTP = new SlalomResultsHTTP();
  }

  public void removeCompletedRun(RaceRun remove) {
    completedRuns.remove(remove);
  }

  public void incrementCurrentRunIteration() {
    if (currentRunIteration < MAX_RUNS_ALLOWED) {
      currentRunIteration++;
    }
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
    lastRace.setName(name);
    lastRace.saveSerializedData();
  }

  public String getLocation() {
    return location;
  }

  public void setLocation(String location) {
    this.location = location;
  }

  public Integer getNbrGates() {
    return nbrGates;
  }

  public ArrayList<JudgingSection> getSections() {
    return judgingSections;
  }

  public void setNbrGates(Integer nbrGates) {
    this.nbrGates = nbrGates;
  }

  public List<Integer> getUpstreamGates() {
    return upstreamGates;
  }

  public boolean isUpstream(int iGate) {
    for (int i : upstreamGates) {
      if (i == iGate) {
        return true;
      }
    }
    return false;
  }

  public int getNbrOfSections() {
    return judgingSections.size();
  }

  public ArrayList<JudgingSection> getSectionEndingGates() {
    return judgingSections;
  }

  public void setSectionEndingGates(ArrayList<JudgingSection> sectionEndingGates) {
    this.judgingSections = sectionEndingGates;
  }

  public void addSection(JudgingSection section) {
    judgingSections.add(section);
  }

  public boolean isFirstGateInSection(int iGate) {
    for (JudgingSection s : judgingSections) {
      if (iGate == s.getFirstGate()) {
        return true;
      }
    }
    return false;
  }

  public String getSectionsConnectedNamesAsString() {
    StringBuffer sb = new StringBuffer();
    boolean first = true;
    for (JudgingSection s : judgingSections) {
      if (s.getClientDeviceAttached()) {
        if (!first) {
          sb.append(",");
        }
        first = false;
        sb.append(s.getSectionNbr());
      }
    }
    if (sb.length() == 0) {
      sb.append(SECTIONS_NONE);
    }
    return sb.toString();
  }

  public JudgingSection getSection(int section) {
    JudgingSection judgingSection = null;
    for (JudgingSection s : judgingSections) {
      if (s.getClientDeviceAttached()) {
        judgingSection = s;
        break;
      }
    }
    return judgingSection;
  }

  public boolean isGateInSection(int iGate, int section) {
    if (section == 0) { // All Sections are represented by 0 /// fixme kludge
      return true;
    }
    int currSection = 1;
    for (JudgingSection s : judgingSections) {
      if (section == currSection) {
        if (iGate >= s.getFirstGate() && iGate <= s.getLastGate()) {
          // System.out.println(iGate + " is in section " + section);
          return true;
        }
      }
      currSection++;
    }
    //        System.out.println(iGate + " is NOT in section " + section);

    return false;
  }

  public boolean isLastGateInSection(int iGate) {
    for (JudgingSection s : judgingSections) {
      if (iGate == s.getLastGate()) {
        return true;
      }
    }
    return false;
  }

  public ArrayList<RaceRun> getCompletedRuns() {
    return completedRuns;
  }

  public RaceRun getExistingRun(BoatEntry be) { // todo Add Run#
    RaceRun run = null;
    for (RaceRun r : completedRuns) {
      if (r.getRunNumber() == currentRunIteration && r.getBoat() == be) {
        run = r;
        break;
      }
    }

    if (run == null) {
      for (RaceRun r : activeRuns) {
        if (r.getRunNumber() == currentRunIteration && r.getBoat() == be) {
          run = r;
          break;
        }
      }
    }

    return run;
  }

  public ArrayList<RaceRun> getCompletedRunsByClassTime() {
    ArrayList<RaceRun> sorted = new ArrayList<RaceRun>(completedRuns);

    Collections.sort(sorted);
    return sorted;
  }

  public ArrayList<RaceRun> getActiveRuns() {
    return activeRuns;
  }

  public List<Racer> getRacers() {
    return racers;
  }

  /**
   * Add an entry to the StartList rejecting any duplicate Bib assignments in the same race class It
   * is possible to have the same bib in a different classes in lower levels of races (e.g. C1 and
   * C2)
   *
   * @param racer
   * @param boatClass
   * @throws DuplicateBibException
   */
  public void addBoat(Racer racer, String boatClass) throws DuplicateBibException {
    if (count(racer.getBibNumber(), boatClass) < 1) {
      racers.add(racer);
      startList.add(new BoatEntry(racer, boatClass));
    } else {
      log.error(
          "Can't add bib "
              + racer.getBibNumber()
              + " for "
              + boatClass
              + " "
              + racer.getShortName()
              + " already used by "
              + whoIs(racer.getBibNumber(), boatClass));
      throw new DuplicateBibException();
    }
  }

  public void addRun(RaceRun newRun) {
    synchronized (activeRuns) {
      activeRuns.add(newRun);
      runsStartedOrCompletedCnt++; /// count of total racer starts

      System.out.println("CURRENTLY " + activeRuns.size() + " ACTIVE RUNS");
    }
  }

  public void finishedRun(RaceRun run) {
    synchronized (activeRuns) {
      activeRuns.remove(run);
      runsStartedOrCompletedCnt++;
    }

    synchronized (completedRuns) {
      completedRuns.add(run);
    }
  }

  public boolean isDNF(String bibNumber, int runNumber) {
    boolean dnf = false;
    for (RaceRun rr : completedRuns) {
      if (rr.getBoat().getRacer().getBibNumber().equals(bibNumber)
          && rr.getRunNumber() == runNumber) {
        if (rr.isDnf()) {
          dnf = true;
        }
      }
    }
    return (dnf);
  }

  // A150009 (ajm) Start

  public RaceRun getNewestCompletedRun() {
    RaceRun run = null;
    //    if (getActiveRuns().size() > 0) {
    //        run = getActiveRuns().get(0);
    //    }

    int size = getCompletedRuns().size();
    if (size > 0) {

      run = getCompletedRuns().get(size - 1);
    }

    return (run);
  }

  public RaceRun getRecentCompletedRun(int which) {
    RaceRun run = null;
    //    if (getActiveRuns().size() > 0) {
    //        run = getActiveRuns().get(0);
    //    }

    int size = getCompletedRuns().size();
    if (size >= which) {
      run = getCompletedRuns().get(size - which);
    }

    return (run);
  }

  public RaceRun getNewestActiveRun() {
    RaceRun run = null;
    int size = getActiveRuns().size();
    if (size > 0) {
      run = getActiveRuns().get(size - 1);
    }
    return (run);
  }

  public RaceRun getOldestActiveRun() {
    RaceRun run = null;
    int size = getActiveRuns().size();
    if (size > 0) {
      run = getActiveRuns().get(0);
    }
    return (run);
  }

  // A150009 (ajm) End

  public long getRunsStartedOrCompletedCnt() {
    return runsStartedOrCompletedCnt;
  }

  public static final int MAX_COMPLETED_RUNS_IN_SCORING_PICKLIST = 2;
  public static final int MAX_ACTIVE_RUNS_IN_SCORING_PICKLIST = 2;

  private void addaFewCompletedRuns(ArrayList<RaceRun> scorable) {

    // add all runs for now
    try {

      for (RaceRun r : completedRuns) {
        scorable.add(r);
      }
    } catch (Exception e) {
      log.warn("BAD ARRAY EXCEPTION AJM");
    }
  }

  public ArrayList<RaceRun> getScorableRuns() {
    ArrayList<RaceRun> scorable = new ArrayList<RaceRun>();
    addaFewCompletedRuns(scorable);
    for (RaceRun r : activeRuns) {
      scorable.add(r);
    }

    return scorable;
  }

  public List<BoatEntry> getRemainingStartList() {
    return startList;
  }

  private int count(String bibNbr, String boatClass) {
    int count = 0;
    for (BoatEntry boat : startList) {
      if (boat.getRacer().getBibNumber().trim().compareTo(bibNbr.trim()) == 0
          && boat.getBoatClass().compareTo(boatClass) == 0) {
        count++;
      }
    }
    return count;
  }

  private String whoIs(String bibNbr, String boatClass) {
    String who = "";
    for (BoatEntry boat : startList) {
      if (boat.getRacer().getBibNumber().trim().compareTo(bibNbr.trim()) == 0
          && boat.getBoatClass().compareTo(boatClass) == 0) {
        who =
            boat.getRacer().getBibNumber()
                + " "
                + boat.getBoatClass()
                + " "
                + boat.getRacer().getShortName();
      }
    }
    return who;
  }

  public String lookForDuplicateBibsInTheSameClass() {
    String returnString = null;
    for (BoatEntry boat : startList) {
      if (count(boat.getRacer().getBibNumber(), boat.getBoatClass()) > 1) {

        returnString =
            "Bib number "
                + boat.getRacer().getBibNumber()
                + " occurs more than once in "
                + boat.getBoatClass();
        System.out.println(returnString);
        log.warn(returnString);
      }
    }
    return (returnString);
  }

  /*
      private XStream initXML() {
          XStream xstream = new XStream(new DomDriver());
          xstream.registerConverter(new XStreamRaceConverter());

          xstream.alias("race", Race.class);
  //        xstream.alias("run", RaceRun.class);
  //        xstream.alias("section", JudgingSection.class);
  //        xstream.alias("boatEntry", BoatEntry.class);
  //        xstream.alias("racer", Racer.class);

          return(xstream);
      }
  */

  /*
      private void saveXML() {
          String filename = getName() + ".xml";

          File fileOut=null;
          FileOutputStream out=null;
          try {
              fileOut = new File(filename);
              out = new FileOutputStream(fileOut);
              String xml = xstream.toXML(this);
              out.write(xml.getBytes());
              out.close();
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              try {
                 out.close();
              } catch (IOException e) {
              }
          }

          log.trace("Saved XML to " + filename);




          String xml = xstream.toXML(this);
   //       System.out.println(xml);
      }

      private Race loadXML() {
          String fileName = lastRace.getName();
  //        String filename = getName() + ".xml";
          fileName+=".xml";
          char[] xml = new char[10000];
          Race race=null;

          File file=null;
          ObjectInputStream in = null;
         // BufferedReader in=null;
          try {
              ///file = new File(fileName);
  //            FileInputStream fileIn = new FileInputStream(fileName);//"RaceRun.ser");

  //            in = xstream.createObjectInputStream;//)OutputStream(aReader);

              Reader someReader = new FileReader(fileName);

               in = xstream.createObjectInputStream(someReader);
  //            in = new BufferedReader(new FileReader(file));//InputStream(file);


            //  BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
            //  String line = null;
            // while ((line =

  //          in.read(xml); ///readLine()) != null) {
                  // ...


              // in = new ObjectInputStream(fileIn);
              deSerializeXML(in);

              in.close();



              //in.read(xml);
  //            String xmlString = new String(xml);
  //            race  = (Race)xstream.fromXML(xmlString);
  //            System.out.println(race);
              in.close();
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              try {
                  in.close();
              } catch (IOException e) {
              }
          }

          return race;
          //Race race  = (Race)xstream.fromXML(xml);
      }

  */

  // fixme todo change all to XML serialization, so class versions are NOT an issue !
  public void saveSerializedData() {

    // saveXML();
    try {
      lastRace.setName(getName());
      lastRace.saveSerializedData();
      String filename = getName() + ".ser";

      FileOutputStream fileOut = new FileOutputStream(filename);
      ObjectOutputStream out =
          new ObjectOutputStream(
              fileOut); /// MUST FIX 2016 Nationals ERROR CONCurrentMpdificationException
      out.writeObject(
          this); // See   Ref#20161008 This was Line 913 BELOW on 20161008   //// This was line 869
      // in bwlow Log -->> Got CONCurrentMpdificationException ///20160727 in test
      /*
                  PRIOR CRASH  Prior to 20161008  See bottom of source file for new carsh dump
      at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329)
      	at com.tcay.slalom.Race.saveSerializedData(Race.java:869)
      	at com.tcay.slalom.Race.updateResults(Race.java:1177)
      	at com.tcay.slalom.Race.updateResults(Race.java:1168)
      	at com.tcay.slalom.RaceRun.updateResults(RaceRun.java:535)
      	at com.tcay.slalom.RaceRun.setPhotoCellRaceRun(RaceRun.java:139)
      	at com.tcay.slalom.Race.associatePhotoCellRun(Race.java:1163)
      	at com.tcay.slalom.timingDevices.PhotoCellAgent.saveResult(PhotoCellAgent.java:57)
      	at com.tcay.slalom.timingDevices.tagHeuer.TagHeuerAgent.processDeviceOutput(TagHeuerAgent.java:174)
      	at com.tcay.RS232.PhotoEyeListener.readAndProcess(PhotoEyeListener.java:241)
      	at com.tcay.RS232.PhotoEyeListener.processPhotoEyeDataFromDevice(PhotoEyeListener.java:190)
      	at com.tcay.RS232.PhotoEyeListener.listenAndProcessPortOutput(PhotoEyeListener.java:304)
      	at com.tcay.RS232.PhotoEyeListener.run(PhotoEyeListener.java:76)
                  */

      out.close();
      fileOut.close();
      log.trace("Saved serialized data to " + filename);

    } catch (IOException i) {
      i.printStackTrace();
    }
  }

  public void loadSerializedData() {
    // fixme        Race x = loadXML();
    // return;
    // lastRace.getName();
    //        RaceRun run;
    try {
      //          lastRace.loadSerializedData();
      String fileName = lastRace.getName();
      FileInputStream fileIn = new FileInputStream(fileName + ".ser"); // "RaceRun.ser");
      try {
        ObjectInputStream in = new ObjectInputStream(fileIn);
        deSerialize(in);

        in.close();
        fileIn.close();

        tagHeuerConnected = new Boolean(false); // / make sure it exists - transient object
        microgateConnected = new Boolean(false); // / make sure it exists - transient object

      } catch (InvalidClassException ice) {
        log.info("Invalid Class from deserialization " + ice.classname);
      } catch (EOFException eof) {
        log.info("EOF on Serialized data");
      } catch (IOException i) {
        i.printStackTrace();
        // } catch (ClassNotFoundException cnf) {
        //    cnf.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }
    } catch (FileNotFoundException fnf) {
      // Empty block OK - ignore this exception
    }

    // load required transient members
    Log raceRunLog = Log.getInstance();
    for (RaceRun r : activeRuns) {
      r.setLog(raceRunLog);
    }
    for (RaceRun r : completedRuns) {
      r.setLog(raceRunLog);
    }
    if (pendingRerun != null) {
      pendingRerun.setLog(raceRunLog);
    }

    //     updateResults();   //todo OK Here ???        NO - didn't set

  }

  private void deSerializeXML(ObjectInputStream in) {
    Object o;
    try {
      while ((o = in.readObject()) != null) {
        System.out.println(o);
      }
    } catch (IOException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    } catch (ClassNotFoundException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }
  }

  public Date getDate() {
    return date;
  }

  private void deSerialize(ObjectInputStream in) throws DuplicateBibException {
    Object o;
    try {
      while ((o = in.readObject()) != null) {
        Race raceFromSerialized = (Race) o;

        this.date = raceFromSerialized.date;
        this.name = raceFromSerialized.name;
        this.location = raceFromSerialized.location;
        setNbrGates(raceFromSerialized.nbrGates); // this.nbrGates = race.nbrGates;// = 25;
        this.upstreamGates = raceFromSerialized.upstreamGates;
        this.judgingSections = raceFromSerialized.judgingSections;
        for (JudgingSection s : judgingSections) {
          // must assign all transients, otherwise they are null and cause problsm
          s.setClientDeviceAttached(new Boolean(false));
        }

        // Race Status
        this.pendingRerun = raceFromSerialized.pendingRerun;
        this.activeRuns = raceFromSerialized.activeRuns;
        this.completedRuns = raceFromSerialized.completedRuns;

        this.startList = raceFromSerialized.startList;
        this.runsStartedOrCompletedCnt = raceFromSerialized.runsStartedOrCompletedCnt;
        this.currentRunIteration =
            raceFromSerialized.currentRunIteration; // are we on 1st runs, or 2nd runs ?
        this.racers = raceFromSerialized.racers;
        this.tagHeuerEnabled =
            raceFromSerialized.tagHeuerEnabled; // todo REMOVE ->tagHeuerEmulation =
        // raceFromSerialized.tagHeuerEmulation;
        this.microgateEnabled = raceFromSerialized.microgateEnabled;
        this.microgateEnabled = raceFromSerialized.timyEnabled;

        this.icfPenalties = raceFromSerialized.icfPenalties;
      }

    } catch (InvalidClassException ice) {
      clearRace();
      System.out.println("All data cleared, incompatible race object version information");
    } catch (EOFException io) {
      // io.printStackTrace();

    } catch (IOException io) {
      io.printStackTrace();
    } catch (ClassNotFoundException cnfe) {
      cnfe.printStackTrace();
    }
    String duplicates = lookForDuplicateBibsInTheSameClass();
    if (duplicates != null) {
      log.error(duplicates);
      throw new DuplicateBibException();
    }
  }

  public void askSampleDataIfNoRacersExist(JPanel panel) {
    if (Race.getInstance().getRacers().size() == 0) {
      int n =
          JOptionPane.showConfirmDialog(
              panel,
              "No Course or Racers Exist, would you like to load a sample race ?",
              "Load Sample Data",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.YES_OPTION,
              Race.getInstance().getSlalomCourseSmall());

      if (n == 0) {
        new TestData().load();
      }
    }
  }

  private boolean sameRun(RaceRun ourRun, RaceRun otherRun) {
    boolean same = false;
    BoatEntry b;
    Racer racer;
    String bib;
    try {
      b = ourRun.getBoat();
      racer = b.getRacer();
      bib = racer.getBibNumber();

      if (bib.compareTo(otherRun.getBoat().getRacer().getBibNumber()) == 0) {
        if (ourRun.getRunNumber() == otherRun.getRunNumber()) {
          same = true;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return (same);
  }

  private boolean sameRun(RaceRun ourRun, PhotoCellRaceRun otherRun) {
    boolean same = false;
    BoatEntry b;
    Racer racer;
    String bib;
    try {
      b = ourRun.getBoat();
      racer = b.getRacer();
      bib = racer.getBibNumber();

      if (bib.compareTo(otherRun.getBibNumber()) == 0) {
        // We only want to store real time Tag Heuer electronic eye times
        // with the current run
        if (ourRun.getRunNumber() == otherRun.getRunNumber()) {
          same = true;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return (same);
  }

  // fixme consolidate with associatePhotoCellRun() method
  public RaceRun findRun(RaceRun clientRaceRun) {

    RaceRun matchingRun = null;

    for (RaceRun r : activeRuns) {
      if (sameRun(r, clientRaceRun)) {
        matchingRun = r;
        break;
      }
    }

    if (matchingRun == null) {
      for (RaceRun r : completedRuns) {
        try {

          if (sameRun(r, clientRaceRun)) {
            matchingRun = r;
            break;
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return (matchingRun);
  }

  private BoatEntry boatInStartingBlock = null;

  public BoatEntry getBoatInStartingBlock() {
    return boatInStartingBlock;
  }

  public void setBoatInStartingBlock(BoatEntry boat) {
    boatInStartingBlock = boat;
  }

  public BoatEntry getBoatReadyToFinish() {
    RaceTimingUI timingUI = RaceTimingUI.getInstance();
    return timingUI.boatReadyToFinish();
  }

  public void associatePhotoCellRun(PhotoCellRaceRun photoCellRun) {

    RaceRun matchingRun = null;

    for (RaceRun r : activeRuns) {
      try {
        if (sameRun(r, photoCellRun)) {
          matchingRun = r;
          // log.info/*trace*/("Found bib#" + r.getBoat().getRacer().getBibNumber() + " r#"+
          // r.getRunNumber() +  " in Active Runs");

        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    if (matchingRun == null) {
      for (RaceRun r : completedRuns) {
        try {
          if (sameRun(r, photoCellRun)) {
            matchingRun = r;
            //    log.trace("Found bib#" + r.getBoat().getRacer().getBibNumber() + " r#"+
            // r.getRunNumber() + " + in Completed Runs");
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    if (matchingRun != null) {
      matchingRun.setPhotoCellRaceRun(
          photoCellRun); /// MUST FIX 2016 Nationals ERROR CONCurrentMpdificationException
    }
  }

  public void updateResults(RaceRun run, boolean saveSerialized) {
    updateResults(saveSerialized); // /MUST FIX 2016 Nationals ERROR CONCurrentMpdificationException
    racerResultsHTTP.outputWeb(run.getBoat());
    // M161006    scoreboardResultsHTTP_New.outputWeb("Sorted", getCompletedRunsByClassTime(),
    // true);
  }

  public void updateResults(boolean saveSerialized) {
    results = accumulateResults(getCompletedRuns());
    ResultsTableModel.getInstance().updateResults();
    RunScoringTableModel.getInstance().updateResults();
    if (saveSerialized) {
      saveSerializedData();
    } /// MUST FIX 2016 Nationals ERROR CONCurrentMpdificationException
    // D161004        resultsHTTP.outputWeb("Sorted", getCompletedRunsByClassTime(), true);

    // M161006
    scoreboardResultsHTTP_New.outputWeb("Sorted", getCompletedRunsByClassTime(), true);
  }

  public void printResultsHTTP(String boatClass, int runNbr) {
    someResultsHTTP.outputWeb("", getCompletedRunsByClassTime(), true, boatClass, runNbr);
  }

  private Result findRacer(RaceRun run) {
    Result result = null;
    for (Result r : results) {
      if (r.getRacer() == run.getBoat().getRacer()) {
        result = r;
        break;
      }
    }

    return result;
  }

  private ArrayList<Result> accumulateResults(ArrayList<RaceRun> runs) {
    Result res;
    results = new ArrayList<Result>();

    for (RaceRun r : runs) {
      res = findRacer(r);
      if (res == null) {
        res = new Result();
        results.add(res);
      }
      res.setRacer(r.getBoat().getRacer());
      res.setBoat(r.getBoat());

      switch (r.getRunNumber()) {
        case 1:
          res.setRun1(r);
          break;
        case 2:
          res.setRun2(r);
          break;
      }
    }

    float run1Time;
    float run2Time;
    for (Result res1 : results) {
      // run1Time = (float)999999.99;
      // run2Time = (float)999999.99;

      try {

        if (res1.getRun1() == null || res1.getRun2() == null) {
          if (res1.getRun1() == null) {
            res1.setBestRun(res1.getRun2());
          }
          if (res1.getRun2() == null) {
            res1.setBestRun(res1.getRun1());
          }
        } else {
          run1Time = res1.getRun1().getElapsed() + res1.getRun1().getTotalPenalties();
          run2Time = res1.getRun2().getElapsed() + res1.getRun2().getTotalPenalties();
          if (run1Time <= run2Time) {
            res1.setBestRun(res1.getRun1());
          } else {
            res1.setBestRun(res1.getRun2());
          }
        }
      } catch (Exception e) {
        log.write(e);
      }
    }

    ArrayList<Result> sorted = Result.getResultsByClassTime(results);
    results = sorted; // A10112013

    String lastBoatClass = "";
    int place = 1;

    for (Result r : sorted) {
      try {
        r.getRun1()
            .setGold(false); // / TODO: if skipping 1st runs fro some reason, this will cause a null
        // pointer reference
        r.getRun1().setSilver(false);
        r.getRun1().setBronze(false);
      } catch (NullPointerException e) {
        // Intentionally empty exception block
      }

      try {
        r.getRun2().setGold(false);
        r.getRun2().setSilver(false);
        r.getRun2().setBronze(false);
      } catch (NullPointerException e) {
        // Intentionally empty exception block
      }

      // todo check this logic   20141122
      try {
        if (lastBoatClass.compareTo(r.getBoat().getBoatClass()) != 0) {
          lastBoatClass = r.getBoat().getBoatClass();
          place = 1;
        }
        switch (place) {
          case 1:
            r.getBestRun().setGold(true);
            break;
          case 2:
            r.getBestRun().setSilver(true);
            break;
          case 3:
            r.getBestRun().setBronze(true);
            break;
          default:
            break;
        }
      } catch (NullPointerException e) {
        // Intentionally empty exception block
      }

      r.getBestRun().setPlaceInClass(place++);
    }
    return (sorted);
  }

  public String getHTTPGateHeadersString() {
    StringBuffer sb = new StringBuffer();

    for (int iGate = 1; iGate <= Race.getInstance().getNbrGates(); iGate++) {
      sb.append(String.format("<td>%d</td>", iGate));
    }

    return sb.toString();
  }

  public String getHTTPGateHeadersWidthString() {
    StringBuffer sb = new StringBuffer();

    for (int iGate = 1; iGate <= Race.getInstance().getNbrGates(); iGate++) {
      sb.append("<col span=\"1\" style=\"width: 3%;\">");
    }

    return sb.toString();
  }

  public void markClassRun(String boatClass, int runNbr, RaceRun.Status status) {
    for (RaceRun r : getCompletedRunsByClassTime()) {
      if (r.getRunNumber() == runNbr) {
        if (r.getBoat().getBoatClass().compareTo(boatClass) == 0) {
          r.setStatus(status);
        }
      }
    }
    updateResults(true);
  }

  ArrayList<String> classesRuns;

  public ArrayList getClassesRuns() {
    classesRuns = new ArrayList<String>();

    StringBuffer classRun = new StringBuffer();
    StringBuffer testClassRun;

    for (int run = 1; run < 3; run++) {
      for (RaceRun r : getCompletedRunsByClassTime()) {
        if (r.getRunNumber() == run) {
          testClassRun = new StringBuffer();
          testClassRun.append(r.getBoat().getBoatClass());
          testClassRun.append(":");
          testClassRun.append(run);
          testClassRun.append(":");
          testClassRun.append(r.getStatusString());

          if (testClassRun.toString().compareTo(classRun.toString()) != 0) {
            classRun = testClassRun;
            classesRuns.add(classRun.toString());
          }
        }
      }
    }
    return (classesRuns);
  }
}
Пример #24
0
 private void recordMofifTime() {
   Calendar c = new GregorianCalendar();
   c.setTime(new Date());
   c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 1);
   c.set(Calendar.SECOND, 0);
 }
  /**
   * Réagit au clique de la souris sur un bouton
   *
   * @param e L'ActionEvent généré
   */
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof JButton) {
      JButton b = (JButton) e.getSource();
      if (b.getName() == "statTab") { // Si on clique sur l'onglet statistiques
        cartes.show(panneau, "statistiques");
      } else if (b.getName() == "payTab") { // Si on clique sur l'onglet de paiement
        cartes.show(panneau, "paiement");
      } else if (b.getName() == "loginButton") { // Si on clique sur le bonton de login
        char[] input = passTextField.getPassword();
        String pass = new String("root"); // Le mot de passe
        if (pass.equals(new String(input))) {
          cartes.show(panneau, "paiement");
          loginLabel.setText("");
        } else loginLabel.setText("Mot de passe incorrect");

        Arrays.fill(input, '0');
        passTextField.selectAll();
      } else if (b.getName() == "annuler") { // Si clique sur annuler
        // On réserte la sélection et on déselectionne les tables
        ControleurTables.deleteSelection();
        this.tableCounter = 0;
        this.payTextField.setText("");
        this.valider.setEnabled(false);
        this.valider.setBackground(Color.GRAY);
      } else if (b.getName() == "valider") { // Si on clique sur valider

        // On récupère la date
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, (int) this.difTemps);
        // On récupère le mode de paiement sélectionné
        String type = new String("carte bleue");
        if (especes.isSelected()) {
          type = "especes";
        } else if (cheque.isSelected()) {
          type = "cheque";
        }
        try { // On verifie que le prix rentré est correct
          // On met tout dans le meme try pour annuler l'insertion de la commande dans la bdd en cas
          // d'erreur
          float prix = Float.parseFloat(payTextField.getText());
          ModelePaiement mP = new ModelePaiement();
          mP.insert(cal, prix, type);
          // On recupère la selection
          ArrayList<Table> tab = ControleurTables.getSelection();
          // On met toutes les tables à laver
          for (int i = 0; i < tab.size(); i++) {
            tab.get(i).setStatut(Table.ALAVER);
            tab.get(i).setNom(null);
          }
          // On déselectionne les tables
          ControleurTables.deleteSelection();
          this.tableCounter = 0;
          this.payTextField.setText("");
          this.valider.setEnabled(false);
          this.valider.setBackground(Color.GRAY);
          // On insère le paiement dans la bdd
          modeleTable.updateTables(this.tables);
        } catch (NumberFormatException nfe) {
          JOptionPane.showMessageDialog(
              null, "Veuillez entrez un rpix valide.", "Erreur prix", JOptionPane.ERROR_MESSAGE);
        }
      } else if (b.getName() == "trier") { // Si on appuie sur trier
        float ca = -1;
        ModelePaiement mP = new ModelePaiement();
        if (service.isSelected()) { // Si on selection le chiffre d'affaire par service
          ca =
              mP.getCAService(
                  (String)
                      serviceComboBox
                          .getSelectedItem()); // On sélectonne le chiffre d'affaire en focntion du
                                               // service

        } else if (date.isSelected()) { // Si on selection le chiffre d'affaire par date
          try { // On verifie que la date est bien valide
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            cal.setTime(sdf.parse(dateTextField.getText()));
            ca = mP.getCADate(cal); // On va chercher le chiffre d'affaire en fonction de la date
          } catch (Exception npe) {
            JOptionPane.showMessageDialog(
                null,
                "Veuillez entrez une date de la forme 03/06/2012.",
                "Erreur date",
                JOptionPane.ERROR_MESSAGE);
          }
        }

        if (ca > -1) { // Si on a récupérer un chiffre d'affaire
          chiffreAffaire.setText("Chiffre d'affaire : " + Float.toString(ca));
        }
      } else if (b.getName() == "option") { // Si on clique sur option
        String strDate =
            JOptionPane.showInputDialog(null, "Réglage de temps (ex: 03/06/1996 15:06) ", null);

        try {
          Calendar cal = Calendar.getInstance();
          Calendar now = Calendar.getInstance();

          SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
          cal.setTime(sdf.parse(strDate));
          difTemps =
              (int)
                  ((cal.getTimeInMillis() - now.getTimeInMillis())
                      / 1000); // Transformation en secondes
          if ((cal.getTimeInMillis() - now.getTimeInMillis()) % 1000 > 0) {
            difTemps++;
          }
        } catch (Exception exep) {
          JOptionPane.showMessageDialog(
              null,
              "Vous devez entrer une date valide (ex: 03/06/1996 15:06).",
              "Date invalide",
              JOptionPane.ERROR_MESSAGE);
        }
      }
    }
  }
Пример #26
0
    public TaskRead(Map map1, Map m_max, Map m_min, DBCollection coll, ModbusSlaveSet slave) {
      try {
        //// 此处只要点击开始就能保存数据
        /// 方案:利用数据源发送单个布尔型变量(1,0)交替,链接成功,先判断是否链接成功,然后在保存数据
        synchronized (slave) {
          Map map = new HashMap();
          Set set1 = map1.entrySet();
          Iterator it1 = set1.iterator();
          while (it1.hasNext()) {
            Map.Entry<String, Map<String, String>> entry =
                (Map.Entry<String, Map<String, String>>) it1.next();
            Map<String, String> map2 = entry.getValue();
            for (Iterator it2 = map2.entrySet().iterator(); it2.hasNext(); ) {
              Map.Entry<String, String> entry2 = (Map.Entry<String, String>) it2.next();
              String name = entry2.getKey().toString();
              String paramAddr = entry2.getValue().toString();
              int fun = (int) (Double.parseDouble(paramAddr));
              if (paramAddr.substring(0, 1).equals("4")) {
                Short d4 = slave.getProcessImage(1).getInputRegister(fun % 10000);
                double dmax = (Double) m_max.get(name);
                double dmin = (Double) m_min.get(name);
                double dValue = 0;
                if (d4 >= 0) {
                  dValue = dmax * d4 / 32000;
                } else {
                  dValue = dmin * d4 / (-32000);
                }
                map.put(name, dValue);
              }
              if (paramAddr.substring(0, 1).equals("3")) {
                Short d3 = slave.getProcessImage(1).getHoldingRegister(fun % 10000);
                double dmax = (Double) m_max.get(name);
                double dmin = (Double) m_min.get(name);
                double dValue = 0;

                if (d3 >= 0) {
                  dValue = dmax * d3 / 32000;
                } else {
                  dValue = dmin * d3 / (-32000);
                }
                map.put(name, dValue);
              }
              if (paramAddr.substring(0, 1).equals("2")) {
                map.put(name, slave.getProcessImage(2).getInput(fun % 10000));
              }
              if (paramAddr.substring(0, 1).equals("1")) {
                Boolean a = slave.getProcessImage(2).getCoil(fun % 10000 - 1);
                map.put(name, a);
              }
            }
          }

          Calendar calendar = Calendar.getInstance();
          Date dd = calendar.getTime();

          BasicDBObject doc = new BasicDBObject();
          doc.put("_id", dd);

          Set set = map.entrySet();
          Iterator it = set.iterator();
          while (it.hasNext()) {
            Map.Entry<String, String> entry1 = (Map.Entry<String, String>) it.next();
            doc.put(entry1.getKey(), entry1.getValue());
          }
          coll.insert(doc);
        }
      } catch (Exception ex) {
      }
    }
  // Method:
  private void populateData() {

    textpadSeq_ = new RCT.TextpadMsgHistSeqHolder();
    data_ = new Object[0][0];

    if (ARCH_SEL_TODAY == selectionType_) {

      // Get today's date
      Date now = new Date();
      Calendar cal = Calendar.getInstance();
      cal.setTime(now);
      int day = cal.get(Calendar.DAY_OF_MONTH);
      int month = cal.get(Calendar.MONTH) + 1;
      int year = cal.get(Calendar.YEAR);

      String fromDate = year + "-" + month + "-" + day + " 00:00:00";

      String toDate = year + "-" + month + "-" + day + " 23:59:59";

      try {

        TeamModule.getTextpadArchiveTimeRange(className_, teamName_, fromDate, toDate, textpadSeq_);
      } catch (RCT.TeamServerPackage.DataSelectionExceedsLimit dsel) {

        JOptionPane.showMessageDialog(
            SessionModule.getFrame(),
            LangModule.i18n.getString("ExceptionDialog3"),
            LangModule.i18n.getString("ExceptionDialog1"),
            JOptionPane.WARNING_MESSAGE);
        return;
      }
    } else if (ARCH_SEL_TIMERANGE == selectionType_) {

      try {

        TeamModule.getTextpadArchiveTimeRange(
            className_, teamName_, fromDate_, toDate_, textpadSeq_);
      } catch (RCT.TeamServerPackage.DataSelectionExceedsLimit dsel) {

        JOptionPane.showMessageDialog(
            SessionModule.getFrame(),
            LangModule.i18n.getString("ExceptionDialog3"),
            LangModule.i18n.getString("ExceptionDialog1"),
            JOptionPane.WARNING_MESSAGE);
        return;
      }
    }

    // Check if we received any textpads
    if (0 < textpadSeq_.value.length) {

      data_ = new Object[textpadSeq_.value.length][TEXTPAD_N_FIELDS];

      for (int i = 0; i < textpadSeq_.value.length; i++) {

        data_[i][TEXTPAD_ID] = textpadSeq_.value[i].id;
        data_[i][TEXTPAD_NAME] = textpadSeq_.value[i].name;
        data_[i][TEXTPAD_DATE] = Utility.getDateAndTime(textpadSeq_.value[i].date);
      }
    }
  }
Пример #28
0
 /** Return second */
 public int getSecond() // 取得秒數
     {
   return calendar.get(Calendar.SECOND);
 }
Пример #29
0
    public TaskWrite(Map map1, Map m_max, Map m_min, DBCollection coll, ModbusSlaveSet slave) {

      try {
        synchronized (slave) {
          Calendar calener = Calendar.getInstance();
          Date d1 = calener.getTime();
          Date d2 = new Date(calener.getTime().getTime() - 5000);
          BasicDBObject b2 = new BasicDBObject();
          b2.put("$gte", d2);
          b2.put("$lte", d1);
          DBCursor cursor =
              coll.find(new BasicDBObject("_id", b2)).sort(new BasicDBObject("_id", -1)).limit(1);
          while (cursor.hasNext()) {
            DBObject dbo = cursor.next();
            Set set1 = map1.entrySet();
            Iterator it1 = set1.iterator();
            while (it1.hasNext()) {
              Map.Entry<String, Map<String, String>> entry =
                  (Map.Entry<String, Map<String, String>>) it1.next();
              Map<String, String> map2 = entry.getValue();
              for (Iterator it2 = map2.entrySet().iterator(); it2.hasNext(); ) {
                Map.Entry<String, String> entry2 = (Map.Entry<String, String>) it2.next();
                String name = entry2.getKey().toString();
                String paramAddr = entry2.getValue().toString();
                int fun = (int) (Double.parseDouble(paramAddr));
                if (paramAddr.substring(0, 1).equals("4")) {
                  double value = Double.parseDouble(dbo.get(name).toString());
                  double dmax = (Double) m_max.get(name);
                  double dmin = (Double) m_min.get(name);
                  double dValue = 0;
                  if (value > dmax || value < dmin) {
                    if (value >= 0) {
                      dValue = 32000 * (int) (value / dmax);
                    }
                    if (value < 0) {
                      dValue = -32000 * (int) (value / dmin);
                    }
                    // slave.getProcessImage(3).setInputRegister(fun % 10000, (short) dValue);
                  } else { /// 参数超限报警
                    JOptionPane.showMessageDialog(null, "参数超限");
                    slave.stop();
                  }
                }
                if (paramAddr.substring(0, 1).equals("3")) {
                  double value = Double.parseDouble(dbo.get(name).toString());
                  double dmax = (Double) m_max.get(name);
                  double dmin = (Double) m_min.get(name);
                  double dValue = 0;
                  if (value > dmax || value < dmin) {
                    if (value >= 0) {
                      dValue = 32000 * (int) (value / dmax);
                    }
                    if (value < 0) {
                      dValue = -32000 * (int) (value / dmin);
                    }
                    // slave.getProcessImage(3).setHoldingRegister(fun % 10000, (short) dValue);
                  } else { /// 参数超限报警
                    JOptionPane.showMessageDialog(null, "参数超限");
                    slave.stop();
                  }
                  ;
                }
                if (paramAddr.substring(0, 1).equals("2")) {
                  String value = dbo.get(name).toString();
                  /// slave.getProcessImage(4).setInput(fun % 10000, Boolean.valueOf(value));
                }
                if (paramAddr.substring(0, 1).equals("1")) {
                  String value = dbo.get(name).toString();
                  // slave.getProcessImage(4).setCoil(fun % 10000, Boolean.valueOf(value));
                }
              }
            }
          }
        }
      } catch (Exception ex) {
      }
    }
Пример #30
0
 /** Return minute */
 public int getMinute() // 取得分鐘
     {
   return calendar.get(Calendar.MINUTE);
 }