⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 printablestringeditor.java

📁 一个完整的XACML工程,学习XACML技术的好例子!
💻 JAVA
字号:
/*
* Copyright (c) 2006, University of Kent
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this 
* list of conditions and the following disclaimer.
* 
* Redistributions in binary form must reproduce the above copyright notice, 
* this list of conditions and the following disclaimer in the documentation 
* and/or other materials provided with the distribution. 
*
* 1. Neither the name of the University of Kent nor the names of its 
* contributors may be used to endorse or promote products derived from this 
* software without specific prior written permission. 
*
* 2. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS  
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
* PURPOSE ARE DISCLAIMED. 
*
* 3. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* 4. YOU AGREE THAT THE EXCLUSIONS IN PARAGRAPHS 2 AND 3 ABOVE ARE REASONABLE
* IN THE CIRCUMSTANCES.  IN PARTICULAR, YOU ACKNOWLEDGE (1) THAT THIS
* SOFTWARE HAS BEEN MADE AVAILABLE TO YOU FREE OF CHARGE, (2) THAT THIS
* SOFTWARE IS NOT "PRODUCT" QUALITY, BUT HAS BEEN PRODUCED BY A RESEARCH
* GROUP WHO DESIRE TO MAKE THIS SOFTWARE FREELY AVAILABLE TO PEOPLE WHO WISH
* TO USE IT, AND (3) THAT BECAUSE THIS SOFTWARE IS NOT OF "PRODUCT" QUALITY
* IT IS INEVITABLE THAT THERE WILL BE BUGS AND ERRORS, AND POSSIBLY MORE
* SERIOUS FAULTS, IN THIS SOFTWARE.
*
* 5. This license is governed, except to the extent that local laws
* necessarily apply, by the laws of England and Wales.
*/

/*
* Copyright (c) 2000-2005, University of Salford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this 
* list of conditions and the following disclaimer.
* 
* Redistributions in binary form must reproduce the above copyright notice, 
* this list of conditions and the following disclaimer in the documentation 
* and/or other materials provided with the distribution. 
*
* Neither the name of the University of Salford nor the names of its 
* contributors may be used to endorse or promote products derived from this 
* software without specific prior written permission. 
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
* POSSIBILITY OF SUCH DAMAGE.
*/

package issrg.acm.extensions;

import issrg.ac.*;
import iaik.asn1.ASN1Type;
import java.util.Map;

import issrg.ac.attributes.PermisRole;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.io.*;
import java.awt.*;

/**
 * The editor for an attribute with PrintableString values. It is just an input box and a list of
 * strings already input in the set of attribute values.
 *
 * <p>It can be fed a configuration file with OIDs and names of the roles, or
 * it can use the sequence of such values in the acm.cfg
 *
 * <p>The <code>PRINTABLE_STRING_EDITOR_CFG_FILE</code> variable contains the name
 * of the configuration variable, specifying the file with OIDs. The
 * <code>PRINTABLE_STRING_EDITOR_CFG_LINE</code> variable contains the name of the
 * configuration variable to keep the sequence of the role OIDs and their names.
 *
 * <p>The configuration line in the acm.cfg must be of the following format:
 * <code>&lt;OID in dotted form&gt; &lt;attribute name; cannot not contain ';' char&gt;';'</code><p>
 * repeated as many times, as needed.
 *
 * <p>The configuration file for PrintableStringEditor can contain as many lines of
 * the format said above, as needed; the trailing semicolon can be omitted.
 * Empty lines and comments (lines starting with ';' or '#') are ignored.
 *
 * @author A Otenko
 * @version 1.0
 */
public class PrintableStringEditor implements issrg.acm.Utility {	// this one is a bit tricky
  /**
   * This variable specifies the configuration file variable. Its name is
   * <code>"PrintableStringEditor.Config"</code>.
   */
  public final static String PRINTABLE_STRING_EDITOR_CFG_FILE = "PrintableStringEditor.Config";

  /**
   * This variable specifies OID-name pairs directly in the configuration file.
   * Its name is <code>"PrintableStringEditor.OIDs"</code>.
   */
  public final static String PRINTABLE_STRING_EDITOR_CFG_LINE = "PrintableStringEditor.OIDs";
  public final static String COMMENT1 = ";";
  public final static String COMMENT2 = "#";
  public final static String OID_SEPARATOR = "|";
  private boolean use_GUI=false;

  public PrintableStringEditor() {
  }

  /**
   * Reads in PRINTABLE_STRING_EDITOR_CFG_FILE and PRINTABLE_STRING_EDITOR_CFG_LINE
   * and constructs a sequence of PermisRoleEditorHelpers. PRINTABLE_STRING_EDITOR_CFG_LINE
   * definitions take precedence, if OID to attribute type mappings overlap.
   */
  public void registerMe(issrg.acm.Registry where){
    Map env = where.getCollection(issrg.acm.EnvironmentalVariables.VARIABLES_COLLECTION);
    String roleTypesFilename=null;	// these variables are called so just because this class was PermisRoleEditor formerly
    String roleOIDs=null;

    if (env!=null){
      roleTypesFilename=(String)env.get(PRINTABLE_STRING_EDITOR_CFG_FILE);
      roleOIDs=(String)env.get(this.PRINTABLE_STRING_EDITOR_CFG_LINE);
    }

    if (roleTypesFilename==null && roleOIDs==null){
      //?? do what?
      return;
    }

    use_GUI = env.get(issrg.acm.EnvironmentalVariables.GUI_NOT_REQUIRED_FLAG)==null;

    StringBuffer sb = new StringBuffer(roleOIDs==null?"":
                                        roleOIDs.endsWith(this.OID_SEPARATOR)?
                                          roleOIDs:(roleOIDs+this.OID_SEPARATOR)
                                      );

    if (roleTypesFilename!=null){
      try{
        BufferedReader br = new BufferedReader(new FileReader(roleTypesFilename));
        while (br.ready()){
          String s=br.readLine();
	  if (s==null) break;
	  s = s.trim();
          if (s.intern()=="" || s.startsWith(COMMENT1) || s.startsWith(COMMENT2)){
            continue;
          }

          sb.append(s);
          sb.append(OID_SEPARATOR);
        }
        br.close();
      }catch (FileNotFoundException fnfe){
        issrg.utils.Util.bewail("OIDs file "+roleTypesFilename+" not found", fnfe, null);
      }catch (IOException ioe){
        issrg.utils.Util.bewail("Error reading OIDs file "+roleTypesFilename+" : "+ioe.getMessage(), ioe, null);
      }
    }

    roleOIDs = sb.toString();
    int from = 0;
    int l=roleOIDs.length();
    while (l>from){
      int i = roleOIDs.indexOf(this.OID_SEPARATOR, from);
      String o = roleOIDs.substring(from, i).trim();    // remove extra spaces
      from = i+this.OID_SEPARATOR.length();

      i=o.indexOf(" ");
      String name = i>0? o.substring(i+1).trim(): ""; // you could also check i>=0, to be more precise; but i need an OID to be non-empty. that' why
      if (i>0) o = o.substring(0, i); //.trim(); - no, don't trim: we don't need that anymore.

      new PermisRoleEditorHelper(o, name).registerMe(where);  // creating and registering a Helper
          // note that if an Editor for such an OID o is already registered,
          // nothing happens (Register.register returns false)
    }
  }

  public void bewail(String message){
    if (use_GUI){
      javax.swing.JOptionPane.showMessageDialog(null, message, "Error", javax.swing.JOptionPane.ERROR_MESSAGE);
    }else{
      System.err.println(message);
    }
  }

}

/**
 * This class is what actually gets registered with the Registry; one instance
 * per OID read from the configuration line and file.
 */
class PermisRoleEditorHelper extends issrg.acm.AttributeEditor {
  public String PERMIS_ROLE_OID;
  public String PERMIS_ROLE_TYPE;

  protected PermisRoleEditorHelper(String OID, String Type){
        if (Type.intern()=="") Type=OID;  // let's output something, if Type is not specified.

	PERMIS_ROLE_OID = OID;
	PERMIS_ROLE_TYPE = Type;
  }

  public String getName() {
//    return PERMIS_ROLE_TYPE+" "+getOID();
    return PERMIS_ROLE_TYPE;
}

  public String getOID() {
    return PERMIS_ROLE_OID;
  }

  public AttributeValue parseAttribute(AttributeValue attributeValue) throws iaik.asn1.CodingException{
    return new PermisRole(attributeValue);
  }

  public java.util.Vector buildValues(java.awt.Frame parentComponent, Map environment, java.util.Vector values, issrg.acm.Registry registry) throws issrg.acm.ACCreationException {
    java.util.Vector result=new java.util.Vector();
    try{
      if (values==null){
        //result.add(""); // ohmygod :-) this tiny thingy was causing troubles with null value being inserted :-)
      }else{
        for (int i=values.size(); i-->0;){
          AttributeValue attributeValue = (AttributeValue)values.get(i);

          String rv;
          if (!attributeValue.isDecoded()){
            rv = new PermisRole(attributeValue).getRoleValue();
          }else rv=((PermisRole)attributeValue).getRoleValue();

          result.add(0, rv);
        }
      }
    }catch (iaik.asn1.CodingException ce){
      throw new issrg.acm.ACCreationException("Error parsing the Attribute value: PermisRole attribute was expected", ce);
    }

    result = showInputDialog(parentComponent, result);
    if (result!=null){
      values= new java.util.Vector();

      for (int i=result.size(); i-->0;){
        values.add(0, new PermisRole((String)(result.get(i))));
      }
    }else values=null;  // it is specified to return null.

    return values;
  }


  private java.util.Vector showInputDialog(java.awt.Frame parentFrame, final java.util.Vector values){

      final JDialog dialog = new JDialog(parentFrame);
      final JList list = new JList(values);
      final JTextField text = new JTextField(10);
      final java.util.Vector [] result = new java.util.Vector[]{null};

      dialog.setTitle("Please enter the "+this.PERMIS_ROLE_TYPE+" attribute values");
      dialog.setModal(true);

      Container cnt = dialog.getContentPane();
      cnt.setLayout(new java.awt.BorderLayout());

      JPanel pData, pButton, pText, pArrows, pList;
      pData = new JPanel();
      pData.setBorder(new TitledBorder("Please add (or remove) the values to (from) the list"));

      pData.setLayout(new BorderLayout());
      pButton = new JPanel();
      pText = new JPanel();
      pText.setLayout(new GridLayout(5,1));
      pArrows = new JPanel();
      pArrows.setLayout(new GridLayout(5,1));
      pList = new JPanel();
      pList.setLayout(new BorderLayout());

      JButton jbRemove = new JButton("Remove");

      jbRemove.addActionListener(new java.awt.event.ActionListener(){
                public void actionPerformed(java.awt.event.ActionEvent ae){
                  int i;
                  if ((i=list.getSelectedIndex())>=0){
                    text.setText((String)values.remove(i));
                    list.setListData(values);
                  }
                }
            });

      JButton jbAdd = new JButton("Add");
      jbAdd.addActionListener(new java.awt.event.ActionListener(){
                public void actionPerformed(java.awt.event.ActionEvent ae){
                  String s;
                  if ((s=text.getText()).intern()=="") return;  // at the moment it does not allow to insert empty lines
                  values.add(s);
                  text.setText("");
                  int i=list.getSelectedIndex();
                  list.setListData(values);
                  list.setSelectedIndex(i);
                  list.ensureIndexIsVisible(values.size()-1);
                }
            });

      pArrows.add(new JLabel(""));
      pArrows.add(jbAdd);
      pArrows.add(new JLabel(""));
      pArrows.add(jbRemove);

      pText.add(new JLabel(""));
      pText.add(new JLabel("Value"));
      pText.add(text);

      JButton accept = new JButton("Accept");
      accept.addActionListener(new java.awt.event.ActionListener(){
                public void actionPerformed(java.awt.event.ActionEvent ae){
                  result[0]=values;
                  dialog.dispose();
                }
            });

      JButton cancel = new JButton("Cancel");
      cancel.addActionListener(new java.awt.event.ActionListener(){
                public void actionPerformed(java.awt.event.ActionEvent ae){
                  dialog.dispose();
                }
            });

      pButton.add(accept);
      pButton.add(cancel);

      JScrollPane scrollPane = new javax.swing.JScrollPane(list);
//      scrollPane.setBounds(0, 0, 100, 100);
      scrollPane.setHorizontalScrollBarPolicy(scrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
      scrollPane.setVerticalScrollBarPolicy(scrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
      list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      list.setFixedCellWidth(200);

      pList.add(scrollPane);

      pData.add("West",pText);
      pData.add("Center",pArrows);
      pData.add("East",pList);

      cnt.add("North",pData);
      cnt.add("South",pButton);

      dialog.pack();
      dialog.validate();

      Dimension screenSize = dialog.getToolkit().getScreenSize();
      Dimension size = dialog.getSize();
      screenSize.height = screenSize.height / 2;
      screenSize.width = screenSize.width / 2;
      size.height = size.height / 2;
      size.width = size.width / 2;
      int y = screenSize.height - size.height;
      int x = screenSize.width - size.width;
      dialog.setLocation(x, y);

      dialog.show();

      return result[0];
  }

}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -