Ejemplo n.º 1
0
 public static void main(String[] args) {
   Set<Watercolors> set1 = EnumSet.range(BRILLIANT_RED, VIRIDIAN_HUE);
   Set<Watercolors> set2 = EnumSet.range(CERULEAN_BLUE_HUE, BURNT_UMBER);
   print("set1: " + set1);
   print("set2: " + set2);
   print("union(set1, set2): " + union(set1, set2));
   Set<Watercolors> subset = intersection(set1, set2);
   print("intersection(set1, set2): " + subset);
   print("difference(set1, subset): " + difference(set1, subset));
   print("difference(set2, subset): " + difference(set2, subset));
   print("complement(set1, set2): " + complement(set1, set2));
 }
Ejemplo n.º 2
0
 /** @param args */
 public static void main(String[] args) {
   // TODO Auto-generated method stub
   Set<Watercolors> set1 = EnumSet.range(BRILLIANT_RED, VIRIDIAN_HUE);
   Set<Watercolors> set2 = EnumSet.range(CERULEAN_BLUE_HUE, BURNT_UMBER);
   System.out.println("set1 : " + set1);
   System.out.println("set2 : " + set2);
   System.out.println("union(set1, set2) : " + union(set1, set2));
   Set<Watercolors> subset = intersection(set1, set2);
   System.out.println("intersection(set1, set2) : " + subset);
   System.out.println("difference(set1, subset) : " + difference(set1, subset));
   System.out.println("differenct(set2, subset) : " + difference(set2, subset));
   System.out.println("complement(set1, set2) : " + complement(set1, set2));
 }
Ejemplo n.º 3
0
@SuppressWarnings("javadoc")
@RunWith(Parameterized.class)
public class CeusSoftRock extends GmmTest {

  private static String GMM_INPUTS = "CEUS_vs760_inputs.csv";
  private static String GMM_RESULTS = "CEUS_vs760_results.csv";

  static {
    try {
      inputsList = loadInputs(GMM_INPUTS);
    } catch (IOException ioe) {
      ioe.printStackTrace();
      System.exit(1);
    }
  }

  @Parameters(name = "{index}: {0} {2} {1}")
  public static Collection<Object[]> data() throws IOException {
    return loadResults(GMM_RESULTS);
  }

  public CeusSoftRock(int index, Gmm gmm, Imt imt, double exMedian, double exSigma) {
    super(index, gmm, imt, exMedian, exSigma);
  }

  /* Result generation sets */
  private static Set<Gmm> gmms = EnumSet.range(AB_06_PRIME, TORO_97_MB);
  private static Set<Imt> imts = EnumSet.of(PGA, SA0P2, SA1P0, SA2P0);

  public static void main(String[] args) throws IOException {
    GmmTest.generateResults(gmms, imts, GMM_INPUTS, GMM_RESULTS);
  }
}
Ejemplo n.º 4
0
 private static ImmutableMap<String, TokenKind> buildKeywords(TokenKind start, TokenKind end) {
   ImmutableMap.Builder<String, TokenKind> map = ImmutableMap.builder();
   for (TokenKind keyword : EnumSet.range(start, end)) {
     map.put(keyword.value, keyword);
   }
   return map.build();
 }
Ejemplo n.º 5
0
  private ListBox createScheduleCombo() {
    final ScheduleEditor localThis = this;
    ListBox lb = new ListBox();
    lb.setVisibleItemCount(1);
    // lb.setStyleName("scheduleCombo"); //$NON-NLS-1$
    lb.addChangeHandler(
        new ChangeHandler() {

          @Override
          public void onChange(ChangeEvent event) {
            localThis.handleScheduleChange();
          }
        });

    // add all schedule types to the combobox
    for (ScheduleType schedType : EnumSet.range(ScheduleType.RUN_ONCE, ScheduleType.CRON)) {
      if (!isBlockoutDialog
          || (schedType != ScheduleType.CRON
              && schedType != ScheduleType.SECONDS
              && schedType != ScheduleType.MINUTES
              && schedType != ScheduleType.HOURS)) {
        lb.addItem(schedType.toString());
      }
    }
    lb.setItemSelected(0, true);

    return lb;
  }
 public static TemporalValue stringToTemporalValue(String temporalValue) throws EnumException {
   for (TemporalValue v : EnumSet.range(TemporalValue.SECONDS, TemporalValue.YEARLY)) {
     if (v.toString().equals(temporalValue)) {
       return v;
     }
   }
   throw new EnumException(Messages.getString("schedule.invalidTemporalValue", temporalValue));
 }
Ejemplo n.º 7
0
 public static ScheduleType stringToScheduleType(String strSchedule) throws EnumException {
   for (ScheduleType v : EnumSet.range(ScheduleType.RUN_ONCE, ScheduleType.CRON)) {
     if (v.toString().equals(strSchedule)) {
       return v;
     }
   }
   throw new EnumException(MSGS.invalidTemporalValue(scheduleValue.toString()));
 }
  private ListBox createWhichWeekListBox() {

    ListBox l = new ListBox();
    for (WeekOfMonth week : EnumSet.range(WeekOfMonth.FIRST, WeekOfMonth.LAST)) {
      l.addItem(Messages.getString(week.toString()));
    }

    return l;
  }
Ejemplo n.º 9
0
/**
 * Enumerates a small number of languages, which are identified by their IANA code
 * (http://www.iana.org/assignments/language-subtag-registry).
 */
public enum Language {
  DUTCH("nl", "Dutch"), //
  ENGLISH("en", "English"), //
  FRENCH("fr", "French"), //
  GERMAN("de", "German"), //
  CLASSIC_GREEK("grc", "Greek"), //
  ITALIAN("it", "Italian"), //
  LATIN("la", "Latin"), //
  PORTUGUESE("pt", "Portuguese"), //
  SPANISH("es", "Spanish"), //
  UNKNOWN("?", "?");

  /** Regular languages, i.e., all except <code>UNKNOWN</code>. */
  public static final Set<Language> PROPER = EnumSet.range(DUTCH, SPANISH);

  private static final Map<String, Language> LANGUAGE_MAP;

  static {
    LANGUAGE_MAP = Maps.newHashMap();
    for (Language language : Language.values()) {
      LANGUAGE_MAP.put(language.getCode(), language);
    }
  }

  public static Language getInstance(String code) {
    Language language = (code != null) ? LANGUAGE_MAP.get(code) : null;
    return (language != null) ? language : Language.UNKNOWN;
  }

  public static String nameFor(String code) {
    return getInstance(code).getName();
  }

  // ---------------------------------------------------------------------------

  private final String code;
  private final String name;

  private Language(String code, String name) {
    this.code = code;
    this.name = name;
  }

  public String getCode() {
    return code;
  }

  public String getName() {
    return name;
  }

  @Override
  public String toString() {
    return name;
  }
}
 public List<DayOfWeek> getCheckedDays() {
   ArrayList<DayOfWeek> checkedDays = new ArrayList<DayOfWeek>();
   for (DayOfWeek d : EnumSet.range(DayOfWeek.SUN, DayOfWeek.SAT)) {
     CheckBox cb = dayToCheckBox.get(d);
     if (cb.isChecked()) {
       checkedDays.add(d);
     }
   }
   return checkedDays;
 }
Ejemplo n.º 11
0
  public void checkMap(SessionState ss) {
    if (map.isEmpty()) {
      for (Lists mylist : EnumSet.range(Lists.MYLIST, Lists.MAYBELIST)) {
        for (Types typeval : Types.values()) {
          HashMap<String, Integer> own = new HashMap<String, Integer>();

          listName = mylist.getListName(typeval.getName());
          map.put(listName, own);
        }
      }
    } else return;
  }
Ejemplo n.º 12
0
  public static void main(String[] args) {
    System.out.println("All books:\n");

    // print all books in enum Book
    for (Book book : Book.values())
      System.out.printf("%-10s%-45s%s\n", book, book.getTitle(), book.getCopyrightYear());

    System.out.println("\nDisplay a range of enum constants:\n");

    // print first four books
    for (Book book : EnumSet.range(Book.JHTP, Book.CPPHTP))
      System.out.printf("%-10s%-45s%s\n", book, book.getTitle(), book.getCopyrightYear());
  } // end main
Ejemplo n.º 13
0
  static {
    Relation.aRelationSet = EnumSet.range(Relation.EXPLICITLY_CALLS, Relation.REFERENCES);
    Relation.tRelationSet = EnumSet.complementOf(Relation.aRelationSet);
    // cRelationSet = EnumSet.range(Relation.T_EXPLICITLY_CALLS, Relation.T_REFERENCES);

    Relation.aRelationMap = new EnumMap<Type, Relation>(Type.class);
    Relation.tRelationMap = new EnumMap<Type, Relation>(Type.class);

    for (final Relation lRelation : Relation.aRelationSet)
      Relation.aRelationMap.put(lRelation.getType(), lRelation);
    for (final Relation lTransRelation : Relation.tRelationSet)
      Relation.tRelationMap.put(lTransRelation.getType(), lTransRelation);
  }
Ejemplo n.º 14
0
  @Override
  public boolean apply(Player p) {
    PlayingCard draw = context.flipCard();

    boolean hit =
        (draw.getSuit() == Suit.Spades
            && EnumSet.range(Face.Two, Face.Nine).contains(draw.getFace()));

    if (hit) {
      p.loseLife();
      p.loseLife();
      p.loseLife();
    }

    return hit;
  }
Ejemplo n.º 15
0
 @Override
 public EnumSet<TickType> ticks() {
   return EnumSet.range(TickType.SERVER, TickType.SERVER);
 }
Ejemplo n.º 16
0
 public TileEnergyUser() {
   super();
   MagicConnections.registerConnector(
       this, EnumSet.range(ForgeDirection.DOWN, ForgeDirection.EAST));
 }
public class SortTiming {

  /** Private Constructor */
  private SortTiming() {}

  static int[] naturalRandomArray(int len, int maxVal) {
    int[] a = new int[len];
    Random rand = new Random();
    for (int i = 0; i < len; ++i) {
      a[i] = rand.nextInt(maxVal + 1);
    }
    return a;
  }

  static enum SequenceKind {
    UNSORTED,
    ALMOST_SORTED,
    REPEATED_VALUES;
  }

  static enum Algorithm {
    SSORT,
    ISORT,
    ISORT_BIN,
    MSORT_BASIC,
    MSORT_NO_GAR,
    MSORT_ALT,
    PAR_MSORT,
    QSORT_BASIC,
    QSORT_HOARE,
    PAR_QSORT,
    HSORT,
    JAVASORT,
    JAVASORT_PAR;
  }

  public static void sort(Algorithm algo, int[] a) {
    switch (algo) {
      case SSORT:
        ssort(a);
        break;
      case ISORT:
        isort(a);
        break;
      case ISORT_BIN:
        isortBin(a);
        break;
      case MSORT_BASIC:
        msortBasic(a);
        break;
      case MSORT_NO_GAR:
        msortNoGarbage(a);
        break;
      case MSORT_ALT:
        msortAlt(a);
        break;
      case PAR_MSORT:
        parallelMergesort(a);
        break;
      case QSORT_BASIC:
        qsortBasic(a);
        break;
      case QSORT_HOARE:
        qsortHoare(a);
        break;
      case PAR_QSORT:
        parallelQuicksort(a);
        break;
      case HSORT:
        hsort(a);
        break;
      case JAVASORT:
        Arrays.sort(a);
        break;
      case JAVASORT_PAR:
        Arrays.parallelSort(a);
        break;
    }
  }

  static EnumSet<Algorithm> quadraticVsOptimal =
      EnumSet.range(Algorithm.SSORT, Algorithm.MSORT_BASIC);

  static EnumSet<Algorithm> optimal = EnumSet.range(Algorithm.MSORT_BASIC, Algorithm.JAVASORT_PAR);

  static double executionTime(Algorithm algo, int[] a) {
    long t1 = nanoTime();
    sort(algo, a);
    long t2 = nanoTime();
    if (!isSorted(a)) throw new RuntimeException("not ordered");
    return (t2 - t1) / 1E6;
  }

  /**
   * Crea una riga della tabella sull'output out, per sequenze di genere kind, eseguendo tutti gli
   * algoritmi algorithms, su un array di lunghezza len
   */
  static void runAllAlgorithms(
      EnumSet<Algorithm> algorithms, SequenceKind kind, PrintWriter out, int len) {
    int maxValue = (kind == SequenceKind.REPEATED_VALUES) ? len / 3 : 9 * len / 10;
    int[] array = naturalRandomArray(len, maxValue);
    if (kind == SequenceKind.ALMOST_SORTED) {
      Arrays.sort(array);
      swap(array, len / 3, 2 * len / 3);
    }

    out.printf("%6d;", len);
    System.out.println(len);
    for (Algorithm algo : algorithms) {
      System.out.println(algo.toString());
      int[] arrayCopy = Arrays.copyOf(array, array.length);
      double time = executionTime(algo, arrayCopy);
      out.printf("%9.2f;", time);
    }
    out.println();
    System.out.println();
  }

  /**
   * Crea una tabella sull'output out, per tutti i generi di sequenze, eseguendo tutti gli algoritmi
   * su array di lunghezze via via crescenti, da step fino a maxLength
   */
  static void makeTable(EnumSet<Algorithm> algorithms, int step, int maxLength, String fileName)
      throws IOException {
    ;
    FileWriter outFile = new FileWriter(fileName, false);
    PrintWriter writer = new PrintWriter(outFile);
    writer.println("sep=;");
    writer.println(
        "Test a on a int array: "
            + getProperty("os.name")
            + " Java "
            + getProperty("java.version"));
    for (SequenceKind kind : SequenceKind.values()) {
      writer.println(kind.toString());
      System.out.println(kind.toString() + "\n");
      for (Algorithm algo : algorithms) writer.print(";" + algo.toString());
      writer.println();
      for (int len = step; len <= maxLength; len += step) {
        runAllAlgorithms(algorithms, kind, writer, len);
      }
      writer.println();
    }
    writer.close();
    System.out.println();
    System.out.println();
  }

  public static void main(String[] args) throws IOException {
    makeTable(quadraticVsOptimal, 50000, 150000, "quadraticTimes.csv");
    makeTable(optimal, 100000, 2000000, "optimalTimes.csv");
    System.out.println("end!");
  }
}
Ejemplo n.º 18
0
/**
 * @author Alexei Drummond
 * @author Andrew Rambaut
 * @author Walter Xie
 */
public class PartitionModelPanel extends OptionsPanel {

  private static final boolean ENABLE_STOCHASTIC_DOLLO = true;

  // Components
  private static final long serialVersionUID = -1645661616353099424L;

  private JComboBox nucSubstCombo =
      new JComboBox(EnumSet.range(NucModelType.HKY, NucModelType.TN93).toArray());
  private JComboBox aaSubstCombo = new JComboBox(AminoAcidModelType.values());
  private JComboBox binarySubstCombo =
      new JComboBox(
          new BinaryModelType[] {BinaryModelType.BIN_SIMPLE, BinaryModelType.BIN_COVARION});
  private JCheckBox useAmbiguitiesTreeLikelihoodCheck =
      new JCheckBox("Use ambiguities in the tree likelihood associated with this model");

  private JComboBox frequencyCombo = new JComboBox(FrequencyPolicyType.values());

  private JComboBox heteroCombo =
      new JComboBox(new String[] {"None", "Gamma", "Invariant Sites", "Gamma + Invariant Sites"});

  private JComboBox gammaCatCombo =
      new JComboBox(new String[] {"4", "5", "6", "7", "8", "9", "10"});
  private JLabel gammaCatLabel;

  private JComboBox codingCombo =
      new JComboBox(
          new String[] {
            "Off", "2 partitions: positions (1 + 2), 3", "3 partitions: positions 1, 2, 3"
          });

  private JCheckBox substUnlinkCheck =
      new JCheckBox("Unlink substitution rate parameters across codon positions");
  private JCheckBox heteroUnlinkCheck =
      new JCheckBox("Unlink rate heterogeneity model across codon positions");
  private JCheckBox freqsUnlinkCheck =
      new JCheckBox("Unlink base frequencies across codon positions");

  private JButton setYang96Button;
  private JButton setSRD06Button;

  private JCheckBox dolloCheck = new JCheckBox("Use stochastic Dollo model");
  // private JComboBox dolloCombo = new JComboBox(new String[]{"Analytical",
  // "Sample"});

  private JComboBox discreteTraitSiteModelCombo = new JComboBox(DiscreteSubstModelType.values());
  private JCheckBox activateBSSVS =
      new JCheckBox(
          // "Activate BSSVS"
          "Infer social network with BSSVS");

  private JComboBox continuousTraitSiteModelCombo =
      new JComboBox(ContinuousSubstModelType.values());

  private JCheckBox latLongCheck =
      new JCheckBox("Bivariate trait represents latitude and longitude");

  private JCheckBox useLambdaCheck =
      new JCheckBox("Estimate phylogenetic signal using tree transform");

  private JTextArea citationText;

  // =========== micro sat ===========
  private JTextField microsatName = new JTextField();
  private WholeNumberField microsatMax = new WholeNumberField(2, Integer.MAX_VALUE);
  private WholeNumberField microsatMin = new WholeNumberField(1, Integer.MAX_VALUE);
  private JComboBox rateProportionCombo =
      new JComboBox(MicroSatModelType.RateProportionality.values());
  private JComboBox mutationBiasCombo = new JComboBox(MicroSatModelType.MutationalBias.values());
  private JComboBox phaseCombo = new JComboBox(MicroSatModelType.Phase.values());
  JCheckBox shareMicroSatCheck =
      new JCheckBox("Share one microsatellite among all substitution model(s)");

  protected final PartitionSubstitutionModel model;

  public PartitionModelPanel(final PartitionSubstitutionModel partitionModel) {

    super(12, (OSType.isMac() ? 6 : 24));

    this.model = partitionModel;

    initCodonPartitionComponents();

    PanelUtils.setupComponent(nucSubstCombo);
    nucSubstCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setNucSubstitutionModel((NucModelType) nucSubstCombo.getSelectedItem());
          }
        });
    nucSubstCombo.setToolTipText("<html>Select the type of nucleotide substitution model.</html>");

    PanelUtils.setupComponent(aaSubstCombo);
    aaSubstCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            AminoAcidModelType type = (AminoAcidModelType) aaSubstCombo.getSelectedItem();
            model.setAaSubstitutionModel(type);
            citationText.setText(type.getCitation().toString());
          }
        });
    aaSubstCombo.setToolTipText("<html>Select the type of amino acid substitution model.</html>");

    PanelUtils.setupComponent(binarySubstCombo);
    binarySubstCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setBinarySubstitutionModel((BinaryModelType) binarySubstCombo.getSelectedItem());
            useAmbiguitiesTreeLikelihoodCheck.setSelected(
                binarySubstCombo.getSelectedItem() == BinaryModelType.BIN_COVARION);
            useAmbiguitiesTreeLikelihoodCheck.setEnabled(
                binarySubstCombo.getSelectedItem() != BinaryModelType.BIN_COVARION);
          }
        });
    binarySubstCombo.setToolTipText("<html>Select the type of binary substitution model.</html>");

    PanelUtils.setupComponent(useAmbiguitiesTreeLikelihoodCheck);
    useAmbiguitiesTreeLikelihoodCheck.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setUseAmbiguitiesTreeLikelihood(useAmbiguitiesTreeLikelihoodCheck.isSelected());
          }
        });
    useAmbiguitiesTreeLikelihoodCheck.setToolTipText(
        "<html>Detemine useAmbiguities in &lt treeLikelihood &gt .</html>");

    PanelUtils.setupComponent(frequencyCombo);
    frequencyCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setFrequencyPolicy((FrequencyPolicyType) frequencyCombo.getSelectedItem());
          }
        });
    frequencyCombo.setToolTipText(
        "<html>Select the policy for determining the base frequencies.</html>");

    PanelUtils.setupComponent(heteroCombo);
    heteroCombo.setToolTipText(
        "<html>Select the type of site-specific rate<br>heterogeneity model.</html>");
    heteroCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {

            boolean gammaHetero =
                heteroCombo.getSelectedIndex() == 1 || heteroCombo.getSelectedIndex() == 3;

            model.setGammaHetero(gammaHetero);
            model.setInvarHetero(
                heteroCombo.getSelectedIndex() == 2 || heteroCombo.getSelectedIndex() == 3);

            if (gammaHetero) {
              gammaCatLabel.setEnabled(true);
              gammaCatCombo.setEnabled(true);
            } else {
              gammaCatLabel.setEnabled(false);
              gammaCatCombo.setEnabled(false);
            }

            if (codingCombo.getSelectedIndex() != 0) {
              heteroUnlinkCheck.setEnabled(heteroCombo.getSelectedIndex() != 0);
              heteroUnlinkCheck.setSelected(heteroCombo.getSelectedIndex() != 0);
            }
          }
        });

    PanelUtils.setupComponent(gammaCatCombo);
    gammaCatCombo.setToolTipText(
        "<html>Select the number of categories to use for<br>the discrete gamma rate heterogeneity model.</html>");
    gammaCatCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {

            model.setGammaCategories(gammaCatCombo.getSelectedIndex() + 4);
          }
        });

    setYang96Button = new JButton("Use Yang96 model");
    setYang96Button.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent ev) {
            setYang96Model();
          }
        });
    PanelUtils.setupComponent(setYang96Button);
    setYang96Button.setToolTipText(
        "<html>Sets a 3 codon-position model with independent GTR and Gamma as described in<br>"
            + "Yang (1996) <i>J Mol Evol</i> <b>42</b>: 587–596. This model is named 3' in this paper.</html>");

    setSRD06Button = new JButton("Use SRD06 model");
    setSRD06Button.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent ev) {
            setSRD06Model();
          }
        });
    PanelUtils.setupComponent(setSRD06Button);
    setSRD06Button.setToolTipText(
        "<html>Sets the SRD06 model as described in<br>"
            + "Shapiro, Rambaut & Drummond (2006) <i>MBE</i> <b>23</b>: 7-9.</html>");

    citationText = new JTextArea(1, 40);
    citationText.setLineWrap(true);
    citationText.setWrapStyleWord(true);
    citationText.setEditable(false);
    citationText.setFont(this.getFont());
    citationText.setOpaque(false);
    AminoAcidModelType type = (AminoAcidModelType) aaSubstCombo.getSelectedItem();
    citationText.setText(type.getCitation().toString());

    dolloCheck.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            if (dolloCheck.isSelected()) {
              binarySubstCombo.setSelectedIndex(0);
              binarySubstCombo.setEnabled(false);
              useAmbiguitiesTreeLikelihoodCheck.setSelected(true);
              useAmbiguitiesTreeLikelihoodCheck.setEnabled(false);
              frequencyCombo.setEnabled(false);
              frequencyCombo.setSelectedItem(FrequencyPolicyType.EMPIRICAL);
              heteroCombo.setSelectedIndex(0);
              heteroCombo.setEnabled(false);
              model.setBinarySubstitutionModel(BinaryModelType.BIN_DOLLO);
              model.setDolloModel(true);
              DolloComponentOptions comp =
                  (DolloComponentOptions)
                      model.getOptions().getComponentOptions(DolloComponentOptions.class);
              comp.createParameters(model.getOptions());
              comp.setActive(true);

            } else {
              binarySubstCombo.setEnabled(true);
              useAmbiguitiesTreeLikelihoodCheck.setEnabled(true);
              frequencyCombo.setEnabled(true);
              heteroCombo.setEnabled(true);
              model.setBinarySubstitutionModel(
                  (BinaryModelType) binarySubstCombo.getSelectedItem());
              model.setDolloModel(false);
            }
          }
        });

    PanelUtils.setupComponent(dolloCheck);
    //        dolloCheck.addChangeListener(new ChangeListener() {
    //            public void stateChanged(ChangeEvent e) {
    //                model.setDolloModel(true);
    //            }
    //        });
    dolloCheck.setEnabled(true);
    dolloCheck.setToolTipText(
        "<html>Activates a Stochastic Dollo model as described in<br>"
            + "Alekseyenko, Lee & Suchard (2008) <i>Syst Biol</i> <b>57</b>: 772-784.</html>");

    PanelUtils.setupComponent(discreteTraitSiteModelCombo);
    discreteTraitSiteModelCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setDiscreteSubstType(
                (DiscreteSubstModelType) discreteTraitSiteModelCombo.getSelectedItem());
          }
        });

    PanelUtils.setupComponent(continuousTraitSiteModelCombo);
    continuousTraitSiteModelCombo.setToolTipText(
        "<html>Select the model of continuous random walk, either homogenous<br>"
            + "or relaxed random walk (RRW) with a choice of distributions.</html>");
    continuousTraitSiteModelCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setContinuousSubstModelType(
                (ContinuousSubstModelType) continuousTraitSiteModelCombo.getSelectedItem());
          }
        });

    PanelUtils.setupComponent(latLongCheck);
    latLongCheck.setToolTipText(
        "<html>Specify whether this is a geographical trait representing <br>"
            + "latitude and longitude. Provides appropriate statistics to log file.</html>");

    latLongCheck.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setIsLatitudeLongitude(latLongCheck.isSelected());
          }
        });
    latLongCheck.setEnabled(false);

    PanelUtils.setupComponent(useLambdaCheck);
    useLambdaCheck.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            ContinuousComponentOptions component =
                (ContinuousComponentOptions)
                    model.getOptions().getComponentOptions(ContinuousComponentOptions.class);
            component.setUseLambda(model, useLambdaCheck.isSelected());
          }
        });
    useLambdaCheck.setToolTipText(
        "<html>Estimate degree of phylogenetic correlation in continuous traits using <br>"
            + "a tree transform. Inspired by Pagel (1999), described in Lemey et al (2013) <i>in prep</i></html>");

    PanelUtils.setupComponent(activateBSSVS);
    activateBSSVS.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setActivateBSSVS(activateBSSVS.isSelected());
          }
        });
    activateBSSVS.setToolTipText(
        "<html>Activates Bayesian stochastic search variable selection on the rates as described in<br>"
            + "Lemey, Rambaut, Drummond & Suchard (2009) <i>PLoS Computational Biology</i> <b>5</b>: e1000520</html>");

    // ============ micro-sat ================
    microsatName.setColumns(30);
    microsatName.addKeyListener(
        new java.awt.event.KeyListener() {
          public void keyTyped(KeyEvent e) {}

          public void keyPressed(KeyEvent e) {}

          public void keyReleased(KeyEvent e) {
            model.getMicrosatellite().setName(microsatName.getText());
          }
        });
    microsatMax.setColumns(10);
    microsatMax.addKeyListener(
        new java.awt.event.KeyListener() {
          public void keyTyped(KeyEvent e) {}

          public void keyPressed(KeyEvent e) {}

          public void keyReleased(KeyEvent e) {
            model.getMicrosatellite().setMax(Integer.parseInt(microsatMax.getText()));
          }
        });
    microsatMin.setColumns(10);
    microsatMin.addKeyListener(
        new java.awt.event.KeyListener() {
          public void keyTyped(KeyEvent e) {}

          public void keyPressed(KeyEvent e) {}

          public void keyReleased(KeyEvent e) {
            model.getMicrosatellite().setMin(Integer.parseInt(microsatMin.getText()));
          }
        });

    PanelUtils.setupComponent(shareMicroSatCheck);
    shareMicroSatCheck.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            model.getOptions().shareMicroSat = shareMicroSatCheck.isSelected();
            if (shareMicroSatCheck.isSelected()) {
              model.getOptions().shareMicroSat();
            } else {
              model.getOptions().unshareMicroSat();
            }
            setOptions();
          }
        });

    PanelUtils.setupComponent(rateProportionCombo);
    rateProportionCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setRatePorportion(
                (MicroSatModelType.RateProportionality) rateProportionCombo.getSelectedItem());
          }
        });
    // rateProportionCombo.setToolTipText("<html>Select the type of microsatellite substitution
    // model.</html>");
    PanelUtils.setupComponent(mutationBiasCombo);
    mutationBiasCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setMutationBias(
                (MicroSatModelType.MutationalBias) mutationBiasCombo.getSelectedItem());
          }
        });
    PanelUtils.setupComponent(phaseCombo);
    phaseCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setPhase((MicroSatModelType.Phase) phaseCombo.getSelectedItem());
          }
        });

    setupPanel();
    setOpaque(false);
  }

  /**
   * Sets the components up according to the partition model - but does not layout the top level
   * options panel.
   */
  public void setOptions() {

    if (SiteModelsPanel.DEBUG) {
      String modelName = (model == null) ? "null" : model.getName();
      Logger.getLogger("dr.app.beauti").info("ModelsPanel.setModelOptions(" + modelName + ")");
    }

    if (model == null) {
      return;
    }

    int dataType = model.getDataType().getType();
    switch (dataType) {
      case DataType.NUCLEOTIDES:
        nucSubstCombo.setSelectedItem(model.getNucSubstitutionModel());
        frequencyCombo.setSelectedItem(model.getFrequencyPolicy());

        break;

      case DataType.AMINO_ACIDS:
        aaSubstCombo.setSelectedItem(model.getAaSubstitutionModel());

        break;

      case DataType.TWO_STATES:
      case DataType.COVARION:
        binarySubstCombo.setSelectedItem(model.getBinarySubstitutionModel());
        useAmbiguitiesTreeLikelihoodCheck.setSelected(model.isUseAmbiguitiesTreeLikelihood());

        break;

      case DataType.GENERAL:
        discreteTraitSiteModelCombo.setSelectedItem(model.getDiscreteSubstType());
        activateBSSVS.setSelected(model.isActivateBSSVS());
        break;

      case DataType.CONTINUOUS:
        continuousTraitSiteModelCombo.setSelectedItem(model.getContinuousSubstModelType());

        ContinuousComponentOptions component =
            (ContinuousComponentOptions)
                model.getOptions().getComponentOptions(ContinuousComponentOptions.class);

        latLongCheck.setSelected(model.isLatitudeLongitude());
        latLongCheck.setEnabled(model.getContinuousTraitCount() == 2);
        useLambdaCheck.setSelected(component.useLambda(model));
        break;
      case DataType.MICRO_SAT:
        microsatName.setText(model.getMicrosatellite().getName());
        microsatMax.setText(Integer.toString(model.getMicrosatellite().getMax()));
        microsatMin.setText(Integer.toString(model.getMicrosatellite().getMin()));
        shareMicroSatCheck.setSelected(model.getOptions().shareMicroSat);
        rateProportionCombo.setSelectedItem(model.getRatePorportion());
        mutationBiasCombo.setSelectedItem(model.getMutationBias());
        phaseCombo.setSelectedItem(model.getPhase());
        shareMicroSatCheck.setEnabled(
            model.getOptions().getPartitionSubstitutionModels(Microsatellite.INSTANCE).size() > 1);
        break;

      default:
        throw new IllegalArgumentException("Unknown data type");
    }

    if (model.isGammaHetero() && !model.isInvarHetero()) {
      heteroCombo.setSelectedIndex(1);
    } else if (!model.isGammaHetero() && model.isInvarHetero()) {
      heteroCombo.setSelectedIndex(2);
    } else if (model.isGammaHetero() && model.isInvarHetero()) {
      heteroCombo.setSelectedIndex(3);
    } else {
      heteroCombo.setSelectedIndex(0);
    }

    gammaCatCombo.setSelectedIndex(model.getGammaCategories() - 4);

    if (model.getCodonHeteroPattern() == null) {
      codingCombo.setSelectedIndex(0);
    } else if (model.getCodonHeteroPattern().equals("112")) {
      codingCombo.setSelectedIndex(1);
    } else {
      codingCombo.setSelectedIndex(2);
    }

    substUnlinkCheck.setSelected(model.isUnlinkedSubstitutionModel());
    heteroUnlinkCheck.setSelected(model.isUnlinkedHeterogeneityModel());
    freqsUnlinkCheck.setSelected(model.isUnlinkedFrequencyModel());

    dolloCheck.setSelected(model.isDolloModel());
  }

  /** Configure this panel for the Yang 96 codon position model */
  private void setYang96Model() {
    nucSubstCombo.setSelectedIndex(1);
    heteroCombo.setSelectedIndex(1);
    codingCombo.setSelectedIndex(2);
    substUnlinkCheck.setSelected(true);
    heteroUnlinkCheck.setSelected(true);
    freqsUnlinkCheck.setSelected(true);
  }

  /** Configure this panel for the Shapiro, Rambaut and Drummond 2006 codon position model */
  private void setSRD06Model() {
    nucSubstCombo.setSelectedIndex(0);
    heteroCombo.setSelectedIndex(1);
    codingCombo.setSelectedIndex(1);
    substUnlinkCheck.setSelected(true);
    heteroUnlinkCheck.setSelected(true);
    freqsUnlinkCheck.setSelected(false);
  }

  /** Lays out the appropriate components in the panel for this partition model. */
  private void setupPanel() {

    switch (model.getDataType().getType()) {
      case DataType.NUCLEOTIDES:
        addComponentWithLabel("Substitution Model:", nucSubstCombo);
        addComponentWithLabel("Base frequencies:", frequencyCombo);
        addComponentWithLabel("Site Heterogeneity Model:", heteroCombo);
        heteroCombo.setSelectedIndex(0);
        gammaCatLabel = addComponentWithLabel("Number of Gamma Categories:", gammaCatCombo);
        gammaCatCombo.setEnabled(false);

        addSeparator();

        addComponentWithLabel("Partition into codon positions:", codingCombo);

        JPanel panel2 = new JPanel();
        panel2.setOpaque(false);
        panel2.setLayout(new BoxLayout(panel2, BoxLayout.PAGE_AXIS));
        panel2.setBorder(BorderFactory.createTitledBorder("Link/Unlink parameters:"));
        panel2.add(substUnlinkCheck);
        panel2.add(heteroUnlinkCheck);
        panel2.add(freqsUnlinkCheck);

        addComponent(panel2);

        addComponent(setYang96Button);
        addComponent(setSRD06Button);

        break;

      case DataType.AMINO_ACIDS:
        addComponentWithLabel("Substitution Model:", aaSubstCombo);
        addComponentWithLabel("Citation:", citationText);

        addComponentWithLabel("Site Heterogeneity Model:", heteroCombo);
        heteroCombo.setSelectedIndex(0);
        gammaCatLabel = addComponentWithLabel("Number of Gamma Categories:", gammaCatCombo);
        gammaCatCombo.setEnabled(false);

        break;

      case DataType.TWO_STATES:
      case DataType.COVARION:
        addComponentWithLabel("Substitution Model:", binarySubstCombo);
        addComponentWithLabel("Base frequencies:", frequencyCombo);
        addComponentWithLabel("Site Heterogeneity Model:", heteroCombo);
        heteroCombo.setSelectedIndex(0);
        gammaCatLabel = addComponentWithLabel("Number of Gamma Categories:", gammaCatCombo);
        gammaCatCombo.setEnabled(false);

        addSeparator();

        addComponentWithLabel("", useAmbiguitiesTreeLikelihoodCheck);

        // Easy XML specification is currently only available for binary models
        if (ENABLE_STOCHASTIC_DOLLO) {
          addSeparator();
          addComponent(dolloCheck);
        }

        break;

      case DataType.GENERAL:
        addComponentWithLabel("Discrete Trait Substitution Model:", discreteTraitSiteModelCombo);
        addComponent(activateBSSVS);
        break;

      case DataType.CONTINUOUS:
        addComponentWithLabel("Continuous Trait Model:", continuousTraitSiteModelCombo);
        addComponent(latLongCheck);
        addSeparator();
        addComponent(useLambdaCheck);
        break;

      case DataType.MICRO_SAT:
        addComponentWithLabel("Microsatellite Name:", microsatName);
        addComponentWithLabel("Max of Length:", microsatMax);
        addComponentWithLabel("Min of Length:", microsatMin);
        addComponent(shareMicroSatCheck);

        addSeparator();

        addComponentWithLabel("Rate Proportionality:", rateProportionCombo);
        addComponentWithLabel("Mutational Bias:", mutationBiasCombo);
        addComponentWithLabel("Phase:", phaseCombo);
        break;

      default:
        throw new IllegalArgumentException("Unknown data type");
    }

    setOptions();
  }

  /** Initializes and binds the components related to modeling codon positions. */
  private void initCodonPartitionComponents() {

    PanelUtils.setupComponent(substUnlinkCheck);

    substUnlinkCheck.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setUnlinkedSubstitutionModel(substUnlinkCheck.isSelected());
          }
        });
    substUnlinkCheck.setEnabled(false);
    substUnlinkCheck.setToolTipText(
        ""
            + "<html>Gives each codon position partition different<br>"
            + "substitution model parameters.</html>");

    PanelUtils.setupComponent(heteroUnlinkCheck);
    heteroUnlinkCheck.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setUnlinkedHeterogeneityModel(heteroUnlinkCheck.isSelected());
          }
        });
    heteroUnlinkCheck.setEnabled(heteroCombo.getSelectedIndex() != 0);
    heteroUnlinkCheck.setToolTipText(
        "<html>Gives each codon position partition different<br>rate heterogeneity model parameters.</html>");

    PanelUtils.setupComponent(freqsUnlinkCheck);
    freqsUnlinkCheck.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {
            model.setUnlinkedFrequencyModel(freqsUnlinkCheck.isSelected());
          }
        });
    freqsUnlinkCheck.setEnabled(false);
    freqsUnlinkCheck.setToolTipText(
        "<html>Gives each codon position partition different<br>nucleotide frequency parameters.</html>");

    PanelUtils.setupComponent(codingCombo);
    codingCombo.setToolTipText("<html>Select how to partition the codon positions.</html>");
    codingCombo.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent ev) {

            switch (codingCombo.getSelectedIndex()) {
              case 0:
                model.setCodonHeteroPattern(null);
                break;
              case 1:
                model.setCodonHeteroPattern("112");
                break;
              default:
                model.setCodonHeteroPattern("123");
                break;
            }

            if (codingCombo.getSelectedIndex() != 0) {
              // codon position partitioning
              substUnlinkCheck.setEnabled(true);
              heteroUnlinkCheck.setEnabled(heteroCombo.getSelectedIndex() != 3);
              freqsUnlinkCheck.setEnabled(true);
              substUnlinkCheck.setSelected(true);
              heteroUnlinkCheck.setSelected(heteroCombo.getSelectedIndex() != 0);
              freqsUnlinkCheck.setSelected(true);

            } else {
              substUnlinkCheck.setEnabled(false);
              substUnlinkCheck.setSelected(false);
              heteroUnlinkCheck.setEnabled(false);
              heteroUnlinkCheck.setSelected(false);
              freqsUnlinkCheck.setEnabled(false);
              freqsUnlinkCheck.setSelected(false);
            }
          }
        });
  }
}
Ejemplo n.º 19
0
 /** {@inheritDoc} */
 @Override
 public boolean isAlive() {
   return EnumSet.range(RUNNING, DONE).contains(status);
 }
Ejemplo n.º 20
0
/**
 * <strong class="changed_modified_2_0 changed_modified_2_0_rev_a changed_modified_2_1
 * changed_modified_2_2">FacesServlet</strong> is a servlet that manages the request processing
 * lifecycle for web applications that are utilizing JavaServer Faces to construct the user
 * interface. <div class="changed_added_2_1">
 *
 * <p>If the application is running in a Servlet 3.0 (and beyond) container, the runtime must
 * provide an implementation of the {@link javax.servlet.ServletContainerInitializer} interface that
 * declares the following classes in its {@link javax.servlet.annotation.HandlesTypes} annotation.
 *
 * <ul>
 *   <li>{@link javax.faces.application.ResourceDependencies}
 *   <li>{@link javax.faces.application.ResourceDependency}
 *   <li>javax.faces.bean.ManagedBean
 *   <li>{@link javax.faces.component.FacesComponent}
 *   <li>{@link javax.faces.component.UIComponent}
 *   <li>{@link javax.faces.convert.Converter}
 *   <li>{@link javax.faces.convert.FacesConverter}
 *   <li>{@link javax.faces.event.ListenerFor}
 *   <li>{@link javax.faces.event.ListenersFor}
 *   <li>{@link javax.faces.render.FacesBehaviorRenderer}
 *   <li>{@link javax.faces.render.Renderer}
 *   <li>{@link javax.faces.validator.FacesValidator}
 *   <li>{@link javax.faces.validator.Validator}
 * </ul>
 *
 * <p>This servlet must automatically be mapped if it is <strong>not</strong> explicitly mapped in
 * <code>web.xml</code> or <code>web-fragment.xml</code> and one or more of the following conditions
 * are true.
 *
 * <ul>
 *   <li>
 *       <p>A <code>faces-config.xml</code> file is found in <code>WEB-INF</code>
 *   <li>
 *       <p>A <code>faces-config.xml</code> file is found in the <code>META-INF</code> directory of
 *       a jar in the application's classpath.
 *   <li>
 *       <p>A filename ending in <code>.faces-config.xml</code> is found in the <code>META-INF
 *       </code> directory of a jar in the application's classpath.
 *   <li>
 *       <p>The <code>javax.faces.CONFIG_FILES</code> context param is declared in <code>web.xml
 *       </code> or <code>web-fragment.xml</code>.
 *   <li>
 *       <p>The <code>Set</code> of classes passed to the <code>onStartup()</code> method of the
 *       <code>ServletContainerInitializer</code> implementation is not empty.
 * </ul>
 *
 * <p>If the runtime determines that the servlet must be automatically mapped, it must be mapped to
 * the following &lt;<code>url-pattern</code>&gt; entries.
 *
 * <ul>
 *   <li>/faces
 *   <li>*.jsf
 *   <li>*.faces
 * </ul>
 *
 * </div>
 *
 * <p><div class="changed_added_2_2">
 *
 * <p>This class must be annotated with {@code javax.servlet.annotation.MultipartConfig}. This
 * causes the Servlet container in which the JSF implementation is running to correctly handle
 * multipart form data.
 *
 * <p><strong>Some security considerations relating to this class</strong>
 *
 * <p>The topic of web application security is a cross-cutting concern and every aspect of the
 * specification address it. However, as with any framework, the application developer needs to pay
 * careful attention to security. Please consider these topics among the rest of the security
 * concerns for the application. This is by no means a complete list of security concerns, and is no
 * substitute for a thorough application level security review.
 *
 * <ul>
 *   <p><strong>Prefix mappings and the <code>FacesServlet</code></strong>
 *   <p>If the <code>FacesServlet</code> is mapped using a prefix <code>&lt;url-pattern&gt;</code>,
 *   such as <code>&lt;url-pattern&gt;/faces/*&lt;/url-pattern&gt;</code>, something must be done to
 *   prevent access to the view source without its first being processed by the <code>FacesServlet
 *   </code>. One common approach is to apply a &lt;security-constraint&gt; to all facelet files and
 *   flow definition files. Please see the <strong>Deployment Descriptor</strong> chapter of the
 *   Java Servlet Specification for more information the use of &lt;security-constraint&gt;.
 *   <p><strong>Allowable HTTP Methods</strong>
 *   <p>The JSF specification only requires the use of the GET and POST http methods. If your web
 *   application does not require any other http methods, such as PUT and DELETE, please consider
 *   restricting the allowable http methods using the &lt;http-method&gt; and
 *   &lt;http-method-omission&gt; elements. Please see the <strong>Security</strong> of the Java
 *   Servlet Specification for more information the use of these elements.
 * </ul>
 *
 * </div>
 */
@MultipartConfig
public final class FacesServlet implements Servlet {

  /*
   * A white space separated list of case sensitive HTTP method names
   * that are allowed to be processed by this servlet. * means allow all
   */
  private static final String ALLOWED_HTTP_METHODS_ATTR = "com.sun.faces.allowedHttpMethods";

  // Http method names must be upper case. http://www.w3.org/Protocols/HTTP/NoteMethodCS.html
  // List of valid methods in Http 1.1 http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9

  private enum HttpMethod {
    OPTIONS("OPTIONS"),
    GET("GET"),
    HEAD("HEAD"),
    POST("POST"),
    PUT("PUT"),
    DELETE("DELETE"),
    TRACE("TRACE"),
    CONNECT("CONNECT");

    private String name;

    HttpMethod(String name) {
      this.name = name;
    }

    @Override
    public String toString() {
      return name;
    }
  }

  private Set<String> allowedUnknownHttpMethods;
  private Set<HttpMethod> allowedKnownHttpMethods;
  private final Set<HttpMethod> defaultAllowedHttpMethods =
      EnumSet.range(HttpMethod.OPTIONS, HttpMethod.CONNECT);
  private Set<HttpMethod> allHttpMethods;

  private boolean allowAllMethods;

  /**
   * Context initialization parameter name for a comma delimited list of context-relative resource
   * paths (in addition to <code>/WEB-INF/faces-config.xml</code> which is loaded automatically if
   * it exists) containing JavaServer Faces configuration information.
   */
  public static final String CONFIG_FILES_ATTR = "javax.faces.CONFIG_FILES";

  /**
   * Context initialization parameter name for the lifecycle identifier of the {@link Lifecycle}
   * instance to be utilized.
   */
  public static final String LIFECYCLE_ID_ATTR = "javax.faces.LIFECYCLE_ID";

  /** The <code>Logger</code> for this class. */
  private static final Logger LOGGER =
      Logger.getLogger("javax.faces.webapp", "javax.faces.LogStrings");

  /** Factory for {@link FacesContext} instances. */
  private FacesContextFactory facesContextFactory = null;

  /** The {@link Lifecycle} instance to use for request processing. */
  private Lifecycle lifecycle = null;

  /** The <code>ServletConfig</code> instance for this servlet. */
  private ServletConfig servletConfig = null;

  /**
   * From GLASSFISH-15632. If true, the FacesContext instance left over from startup time has been
   * released.
   */
  private boolean initFacesContextReleased = false;

  /** Release all resources acquired at startup time. */
  public void destroy() {

    facesContextFactory = null;
    lifecycle = null;
    servletConfig = null;
    uninitHttpMethodValidityVerification();
  }

  /** Return the <code>ServletConfig</code> instance for this servlet. */
  public ServletConfig getServletConfig() {

    return (this.servletConfig);
  }

  /** Return information about this Servlet. */
  public String getServletInfo() {

    return (this.getClass().getName());
  }

  /**
   * Acquire the factory instances we will require.
   *
   * @throws ServletException if, for any reason, the startup of this Faces application failed. This
   *     includes errors in the config file that is parsed before or during the processing of this
   *     <code>init()</code> method.
   */
  public void init(ServletConfig servletConfig) throws ServletException {

    // Save our ServletConfig instance
    this.servletConfig = servletConfig;

    // Acquire our FacesContextFactory instance
    try {
      facesContextFactory =
          (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
    } catch (FacesException e) {
      ResourceBundle rb = LOGGER.getResourceBundle();
      String msg = rb.getString("severe.webapp.facesservlet.init_failed");
      Throwable rootCause = (e.getCause() != null) ? e.getCause() : e;
      LOGGER.log(Level.SEVERE, msg, rootCause);
      throw new UnavailableException(msg);
    }

    // Acquire our Lifecycle instance
    try {
      LifecycleFactory lifecycleFactory =
          (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
      String lifecycleId;

      // First look in the servlet init-param set
      if (null == (lifecycleId = servletConfig.getInitParameter(LIFECYCLE_ID_ATTR))) {
        // If not found, look in the context-param set
        lifecycleId = servletConfig.getServletContext().getInitParameter(LIFECYCLE_ID_ATTR);
      }

      if (lifecycleId == null) {
        lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE;
      }
      lifecycle = lifecycleFactory.getLifecycle(lifecycleId);
      initHttpMethodValidityVerification();
    } catch (FacesException e) {
      Throwable rootCause = e.getCause();
      if (rootCause == null) {
        throw e;
      } else {
        throw new ServletException(e.getMessage(), rootCause);
      }
    }
  }

  private void initHttpMethodValidityVerification() {

    assert (null == allowedUnknownHttpMethods);
    assert (null != defaultAllowedHttpMethods);
    assert (null == allHttpMethods);
    allHttpMethods = EnumSet.allOf(HttpMethod.class);

    // Configure our permitted HTTP methods

    allowedUnknownHttpMethods = Collections.emptySet();
    allowedKnownHttpMethods = defaultAllowedHttpMethods;

    String[] methods;
    String allowedHttpMethodsString =
        servletConfig.getServletContext().getInitParameter(ALLOWED_HTTP_METHODS_ATTR);
    if (null != allowedHttpMethodsString) {
      methods = allowedHttpMethodsString.split("\\s+");
      assert (null != methods); // assuming split always returns a non-null array result
      allowedUnknownHttpMethods = new HashSet(methods.length);
      List<String> allowedKnownHttpMethodsStringList = new ArrayList<String>();
      // validate input against allHttpMethods data structure
      for (String cur : methods) {
        if (cur.equals("*")) {
          allowAllMethods = true;
          allowedUnknownHttpMethods = Collections.emptySet();
          return;
        }
        boolean isKnownHttpMethod;
        try {
          HttpMethod.valueOf(cur);
          isKnownHttpMethod = true;
        } catch (IllegalArgumentException e) {
          isKnownHttpMethod = false;
        }

        if (!isKnownHttpMethod) {
          if (LOGGER.isLoggable(Level.WARNING)) {
            HttpMethod[] values = HttpMethod.values();
            Object[] arg = new Object[values.length + 1];
            arg[0] = cur;
            System.arraycopy(values, HttpMethod.OPTIONS.ordinal(), arg, 1, values.length);
            LOGGER.log(Level.WARNING, "warning.webapp.facesservlet.init_invalid_http_method", arg);
          }
          // prevent duplicates
          if (!allowedUnknownHttpMethods.contains(cur)) {
            allowedUnknownHttpMethods.add(cur);
          }
        } else {
          // prevent duplicates
          if (!allowedKnownHttpMethodsStringList.contains(cur)) {
            allowedKnownHttpMethodsStringList.add(cur);
          }
        }
      }
      // Optimally initialize allowedKnownHttpMethods
      if (5 == allowedKnownHttpMethodsStringList.size()) {
        allowedKnownHttpMethods =
            EnumSet.of(
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0)),
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(1)),
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(2)),
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(3)),
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(4)));
      } else if (4 == allowedKnownHttpMethodsStringList.size()) {
        allowedKnownHttpMethods =
            EnumSet.of(
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0)),
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(1)),
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(2)),
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(3)));

      } else if (3 == allowedKnownHttpMethodsStringList.size()) {
        allowedKnownHttpMethods =
            EnumSet.of(
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0)),
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(1)),
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(2)));

      } else if (2 == allowedKnownHttpMethodsStringList.size()) {
        allowedKnownHttpMethods =
            EnumSet.of(
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0)),
                HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(1)));

      } else if (1 == allowedKnownHttpMethodsStringList.size()) {
        allowedKnownHttpMethods =
            EnumSet.of(HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0)));

      } else {
        List<HttpMethod> restList =
            new ArrayList<HttpMethod>(allowedKnownHttpMethodsStringList.size() - 1);
        for (int i = 1; i < allowedKnownHttpMethodsStringList.size() - 1; i++) {
          restList.add(HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(i)));
        }
        HttpMethod first = HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0));
        HttpMethod[] rest = new HttpMethod[restList.size()];
        restList.toArray(rest);
        allowedKnownHttpMethods = EnumSet.of(first, rest);
      }
    }
  }

  private void uninitHttpMethodValidityVerification() {
    assert (null != allowedUnknownHttpMethods);
    assert (null != defaultAllowedHttpMethods);
    assert (null != allHttpMethods);

    allowedUnknownHttpMethods.clear();
    allowedUnknownHttpMethods = null;
    allowedKnownHttpMethods.clear();
    allowedKnownHttpMethods = null;
    allHttpMethods.clear();
    allHttpMethods = null;
  }

  /**
   * <span class="changed_modified_2_2">Process</span> an incoming request, and create the
   * corresponding response according to the following specification. <div
   * class="changed_modified_2_0">
   *
   * <p>If the <code>request</code> and <code>response</code> arguments to this method are not
   * instances of <code>HttpServletRequest</code> and <code>HttpServletResponse</code>,
   * respectively, the results of invoking this method are undefined.
   *
   * <p>This method must respond to requests that start with the following strings by invoking the
   * <code>sendError</code> method on the response argument (cast to <code>HttpServletResponse
   * </code>), passing the code <code>HttpServletResponse.SC_NOT_FOUND</code> as the argument.
   *
   * <ul>
   *   <pre><code>
   * /WEB-INF/
   * /WEB-INF
   * /META-INF/
   * /META-INF
   * </code></pre>
   * </ul>
   *
   * <p>If none of the cases described above in the specification for this method apply to the
   * servicing of this request, the following action must be taken to service the request.
   *
   * <p>Acquire a {@link FacesContext} instance for this request.
   *
   * <p>Acquire the <code>ResourceHandler</code> for this request by calling {@link
   * javax.faces.application.Application#getResourceHandler}. Call {@link
   * javax.faces.application.ResourceHandler#isResourceRequest}. If this returns <code>true</code>
   * call {@link javax.faces.application.ResourceHandler#handleResourceRequest}. If this returns
   * <code>false</code>, <span class="changed_added_2_2">call {@link
   * javax.faces.lifecycle.Lifecycle#attachWindow} followed by </span> {@link
   * javax.faces.lifecycle.Lifecycle#execute} followed by {@link
   * javax.faces.lifecycle.Lifecycle#render}. If a {@link javax.faces.FacesException} is thrown in
   * either case, extract the cause from the <code>FacesException</code>. If the cause is <code>null
   * </code> extract the message from the <code>FacesException</code>, put it inside of a new <code>
   * ServletException</code> instance, and pass the <code>FacesException</code> instance as the root
   * cause, then rethrow the <code>ServletException</code> instance. If the cause is an instance of
   * <code>ServletException</code>, rethrow the cause. If the cause is an instance of <code>
   * IOException</code>, rethrow the cause. Otherwise, create a new <code>ServletException</code>
   * instance, passing the message from the cause, as the first argument, and the cause itself as
   * the second argument.
   *
   * <p class="changed_modified_2_0_rev_a">The implementation must make it so {@link
   * javax.faces.context.FacesContext#release} is called within a finally block as late as possible
   * in the processing for the JSF related portion of this request. </div>
   *
   * @param req The servlet request we are processing
   * @param resp The servlet response we are creating
   * @throws IOException if an input/output error occurs during processing
   * @throws ServletException if a servlet error occurs during processing
   */
  public void service(ServletRequest req, ServletResponse resp)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    requestStart(request.getRequestURI()); // V3 Probe hook

    if (!isHttpMethodValid(request)) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    if (Thread.currentThread().isInterrupted()) {
      if (LOGGER.isLoggable(Level.FINER)) {
        LOGGER.log(
            Level.FINE,
            "Thread {0} given to FacesServlet.service() in interrupted state",
            Thread.currentThread().getName());
      }
    }

    // If prefix mapped, then ensure requests for /WEB-INF are
    // not processed.
    String pathInfo = request.getPathInfo();
    if (pathInfo != null) {
      pathInfo = pathInfo.toUpperCase();
      if (pathInfo.startsWith("/WEB-INF/")
          || pathInfo.equals("/WEB-INF")
          || pathInfo.startsWith("/META-INF/")
          || pathInfo.equals("/META-INF")) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }
    }

    if (!initFacesContextReleased) {
      FacesContext initFacesContext = FacesContext.getCurrentInstance();
      if (null != initFacesContext) {
        initFacesContext.release();
      }
      initFacesContextReleased = true;
    }

    // Acquire the FacesContext instance for this request
    FacesContext context =
        facesContextFactory.getFacesContext(
            servletConfig.getServletContext(), request, response, lifecycle);

    // Execute the request processing lifecycle for this request
    try {
      ResourceHandler handler = context.getApplication().getResourceHandler();
      if (handler.isResourceRequest(context)) {
        handler.handleResourceRequest(context);
      } else {
        lifecycle.attachWindow(context);
        lifecycle.execute(context);
        lifecycle.render(context);
      }
    } catch (FacesException e) {
      Throwable t = e.getCause();
      if (t == null) {
        throw new ServletException(e.getMessage(), e);
      } else {
        if (t instanceof ServletException) {
          throw ((ServletException) t);
        } else if (t instanceof IOException) {
          throw ((IOException) t);
        } else {
          throw new ServletException(t.getMessage(), t);
        }
      }
    } finally {
      // Release the FacesContext instance for this request
      context.release();
    }

    requestEnd(); // V3 Probe hook
  }

  private boolean isHttpMethodValid(HttpServletRequest request) {
    boolean result = false;
    if (allowAllMethods) {
      result = true;
    } else {
      String requestMethodString = request.getMethod();
      HttpMethod requestMethod = null;
      boolean isKnownHttpMethod;
      try {
        requestMethod = HttpMethod.valueOf(requestMethodString);
        isKnownHttpMethod = true;
      } catch (IllegalArgumentException e) {
        isKnownHttpMethod = false;
      }
      if (isKnownHttpMethod) {
        result = allowedKnownHttpMethods.contains(requestMethod);
      } else {
        result = allowedUnknownHttpMethods.contains(requestMethodString);
      }
    }

    return result;
  }

  // --------------------------------------------------------- Private Methods

  /** DO NOT REMOVE. Necessary for V3 probe monitoring. */
  @SuppressWarnings({"UnusedDeclaration"})
  private void requestStart(String requestUri) {}

  /** DO NOT REMOVE. Necessary for V3 probe monitoring. */
  private void requestEnd() {}
}
  public static enum IOComponentTypes {
    LED,
    Button,
    Pin,
    SevenSegment,
    DIPSwitch,
    RGBLED,
    PortIO,
    LocalBus,
    Bus,
    Unknown;

    public static IOComponentTypes getEnumFromString(String str) {
      for (IOComponentTypes elem : KnownComponentSet) {
        if (elem.name().equalsIgnoreCase(str)) {
          return elem;
        }
      }
      return IOComponentTypes.Unknown;
    }

    public static final int GetFPGAInOutRequirement(IOComponentTypes comp) {
      switch (comp) {
        case PortIO:
          return nbSwitch;
        case LocalBus:
          return 16;
        default:
          return 0;
      }
    }

    public static final int GetFPGAInputRequirement(IOComponentTypes comp) {
      switch (comp) {
        case Button:
          return 1;
        case DIPSwitch:
          return nbSwitch;
        case LocalBus:
          return 12;
        default:
          return 0;
      }
    }

    public static final int GetFPGAOutputRequirement(IOComponentTypes comp) {
      switch (comp) {
        case LED:
          return 1;
        case SevenSegment:
          return 8;
        case RGBLED:
          return 3;
        case LocalBus:
          return 2;
        default:
          return 0;
      }
    }

    public static final int GetNrOfFPGAPins(IOComponentTypes comp) {
      switch (comp) {
        case LED:
        case Button:
        case Pin:
          return 1;
        case DIPSwitch:
        case PortIO:
          return nbSwitch;
        case SevenSegment:
          return 8;
        case RGBLED:
          return 3;
        case LocalBus:
          return 30;
        default:
          return 0;
      }
    }

    public static final EnumSet<IOComponentTypes> KnownComponentSet =
        EnumSet.range(IOComponentTypes.LED, IOComponentTypes.LocalBus);

    public static final EnumSet<IOComponentTypes> SimpleInputSet =
        EnumSet.range(IOComponentTypes.LED, IOComponentTypes.LocalBus);

    public static final EnumSet<IOComponentTypes> InputComponentSet =
        EnumSet.of(IOComponentTypes.Button, IOComponentTypes.Pin, IOComponentTypes.DIPSwitch);

    public static final EnumSet<IOComponentTypes> OutputComponentSet =
        EnumSet.of(
            IOComponentTypes.LED,
            IOComponentTypes.Pin,
            IOComponentTypes.RGBLED,
            IOComponentTypes.SevenSegment);

    public static final EnumSet<IOComponentTypes> InOutComponentSet =
        EnumSet.of(IOComponentTypes.Pin, IOComponentTypes.PortIO);

    private static int nbSwitch = 8;

    private void setNbSwitch(int nb) {
      nbSwitch = nb;
    }
  }
Ejemplo n.º 22
0
/**
 * A simple paint program that is a first demonstration of using an off-screen canvas. This class
 * can be run as a main program and has a nested class PaintWithOffScreenCanvas.Applet that can be
 * used as an applet. Note that the way that the off-screen canvas is used in this class requires
 * that the panel be non-resizable; this is because the size of the off-screen canvas does not
 * change when the panel changes size.
 */
public class AdvancedGUIEX1 extends JPanel {

  /** The main routine simply opens a window that shows a PaintWithOffScreenCanvas panel. */
  public static void main(String[] args) {
    JFrame window = new JFrame("PaintWithOffScreenCanvas");
    AdvancedGUIEX1 content = new AdvancedGUIEX1();
    window.setContentPane(content);
    window.setJMenuBar(content.getMenuBar());
    window.pack();
    window.setResizable(false);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    window.setLocation(
        (screenSize.width - window.getWidth()) / 2, (screenSize.height - window.getHeight()) / 2);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
  }

  /**
   * The public static class PaintWithOffScreenCanvas$Applet represents this program as an applet.
   * The applet's init() method simply sets the content pane of the applet to be a
   * PaintWithOffScreenCanvas. To use the applet on a web page, use
   * code="PaintWithOffScreenCanvas$Applet.class" as the name of the class. (This is a rather tricky
   * way of defining an applet class to run a program as an applet, instead of using a separate file
   * to define the applet. It is not necessarily good style.)
   */
  public static class Applet extends JApplet {
    @Override
    public void init() {
      AdvancedGUIEX1 content = new AdvancedGUIEX1();
      content.setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
      setContentPane(content);
      setJMenuBar(content.getMenuBar());
    }
  }

  /**
   * The possible drawing tools in this program. (The CURVE tool allows the user to sketch a
   * free-hand curve, while the LINE tool draws a line between two points. The SMUDGE tool lets the
   * user "spread paint around" with the mouse. The ERASE tool erases with a 10-by-10 pixel
   * rectangle.)
   */
  private enum Tool {
    CURVE,
    LINE,
    RECT,
    OVAL,
    FILLED_RECT,
    FILLED_OVAL,
    SMUDGE,
    ERASE
  }

  /**
   * The set of Tools that represent "shapes." Shapes are handled differently during dragging than
   * other tools, since they are drawn "on top of" the current picture during a mouse drag and are
   * only added permanently to the picture on mouse release.
   */
  private static final EnumSet<Tool> SHAPE_TOOLS = EnumSet.range(Tool.LINE, Tool.FILLED_OVAL);

  /**
   * The currently selected drawing tool. Initially Tool.CURVE. Can be changed by the user with
   * commands in the "Tool" menu.
   */
  private Tool currentTool = Tool.CURVE;

  /**
   * The current drawing color. Initially Color.BLACK. Can be changed by the user with the "Select
   * Drawing Color" command in the "Color" menu.
   */
  private Color currentColor = Color.BLACK;

  /**
   * The background color that is used to fill the off-screen canvas when it is created. If the user
   * selects the "Fill With Color", the fill color changes, and the canvas is filled with the new
   * fill color, erasing whatever was there before.
   */
  private Color fillColor = Color.WHITE;

  /**
   * The off-screen canvas. This is not created until the first time paintComponent() is called. The
   * size of the canvas will not change after it is crearted, so this program has no support for
   * resizing the window.
   */
  private BufferedImage OSC;

  /** This is set to true when the user is dragging the mouse. */
  private boolean dragging;

  /** The start position of the mouse during a mouse drag. */
  private int startX, startY;

  /** The current position of the mouse during a mouse drag. */
  private int currentX, currentY;

  /**
   * The constructor sets the preferred size of the panel to 640-by-480. It also sets up mouse
   * listeners.
   */
  public AdvancedGUIEX1() {
    setPreferredSize(new Dimension(640, 480));
    MouseHandler mouseHandler = new MouseHandler();
    addMouseListener(mouseHandler);
    addMouseMotionListener(mouseHandler);
  }

  /**
   * The paintComponent() method copies the off-screen canvas to the screen (first creating it, if
   * necessary). If a mouse drag is is progress, then the current tool is not Tool.CURVE, then the
   * shape that the user is drawing is drawn over the off-screen canvas. (This is to avoid making
   * the shape a permanent part of the picture until after the user releases the mouse. The effect
   * is a "rubber band cursor" in which the shape changes as the user drags the mouse, but the
   * picture under the shape is not affected.)
   */
  @Override
  public void paintComponent(Graphics g) {

    /* First create the off-screen canvas, if it does not already exist. */

    if (OSC == null) {
      createOSC();
    }

    /* Copy the off-screen canvas to the panel.  Since we know that the
    image is already completely available, the fourth "ImageObserver"
    parameter to g.drawImage() can be null.  Since the canvas completely
    fills the panel, there is no need to call super.paintComponent(g). */

    g.drawImage(OSC, 0, 0, null);

    /* If the user is currently dragging the mouse to draw a line, oval,
    or rectangle, draw the shape on top the image from the off-screen
    canvas, using the current drawing color.  (This is not done if the
    user is drawing a curve or using the smudge tool.) */

    if (dragging && SHAPE_TOOLS.contains(currentTool)) {
      g.setColor(currentColor);
      putCurrentShape(g);
    }
  }

  /** This method creates the off-screen canvas and fills it with the current fill color. */
  private void createOSC() {
    OSC = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics osg = OSC.getGraphics();
    Color fillColor = new Color(0, 0, 0);
    fillColor = Color.WHITE;
    osg.setColor(fillColor);
    osg.fillRect(0, 0, getWidth(), getHeight());
    osg.dispose();
  }

  /**
   * A utility method to draw the current shape in a given graphics context. It draws the correct
   * shape for the current tool in a rectangle whose corners are given by the starting position of
   * the mouse and the current position of the mouse. This is used by paintComponent() during a
   * mouse drag. It is also used to make the shape a permanent part of the off-screen canvas when
   * the mouse is released. This method is not used when the current tool is Tool.CURVE or
   * Tool.SMUDGE.
   */
  private void putCurrentShape(Graphics g) {
    switch (currentTool) {
      case LINE:
        g.drawLine(startX, startY, currentX, currentY);
        break;
      case OVAL:
        putOval(g, false, startX, startY, currentX, currentY);
        break;
      case RECT:
        putRect(g, false, startX, startY, currentX, currentY);
        break;
      case FILLED_OVAL:
        putOval(g, true, startX, startY, currentX, currentY);
        break;
      case FILLED_RECT:
        putRect(g, true, startX, startY, currentX, currentY);
        break;
    }
  }

  /**
   * Draws a filled or unfilled rectangle with corners at the points (x1,y1) and (x2,y2). Nothing is
   * drawn if x1 == x2 or y1 == y2.
   *
   * @param g the graphics context where the rectangle is drawn
   * @param filled tells whether to draw a filled or unfilled rectangle.
   */
  private void putRect(Graphics g, boolean filled, int x1, int y1, int x2, int y2) {
    if (x1 == x2 || y1 == y2) {
      return;
    }
    if (x2 < x1) { // Swap x1,x2 if necessary to make x2 > x1.
      int temp = x1;
      x1 = x2;
      x2 = temp;
    }
    if (y2 < y1) { // Swap y1,y2 if necessary to make y2 > y1.
      int temp = y1;
      y1 = y2;
      y2 = temp;
    }
    if (filled) {
      g.fillRect(x1, y1, x2 - x1, y2 - y1);
    } else {
      g.drawRect(x1, y1, x2 - x1, y2 - y1);
    }
  }

  /**
   * Draws a filled or unfilled oval in the rectangle with corners at the points (x1,y1) and
   * (x2,y2). Nothing is drawn if x1 == x2 or y1 == y2.
   *
   * @param g the graphics context where the oval is drawn
   * @param filled tells whether to draw a filled or unfilled oval.
   */
  private void putOval(Graphics g, boolean filled, int x1, int y1, int x2, int y2) {
    if (x1 == x2 || y1 == y2) {
      return;
    }
    if (x2 < x1) { // Swap x1,x2 if necessary to make x2 > x1.
      int temp = x1;
      x1 = x2;
      x2 = temp;
    }
    if (y2 < y1) { // Swap y1,y2 if necessary to make y2 > y1.
      int temp = y1;
      y1 = y2;
      y2 = temp;
    }
    if (filled) {
      g.fillOval(x1, y1, x2 - x1, y2 - y1);
    } else {
      g.drawOval(x1, y1, x2 - x1, y2 - y1);
    }
  }

  /**
   * Calls the repaint() method of this panel for the rectangle with corners at the points (x1,y1)
   * and (x2,y2). An extra one-pixel border is added to the area that is repainted; this allows for
   * the size of the "pen" that is used to draw lines and unfilled ovals and rectangles.
   */
  private void repaintRect(int x1, int y1, int x2, int y2) {
    if (x2 < x1) { // Swap x1,x2 if necessary to make x2 >= x1.
      int temp = x1;
      x1 = x2;
      x2 = temp;
    }
    if (y2 < y1) { // Swap y1,y2 if necessary to make y2 >= y1.
      int temp = y1;
      y1 = y2;
      y2 = temp;
    }
    x1--;
    x2++;
    y1--;
    y2++;
    repaint(x1, y1, x2 - x1, y2 - y1);
  }

  /** Creates a menu bar for use with this panel, with "Color" and "Tool" menus. */
  public JMenuBar getMenuBar() {
    JMenuBar menubar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    JMenu colorMenu = new JMenu("Color");
    JMenu toolMenu = new JMenu("Tool");
    menubar.add(fileMenu);
    menubar.add(colorMenu);
    menubar.add(toolMenu);
    ActionListener listener = new MenuHandler();
    JMenuItem item;
    item = new JMenuItem("New File");
    item.addActionListener(listener);
    item.setAccelerator(KeyStroke.getKeyStroke("ctrl N"));
    fileMenu.add(item);
    item = new JMenuItem("Open");
    item.addActionListener(listener);
    item.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
    fileMenu.add(item);
    item = new JMenuItem("Save");
    item.addActionListener(listener);
    item.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
    fileMenu.add(item);
    fileMenu.addSeparator();

    item = new JMenuItem("Exit");
    item.addActionListener(listener);
    fileMenu.add(item);

    item = new JMenuItem("Draw With Black");
    item.addActionListener(listener);
    colorMenu.add(item);
    item = new JMenuItem("Draw With White");
    item.addActionListener(listener);
    colorMenu.add(item);
    item = new JMenuItem("Draw With Red");
    item.addActionListener(listener);
    colorMenu.add(item);
    item = new JMenuItem("Draw With Green");
    item.addActionListener(listener);
    colorMenu.add(item);
    item = new JMenuItem("Draw With Blue");
    item.addActionListener(listener);
    colorMenu.add(item);
    item = new JMenuItem("Draw With Yellow");
    item.addActionListener(listener);
    colorMenu.add(item);
    item = new JMenuItem("Select Drawing Color...");
    item.addActionListener(listener);
    colorMenu.add(item);
    colorMenu.addSeparator();
    item = new JMenuItem("Fill With Color...");
    item.addActionListener(listener);
    colorMenu.add(item);
    item = new JMenuItem("Curve");
    item.addActionListener(listener);
    toolMenu.add(item);
    toolMenu.addSeparator();
    item = new JMenuItem("Line");
    item.addActionListener(listener);
    toolMenu.add(item);
    item = new JMenuItem("Rectangle");
    item.addActionListener(listener);
    toolMenu.add(item);
    item = new JMenuItem("Oval");
    item.addActionListener(listener);
    toolMenu.add(item);
    item = new JMenuItem("Filled Rectangle");
    item.addActionListener(listener);
    toolMenu.add(item);
    item = new JMenuItem("Filled Oval");
    item.addActionListener(listener);
    toolMenu.add(item);
    toolMenu.addSeparator();
    item = new JMenuItem("Smudge");
    item.addActionListener(listener);
    toolMenu.add(item);
    item = new JMenuItem("Erase");
    item.addActionListener(listener);
    toolMenu.add(item);
    return menubar;
  }

  /**
   * This nested class defines the ActionListener that responds when the user selects a command from
   * one of the menus. It is used in the getMenuBar() method.
   */
  private class MenuHandler implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent evt) {
      String command = evt.getActionCommand();
      switch (command) {
        case "New File":
          {
            OSC = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics osg = OSC.getGraphics();
            osg.setColor(fillColor);
            osg.fillRect(0, 0, getWidth(), getHeight());
            osg.dispose();
            repaint();
            break;
          }
        case "Open":
          {
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter =
                new FileNameExtensionFilter("JPG or PNG Images", "jpg", "png");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(null);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
              try {

                OSC = ImageIO.read(chooser.getSelectedFile());
                Graphics2D g2 = (Graphics2D) OSC.getGraphics();

                g2.scale((double) 640 / OSC.getWidth(), (double) 480 / OSC.getHeight());
                g2.drawImage(OSC, 0, 0, OSC.getWidth(), OSC.getHeight(), null);
              } catch (Exception e) {
              }
            }
            repaint();
            break;
          }
        case "Save":
          {
            JFileChooser fileDialog = new JFileChooser();
            fileDialog.setSelectedFile(new File("image.PNG"));
            fileDialog.setDialogTitle("Select File to be Saved");
            int option = fileDialog.showSaveDialog(null);
            if (option != JFileChooser.APPROVE_OPTION)
              return; // User canceled or clicked the dialog’s close box.

            File selectedFile = fileDialog.getSelectedFile();
            if (selectedFile.exists()) { // Ask the user whether to replace the file.
              int response =
                  JOptionPane.showConfirmDialog(
                      null,
                      "The file \""
                          + selectedFile.getName()
                          + "\" already exists.\nDo you want to replace it?",
                      "Confirm Save",
                      JOptionPane.YES_NO_OPTION,
                      JOptionPane.WARNING_MESSAGE);
              if (response != JOptionPane.YES_OPTION)
                return; // User does not want to replace the file.
            }
            try {
              boolean hasFormat = ImageIO.write(OSC, "PNG", selectedFile);
              if (!hasFormat) throw new Exception("PNG" + " format is not available.");
            } catch (Exception e) {
              JOptionPane.showMessageDialog(
                  null, "Sorry, an error occurred while trying to save image.");
              e.printStackTrace();
            }

            break;
          }
        case "Exit":
          {
            System.exit(0);
          }

        case "Select Drawing Color...":
          {
            Color newColor =
                JColorChooser.showDialog(AdvancedGUIEX1.this, "Select Drawing Color", currentColor);
            if (newColor != null) currentColor = newColor;
            break;
          }
        case "Fill With Color...":
          {
            Color newColor =
                JColorChooser.showDialog(AdvancedGUIEX1.this, "Select Fill Color", fillColor);
            if (newColor != null) {
              fillColor = newColor;
              Graphics osg = OSC.getGraphics();
              osg.setColor(fillColor);
              osg.fillRect(0, 0, OSC.getWidth(), OSC.getHeight());
              osg.dispose();
              AdvancedGUIEX1.this.repaint();
            }
            break;
          }
        case "Draw With Black":
          currentColor = Color.BLACK;
          break;
        case "Draw With White":
          currentColor = Color.WHITE;
          break;
        case "Draw With Red":
          currentColor = Color.RED;
          break;
        case "Draw With Green":
          currentColor = Color.GREEN;
          break;
        case "Draw With Blue":
          currentColor = Color.BLUE;
          break;
        case "Draw With Yellow":
          currentColor = Color.YELLOW;
          break;
        case "Curve":
          currentTool = Tool.CURVE;
          break;
        case "Line":
          currentTool = Tool.LINE;
          break;
        case "Rectangle":
          currentTool = Tool.RECT;
          break;
        case "Oval":
          currentTool = Tool.OVAL;
          break;
        case "Filled Rectangle":
          currentTool = Tool.FILLED_RECT;
          break;
        case "Filled Oval":
          currentTool = Tool.FILLED_OVAL;
          break;
        case "Smudge":
          currentTool = Tool.SMUDGE;
          break;
        case "Erase":
          currentTool = Tool.ERASE;
          break;
      }
    }
  } // end nested class MenuHandler

  /**
   * This nested class defines the object that listens for mouse and mouse motion events on the
   * panel. It is used in the constructor.
   */
  private class MouseHandler implements MouseListener, MouseMotionListener {

    int prevX, prevY; // Previous position of mouse during a drag.
    double[][] smudgeRed, smudgeGreen, smudgeBlue; // data for smudge tool

    /**
     * When the ERASE or SMUDGE tools are used and the mouse jumps from (x1,y1) to (x2,y2), the tool
     * has to be applied to a line of pixel positions between the two points in order to cover the
     * entire line that the mouse moves along. The change is made to the off-screen canvas, and
     * repaint() is called to copy the changes to the screen.
     */
    void applyToolAlongLine(int x1, int y1, int x2, int y2) {
      Graphics g = OSC.getGraphics();
      g.setColor(fillColor); // (for ERASE only)
      int w = OSC.getWidth(); // (for SMUDGE only)
      int h = OSC.getHeight(); // (for SMUDGE only)
      int dist = Math.max(Math.abs(x2 - x1), Math.abs(y2 - y1));
      // dist is the number of points along the line from
      // (x1,y1) to (x2,y2) at which the tool will be applied.
      double dx = (double) (x2 - x1) / dist;
      double dy = (double) (y2 - y1) / dist;
      for (int d = 1; d <= dist; d++) {
        // Apply the tool at one of the points (x,y) along the
        // line from (x1,y1) to (x2,y2).
        int x = (int) Math.round(x1 + dx * d);
        int y = (int) Math.round(y1 + dy * d);
        if (currentTool == Tool.ERASE) {
          // Erase a 10-by-10 block of pixels around (x,y)
          g.fillRect(x - 5, y - 5, 10, 10);
          repaint(x - 5, y - 5, 10, 10);
        } else {
          // For the SMUDGE tool, blend some of the color from
          // the smudgeRed, smudgeGreen, and smudgeBlue arrays
          // into the pixels in a 7-by-7 block around (x,y), and
          // vice versa.  The effect is to smear out the color
          // of pixels that are visited by the tool.
          for (int i = 0; i < 7; i++) {
            for (int j = 0; j < 7; j++) {
              int r = y + j - 3;
              int c = x + i - 3;
              if (!(r < 0 || r >= h || c < 0 || c >= w || smudgeRed[i][j] == -1)) {
                int curCol = OSC.getRGB(c, r);
                int curRed = (curCol >> 16) & 0xFF;
                int curGreen = (curCol >> 8) & 0xFF;
                int curBlue = curCol & 0xFF;
                int newRed = (int) (curRed * 0.7 + smudgeRed[i][j] * 0.3);
                int newGreen = (int) (curGreen * 0.7 + smudgeGreen[i][j] * 0.3);
                int newBlue = (int) (curBlue * 0.7 + smudgeBlue[i][j] * 0.3);
                int newCol = newRed << 16 | newGreen << 8 | newBlue;
                OSC.setRGB(c, r, newCol);
                smudgeRed[i][j] = curRed * 0.3 + smudgeRed[i][j] * 0.7;
                smudgeGreen[i][j] = curGreen * 0.3 + smudgeGreen[i][j] * 0.7;
                smudgeBlue[i][j] = curBlue * 0.3 + smudgeBlue[i][j] * 0.7;
              }
            }
          }
          repaint(x - 3, y - 3, 7, 7);
        }
      }
      g.dispose();
    }

    /** Start a drag operation. */
    @Override
    public void mousePressed(MouseEvent evt) {
      startX = prevX = currentX = evt.getX();
      startY = prevY = currentY = evt.getY();
      dragging = true;
      if (currentTool == Tool.ERASE) {
        // Erase a 10-by-10 block around the starting mouse position.
        Graphics g = OSC.getGraphics();
        g.setColor(fillColor);
        g.fillRect(startX - 5, startY - 5, 10, 10);
        g.dispose();
        repaint(startX - 5, startY - 5, 10, 10);
      } else if (currentTool == Tool.SMUDGE) {
        // Record the colors in a 7-by-7 block of pixels around the
        // starting mouse position into the arrays smudgeRed,
        // smudgeGreen, and smudgeBlue.  These arrays hold the
        // red, green, and blue components of the colors.
        if (smudgeRed == null) {
          // Create the arrays, if they have not already been created.
          smudgeRed = new double[7][7];
          smudgeGreen = new double[7][7];
          smudgeBlue = new double[7][7];
        }
        int w = OSC.getWidth();
        int h = OSC.getHeight();
        int x = evt.getX();
        int y = evt.getY();
        for (int i = 0; i < 7; i++) {
          for (int j = 0; j < 7; j++) {
            int r = y + j - 3;
            int c = x + i - 3;
            if (r < 0 || r >= h || c < 0 || c >= w) {
              // A -1 in the smudgeRed array indicates that the
              // corresponding pixel was outside the canvas.
              smudgeRed[i][j] = -1;
            } else {
              int color = OSC.getRGB(c, r);
              smudgeRed[i][j] = (color >> 16) & 0xFF;
              smudgeGreen[i][j] = (color >> 8) & 0xFF;
              smudgeBlue[i][j] = color & 0xFF;
            }
          }
        }
      }
    }

    /**
     * Continue a drag operation when the user drags the mouse. For the CURVE tool, a line is drawn
     * from the previous mouse position to the current mouse position in the off-screen canvas, and
     * the repaint() method is called for a rectangle that contains the line segment that was drawn.
     * For shape tools, the off-screen canvas is not changed, but the repaint() method is called so
     * that the paintComponent() method can redraw the picture with the user's shape in the new
     * position. For the SMUDGE and ERASE tools, the tool is applied along a line from the previous
     * mouse position to the current position;
     */
    @Override
    public void mouseDragged(MouseEvent evt) {
      currentX = evt.getX();
      currentY = evt.getY();
      if (currentTool == Tool.CURVE) {
        Graphics g = OSC.getGraphics();
        g.setColor(currentColor);
        g.drawLine(prevX, prevY, currentX, currentY);
        g.dispose();
        repaintRect(prevX, prevY, currentX, currentY);
      } else if (SHAPE_TOOLS.contains(currentTool)) {
        // Repaint the rectangles occupied by the previous position of
        // the shape and by its current position.
        repaintRect(startX, startY, prevX, prevY);
        repaintRect(startX, startY, currentX, currentY);
      } else {
        // Tool has to be ERASE or SMUDGE
        applyToolAlongLine(prevX, prevY, currentX, currentY);
      }
      prevX = currentX;
      prevY = currentY;
    }

    /**
     * Finish a mouse drag operation. Nothing is done unless the current tool is a shape tool. For
     * shape tools, the user's shape is drawn to the off-screen canvas, making it a permanent part
     * of the picture, and then the repaint() method is called to show the modified picture on the
     * screen.
     */
    @Override
    public void mouseReleased(MouseEvent evt) {
      dragging = false;
      if (SHAPE_TOOLS.contains(currentTool)) {
        Graphics g = OSC.getGraphics();
        g.setColor(currentColor);
        putCurrentShape(g);
        g.dispose();
        repaint();
      }
    }

    @Override
    public void mouseMoved(MouseEvent evt) {}

    @Override
    public void mouseClicked(MouseEvent evt) {}

    @Override
    public void mouseEntered(MouseEvent evt) {}

    @Override
    public void mouseExited(MouseEvent evt) {}
  } // end nested class MenuHandler
} // end class PaintWithOffScreenCanvas
Ejemplo n.º 23
0
 static {
   for (ResourceType e : EnumSet.range(ResourceType.MATERIAL, ResourceType.WORK)) {
     TYPE_VALUES[e.getValue()] = e;
   }
 }
Ejemplo n.º 24
0
  /**
   * Constructs WFS MineralOccurence filter query string based on user parameters.
   *
   * @return Filter query string for sending as a POST request
   */
  private String makeFilter() {
    // @formatter:off
    // Case 1. Get All Query
    if ((this.measureType == MeasureTypes.NONE) && commodityName.isEmpty()) {
      return "";
    }

    // Case 2. Commodities Only Query
    else if ((this.measureType == MeasureTypes.NONE) && (!commodityName.isEmpty())) {
      return this.generatePropertyIsEqualToFragment(
          "gsml:specification/er:MineralOccurrence/er:commodityDescription/er:Commodity/er:commodityName",
          commodityName);
    }

    // Case 3. Amount Only Query
    else if ((this.measureType != MeasureTypes.NONE) && commodityName.isEmpty()) {

      // Single measure
      if (this.measureType != MeasureTypes.ANY) {
        if (paramsCount == 0) {
          return this.generatePropertyIsLikeFragment(
              "gsml:specification/er:MineralOccurrence/er:oreAmount/"
                  + getMeasureTypeTag(this.measureType)
                  + "/er:measureDetails/er:CommodityMeasure/er:commodityOfInterest/er:Commodity/er:commodityName",
              "*");
        } else if (paramsCount > 0) {
          return this.generateParametersFragment(getMeasureTypeTag(this.measureType));
        } else {
          return "";
        }
      }
      // Multiple measures - ANY
      else if (this.measureType == MeasureTypes.ANY) {
        List<String> fragments = new ArrayList<String>();

        if (paramsCount == 0) {
          for (MeasureTypes measure : EnumSet.range(MeasureTypes.RESERVE, MeasureTypes.RESOURCE)) {
            fragments.add(
                this.generatePropertyIsLikeFragment(
                    "gsml:specification/er:MineralOccurrence/er:oreAmount/"
                        + getMeasureTypeTag(measure)
                        + "/er:measureDetails/er:CommodityMeasure/er:commodityOfInterest/er:Commodity/er:commodityName",
                    "*"));
          }
        } else if (paramsCount > 0) {
          for (MeasureTypes measure : EnumSet.range(MeasureTypes.RESERVE, MeasureTypes.RESOURCE)) {
            fragments.add(this.generateParametersFragment(getMeasureTypeTag(measure)));
          }
        }

        return this.generateOrComparisonFragment(fragments.toArray(new String[fragments.size()]));
      }
    }

    // Case 4. Commodity + Amount Query
    else if ((this.measureType != MeasureTypes.NONE) && !commodityName.isEmpty()) {

      // Single Measure
      if (this.measureType != MeasureTypes.ANY) {
        if (this.paramsCount == 0) {
          return this.generatePropertyIsEqualToFragment(
              "gsml:specification/er:MineralOccurrence/er:oreAmount/"
                  + getMeasureTypeTag(this.measureType)
                  + "/er:measureDetails/er:CommodityMeasure/er:commodityOfInterest/er:Commodity/er:commodityName",
              commodityName);
        } else {
          return this.generateCommodityAndParametersFragment(
              commodityName, getMeasureTypeTag(this.measureType));
        }
      }
      // Multiple Measures - ANY
      else if (this.measureType == MeasureTypes.ANY) {
        List<String> fragments = new ArrayList<String>();
        if (this.paramsCount == 0) {
          for (MeasureTypes measure : EnumSet.range(MeasureTypes.RESERVE, MeasureTypes.RESOURCE)) {
            fragments.add(
                this.generatePropertyIsEqualToFragment(
                    "gsml:specification/er:MineralOccurrence/er:oreAmount/"
                        + getMeasureTypeTag(measure)
                        + "/er:measureDetails/er:CommodityMeasure/er:commodityOfInterest/er:Commodity/er:commodityName",
                    commodityName));
          }
        } else if (this.paramsCount > 0) {
          for (MeasureTypes measure : EnumSet.range(MeasureTypes.RESERVE, MeasureTypes.RESOURCE)) {
            fragments.add(
                this.generateCommodityAndParametersFragment(
                    commodityName, getMeasureTypeTag(measure)));
          }
        }

        return this.generateOrComparisonFragment(fragments.toArray(new String[fragments.size()]));
      }
    }

    // @formatter:on
    return "";
  }
 static {
   SOURCE_VERSIONS =
       Collections.unmodifiableSet(
           EnumSet.range(SourceVersion.RELEASE_0, SourceVersion.RELEASE_6));
 }