コード例 #1
0
  /**
   * Returns external XS ds for object
   *
   * @return
   */
  public Map getExternalXSDs() {
    Map map = new HashMap();
    Enumeration enumerator = getExtNamespaces();

    while (enumerator.hasMoreElements()) {
      String namespace = (String) enumerator.nextElement();

      map.put(namespace, getExternalXSD(namespace));
    }
    return map;
  }
コード例 #2
0
  /**
   * Get the named properties for this resource and (potentially) its children.
   *
   * @param names an arrary of property names to retrieve
   * @return a MultiStatus of PropertyResponses
   * @exception com.ibm.webdav.WebDAVException
   */
  public MultiStatus getProperties(PropertyName[] names) throws WebDAVException {
    MultiStatus multiStatus = resource.getProperties(resource.getContext());
    MultiStatus newMultiStatus = new MultiStatus();

    Enumeration responses = multiStatus.getResponses();

    while (responses.hasMoreElements()) {
      PropertyResponse response = (PropertyResponse) responses.nextElement();
      PropertyResponse newResponse = new PropertyResponse(response.getResource());
      newResponse.setDescription(response.getDescription());
      newMultiStatus.addResponse(newResponse);

      Hashtable properties = (Hashtable) response.getPropertiesByPropName();

      // Hashtable newProperties = (Hashtable) newResponse.getProperties();
      for (int i = 0; i < names.length; i++) {
        if (properties.containsKey(names[i])) {
          PropertyValue srcval = response.getProperty(names[i]);
          newResponse.setProperty(names[i], srcval);

          // newProperties.put(names[i], properties.get(names[i]));
        } else {
          Document factory = null;

          try {
            factory = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
          } catch (Exception e) {
            throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
          }

          // we'll create an xml element with no value because that's
          //    what webdav will need to return for most methods... even if the
          //    property doesn't exist.   That's because the
          //    distinction between a propertyname and propertyvalue
          //    is fuzzy in WebDAV xml. A property name is
          //    essentially an empty property value because
          //    all property values have their property
          //    name stuck on.
          // if we decide to set reviewStatus to null instead (as
          //    we did previously, then the code for MultiStatus.asXML()
          //    needs to be updated to expect null values.
          // (jlc 990520)
          Element elTm = factory.createElementNS("X", "X:" + names[i].getLocal());

          elTm.setAttribute("xmlns:X", names[i].getNamespace());

          newResponse.addProperty(names[i], elTm, WebDAVStatus.SC_NOT_FOUND);
        }
      }
    }

    return newMultiStatus;
  }
コード例 #3
0
ファイル: TDTEngine.java プロジェクト: max90727/fosstrak
 /**
  * find a level by its type in a scheme. This involves iterating through the list of levels. The
  * main reason for doing it this way is to avoid being dependent on the order in which the levels
  * are coded in the xml, which is not explicitly constrained.
  */
 private Level findLevel(Scheme scheme, LevelTypeList levelType) {
   Level level = null;
   for (Enumeration e = scheme.enumerateLevel(); e.hasMoreElements(); ) {
     Level lev = (Level) e.nextElement();
     if (lev.getType() == levelType) {
       level = lev;
       break;
     }
   }
   if (level == null) throw new Error("Couldn't find type " + levelType + " in scheme " + scheme);
   return level;
 }
コード例 #4
0
  /**
   * This method tests whether this object of <code>InPort</code> has the required(mandatory) fields
   * set, before inserting values in the database.
   *
   * @exception FioranoException if the object is not valid
   * @since Tifosi2.0
   */
  public void validate() throws FioranoException {
    if (m_strPortName == null) {
      throw new FioranoException(DmiErrorCodes.ERR_INVALID_ARGUMENT_ERROR);
    }

    if (m_params != null) {
      Enumeration _enum = m_params.elements();

      while (_enum.hasMoreElements()) {
        Param param = (Param) _enum.nextElement();

        param.validate();
      }
    }
  }
コード例 #5
0
ファイル: TDTEngine.java プロジェクト: max90727/fosstrak
  /**
   * find a option by its type in a scheme. This involves iterating through the list of options. The
   * main reason for doing it this way is to avoid being dependent on the order in which the options
   * are coded in the xml, which is not explicitly constrained.
   */
  private Option findOption(Level level, String optionKey) {
    Option option = null;

    for (Enumeration e = level.enumerateOption(); e.hasMoreElements(); ) {
      Option opt = (Option) e.nextElement();
      if (opt.getOptionKey().equals(optionKey)) {
        option = opt;
        break;
      }
    }
    if (option == null)
      throw new Error("Couldn't find option for " + optionKey + " in level " + level);

    return option;
  }
コード例 #6
0
  public void generate() throws SAXException, ProcessingException {
    if (log.isDebugEnabled()) log.debug("begin generate");
    contentHandler.startDocument();
    Document doc = XercesHelper.getNewDocument();
    Element root = doc.createElement("authentication");
    doc.appendChild(root);
    try {
      LoginContext lc = new LoginContext(jaasRealm, new InternalCallbackHandler());
      lc.login();
      Subject s = lc.getSubject();
      if (log.isDebugEnabled()) log.debug("Subject is: " + s.getPrincipals().toString());
      Element idElement = doc.createElement("ID");
      root.appendChild(idElement);

      Iterator it = s.getPrincipals(java.security.Principal.class).iterator();
      while (it.hasNext()) {
        Principal prp = (Principal) it.next();
        if (prp.getName().equalsIgnoreCase("Roles")) {
          Element roles = doc.createElement("roles");
          root.appendChild(roles);
          Group grp = (Group) prp;
          Enumeration member = grp.members();
          while (member.hasMoreElements()) {
            Principal sg = (Principal) member.nextElement();
            Element role = doc.createElement("role");
            roles.appendChild(role);
            Text txt = doc.createTextNode(sg.getName());
            role.appendChild(txt);
          }
        } else {
          Node nde = doc.createTextNode(prp.getName());
          idElement.appendChild(nde);
        }
      }
      lc.logout();
    } catch (Exception exe) {
      log.warn("Could not login user \"" + userid + "\"");
    } finally {
      try {
        DOMStreamer ds = new DOMStreamer(contentHandler);
        ds.stream(doc.getDocumentElement());
        contentHandler.endDocument();
      } catch (Exception exe) {
        log.error("Error streaming to dom", exe);
      }
      if (log.isDebugEnabled()) log.debug("end generate");
    }
  }
コード例 #7
0
  /**
   * Retruns the xml string equivalent of this object
   *
   * @param document instance of Xml Document.
   * @return org.w3c.dom.Node
   * @exception FioranoException thrown in case of error.
   */
  protected Node toJXMLString(Document document) throws FioranoException {
    Node root0 = document.createElement("InPort");

    ((Element) root0).setAttribute("isSyncRequestType", "" + isSyncRequestType());

    Node child = null;

    child = XMLDmiUtil.getNodeObject("Name", m_strPortName, document);
    if (child != null) {
      root0.appendChild(child);
    }

    child = XMLDmiUtil.getNodeObject("Description", m_strDscription, document);
    if (child != null) {
      root0.appendChild(child);
    }

    if (m_strXSD != null) {
      Element elem = document.createElement("XSD");
      CDATASection cdata = document.createCDATASection(m_strXSD);

      elem.appendChild(cdata);
      root0.appendChild(elem);
    }

    child = XMLDmiUtil.getNodeObject("JavaClass", m_strJavaClass, document);
    if (child != null) {
      root0.appendChild(child);
    }

    if (m_params != null && m_params.size() > 0) {
      Enumeration _enum = m_params.elements();

      while (_enum.hasMoreElements()) {
        Param param = (Param) _enum.nextElement();
        if (!StringUtil.isEmpty(param.getParamName())
            && !StringUtil.isEmpty(param.getParamValue())) {
          Node paramNode = param.toJXMLString(document);

          root0.appendChild(paramNode);
        }
      }
    }

    return root0;
  }
コード例 #8
0
ファイル: TDTEngine.java プロジェクト: max90727/fosstrak
  /**
   * TDTEngine - constructor for a new Tag Data Translation engine
   *
   * @param confdir the string value of the path to a configuration directory consisting of two
   *     subdirectories, <code>schemes</code> and <code>auxiliary</code>.
   *     <p>When the class TDTEngine is constructed, the path to a local directory must be
   *     specified, by passing it as a single string parameter to the constructor method (without
   *     any trailing slash or file separator). e.g. <code>
   *     <pre>TDTEngine engine = new TDTEngine("/opt/TDT");</pre></code>
   *     <p>The specified directory must contain two subdirectories named auxiliary and schemes. The
   *     Tag Data Translation definition files for the various coding schemes should be located
   *     inside the subdirectory called <code>schemes</code>. Any auxiliary lookup files (such as
   *     <code>ManagerTranslation.xml</code>) should be located inside the subdirectory called
   *     <code>auxiliary</code>.
   *     <p>Files within the schemes directory ending in <code>.xml</code> are read in and
   *     unmarshalled using <a href = "http://www.castor.org">Castor</a>.
   */
  public TDTEngine(String confdir)
      throws FileNotFoundException, MarshalException, ValidationException, TDTException {
    xmldir = confdir;

    long t = System.currentTimeMillis();
    File[] dir =
        new java.io.File(confdir + File.separator + "schemes").listFiles(new XMLFilenameFilter());
    // java.util.Arrays.sort(dir); // Sort it
    if (dir == null) throw new TDTException("Cannot find schemes in " + confdir);
    Unmarshaller unmar = new Unmarshaller();
    for (File f : dir) {
      EpcTagDataTranslation tdt =
          (EpcTagDataTranslation) unmar.unmarshal(EpcTagDataTranslation.class, new FileReader(f));

      initFromTDT(tdt);
    }

    // need to populate the hashmap gs1cpi from the ManagerTranslation.xml table in auxiliary.
    // Unmarshaller unmar = new Unmarshaller();
    GEPC64Table cpilookup =
        (GEPC64Table)
            unmar.unmarshal(
                GEPC64Table.class,
                new FileReader(
                    confdir
                        + File.separator
                        + "auxiliary"
                        + File.separator
                        + "ManagerTranslation.xml"));
    for (Enumeration e = cpilookup.enumerateEntry(); e.hasMoreElements(); ) {
      Entry entry = (Entry) e.nextElement();
      String comp = entry.getCompanyPrefix();
      String indx = Integer.toString(entry.getIndex());
      gs1cpi.put(indx, comp);
      gs1cpi.put(comp, indx);
    }

    // System.out.println("Loaded schemas in " +
    //		   (System.currentTimeMillis() - t)
    //		   + " millisecs");

  }
コード例 #9
0
  /**
   * Get the names of all properties for this resource. This implementation reads all the properties
   * and then extracts their names.
   *
   * @return a MultiStatus of PropertyResponses (PropertyValue.value is always null,
   *     PropertyValue.status contains the status)
   * @exception com.ibm.webdav.WebDAVException
   */
  public MultiStatus getPropertyNames() throws WebDAVException {
    MultiStatus multiStatus = resource.getProperties(resource.getContext());
    Enumeration responses = multiStatus.getResponses();

    // we have the result, but all of the properties in our structure contain
    //    values.  We don't want to include values.  Just names.  The following
    //    code strips out the content of these elements.
    while (responses.hasMoreElements()) {
      PropertyResponse response = (PropertyResponse) responses.nextElement();
      Dictionary properties = response.getPropertiesByPropName();
      Enumeration keys = properties.keys();

      while (keys.hasMoreElements()) {
        PropertyName key = (PropertyName) keys.nextElement();
        Element value = (Element) response.getProperty(key).getValue();
        response.setProperty(
            key, new PropertyValue((Element) value.cloneNode(false), WebDAVStatus.SC_OK));
      }
    }

    return multiStatus;
  }
コード例 #10
0
ファイル: ObjectXml.java プロジェクト: pouncilt/vps-avs
  /* PROTECTED METHODS */
  protected void getBeanElements(
      Element parentElement, String objectName, String objectType, Object bean)
      throws IntrospectionException, IllegalAccessException {
    if (objectName == null) {
      // Get just the class name by lopping off the package name
      StringBuffer sb = new StringBuffer(bean.getClass().getName());
      sb.delete(0, sb.lastIndexOf(".") + 1);
      objectName = sb.toString();
    }

    // Check if the bean is a standard Java object type or a byte[] (encoded as a base 64 array)
    Element element = getStandardObjectElement(document, bean, objectName);
    // If the body element object is null then the bean is not a standard Java object type
    if (element != null) {
      if (includeNullValues
          || !element
              .getAttribute(
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI
                      + ":"
                      + org.apache.axis.Constants.ATTR_TYPE)
              .equals("anyType")) {
        if (!includeTypeInfo) {
          element.removeAttribute(
              NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + org.apache.axis.Constants.ATTR_TYPE);
          element.removeAttribute(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null");
        }
        parentElement.appendChild(element);
      }
    } else {
      // Analyze the bean
      Class classOfBean = null;
      if (bean != null) classOfBean = bean.getClass();
      // If the object is an array, then serialize each of the beans in the array.
      if ((classOfBean != null) && (classOfBean.isArray())) {
        String[] arrayInfo = getXsdSoapArrayInfo(classOfBean.getCanonicalName(), nsPrefix);
        int arrayLen = Array.getLength(bean);
        StringBuffer arrayType = new StringBuffer(arrayInfo[1]);
        arrayType.insert(arrayType.indexOf("[]") + 1, arrayLen);
        if (objectName.charAt(objectName.length() - 1) == ';')
          objectName =
              new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString();
        element = document.createElement(objectName);
        parentElement.appendChild(element);
        // Get the bean objects from the array and serialize each
        for (int i = 0; i < arrayLen; i++) {
          Object b = Array.get(bean, i);
          if (b != null) {
            String name = null;
            if (objectName.charAt(objectName.length() - 1) == 's') {
              name = formatName(objectName.substring(0, objectName.length() - 1));
            }
            getBeanElements(element, name, b.getClass().getName(), b);
          } else {
            // Array element is null, so don't include it and decrement the # elements in the array
            int index = arrayType.indexOf("[");
            arrayType.replace(index + 1, index + 2, String.valueOf(--arrayLen));
          }
          if (includeTypeInfo) {
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":Array");
            element.setAttributeNS(
                NamespaceConstants.NSURI_SOAP_ENCODING,
                NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE,
                arrayInfo[0] + ":" + arrayType.toString());
          }
        }
      } else {
        int beanType = 0;
        String beanName = null;
        if (classOfBean != null) {
          if (classOfBean == Vector.class) {
            beanType = 1;
            beanName = "Vector";
          } else if (classOfBean == ArrayList.class) {
            beanType = 2;
            beanName = "ArrayList";
          } else if (classOfBean == LinkedList.class) {
            beanType = 3;
            beanName = "LinkedList";
          } else if (classOfBean == Hashtable.class) {
            beanType = 4;
            beanName = "Hashtable";
          } else if (classOfBean == Properties.class) {
            beanType = 5;
            beanName = "Properties";
          } else if ((classOfBean == HashMap.class) || (classOfBean == SortedMap.class)) {
            beanType = 6;
            beanName = "Map";
          }
        }
        if (beanType > 0) {
          String prefix = null;
          if ((beanType == 1) || (beanType == 5))
            prefix = NamespaceConstants.NSPREFIX_SOAP_ENCODING;
          if (beanType == 6) prefix = Constants.NS_PREFIX_XMLSOAP;
          else prefix = DEFAULT_NS_PREFIX;
          element = document.createElement(objectName);
          if (includeTypeInfo) {
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                prefix + ":" + beanName);
            if (bean == null)
              element.setAttributeNS(
                  NamespaceConstants.NSURI_SCHEMA_XSI,
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null",
                  "true");
          }
          parentElement.appendChild(element);
          if ((beanType >= 1) && (beanType <= 3)) {
            AbstractCollection collection = (AbstractCollection) bean;
            // Get the bean objects from the vector and serialize each
            Iterator it = collection.iterator();
            while (it.hasNext()) {
              Object b = it.next();
              String name = null;
              if (b != null) {
                if (objectName.charAt(objectName.length() - 1) == 's') {
                  name = formatName(objectName.substring(0, objectName.length() - 1));
                } else name = "item";
              }
              getBeanElements(element, name, b.getClass().getName(), b);
            }
          } else if ((beanType == 4) || (beanType == 5)) {
            Hashtable hashtable = (Hashtable) bean;
            // Get the bean objects from the hashtable or properties and serialize each
            Enumeration en = hashtable.keys();
            while (en.hasMoreElements()) {
              Object key = en.nextElement();
              String keyClassName = key.getClass().getName();
              Object value = hashtable.get(key);
              String beanClassName = null;
              if (value != null) beanClassName = value.getClass().getName();
              Element itemElement = document.createElement("item");
              element.appendChild(itemElement);
              getBeanElements(itemElement, "key", keyClassName, key);
              getBeanElements(itemElement, "value", beanClassName, value);
            }
          } else if (beanType == 6) {
            Map map = null;
            if (classOfBean == HashMap.class) map = (HashMap) bean;
            else if (classOfBean == SortedMap.class) map = (SortedMap) bean;
            // Get the bean objects from the hashmap and serialize each
            Set set = map.keySet();
            Iterator it = set.iterator();
            while (it.hasNext()) {
              Object key = it.next();
              String keyClassName = key.getClass().getName();
              Object value = map.get(key);
              String beanClassName = null;
              if (value != null) beanClassName = value.getClass().getName();
              Element itemElement = document.createElement("item");
              element.appendChild(itemElement);
              getBeanElements(itemElement, "key", keyClassName, key);
              getBeanElements(itemElement, "value", beanClassName, value);
            }
          }
        } else {
          // Create a parent element for this bean's properties
          if (objectName.charAt(objectName.length() - 1) == ';')
            objectName =
                new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString();
          objectName = formatName(objectName);
          element = document.createElement(objectName);
          parentElement.appendChild(element);
          if (includeTypeInfo) {
            StringBuffer className = new StringBuffer(objectType);
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                nsPrefix + ":" + className.delete(0, className.lastIndexOf(".") + 1).toString());
          }
          if (classOfBean != null) {
            // Get an array of property descriptors
            BeanInfo bi = Introspector.getBeanInfo(classOfBean);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();
            // For each property of the bean, get a SOAPBodyElement that
            // represents the individual property. Append that SOAPBodyElement
            // to the class name element of the SOAP body.
            for (int i = 0; i < pds.length; i++) {
              PropertyDescriptor pd = pds[i];
              getBeanElementProperties(element, bean, pd);
            }
          } else {
            if (includeTypeInfo)
              element.setAttributeNS(
                  NamespaceConstants.NSURI_SCHEMA_XSI,
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null",
                  "true");
          }
        }
      }
    }
  }
コード例 #11
0
 /**
  * Discover WS device on the local network
  *
  * @return list of unique devices access strings which might be URLs in most cases
  */
 public static Collection<String> discoverWsDevices() {
   final Collection<String> addresses = new ConcurrentSkipListSet<>();
   final CountDownLatch serverStarted = new CountDownLatch(1);
   final CountDownLatch serverFinished = new CountDownLatch(1);
   final Collection<InetAddress> addressList = new ArrayList<>();
   try {
     final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
     if (interfaces != null) {
       while (interfaces.hasMoreElements()) {
         NetworkInterface anInterface = interfaces.nextElement();
         if (!anInterface.isLoopback()) {
           final List<InterfaceAddress> interfaceAddresses = anInterface.getInterfaceAddresses();
           for (InterfaceAddress address : interfaceAddresses) {
             addressList.add(address.getAddress());
           }
         }
       }
     }
   } catch (SocketException e) {
     e.printStackTrace();
   }
   ExecutorService executorService = Executors.newCachedThreadPool();
   for (final InetAddress address : addressList) {
     Runnable runnable =
         new Runnable() {
           public void run() {
             try {
               final String uuid = UUID.randomUUID().toString();
               final String probe =
                   WS_DISCOVERY_PROBE_MESSAGE.replaceAll(
                       "<wsa:MessageID>urn:uuid:.*</wsa:MessageID>",
                       "<wsa:MessageID>urn:uuid:" + uuid + "</wsa:MessageID>");
               final int port = random.nextInt(20000) + 40000;
               @SuppressWarnings("SocketOpenedButNotSafelyClosed")
               final DatagramSocket server = new DatagramSocket(port, address);
               new Thread() {
                 public void run() {
                   try {
                     final DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
                     server.setSoTimeout(WS_DISCOVERY_TIMEOUT);
                     long timerStarted = System.currentTimeMillis();
                     while (System.currentTimeMillis() - timerStarted < (WS_DISCOVERY_TIMEOUT)) {
                       serverStarted.countDown();
                       server.receive(packet);
                       final Collection<String> collection =
                           parseSoapResponseForUrls(
                               Arrays.copyOf(packet.getData(), packet.getLength()));
                       for (String key : collection) {
                         addresses.add(key);
                       }
                     }
                   } catch (SocketTimeoutException ignored) {
                   } catch (Exception e) {
                     e.printStackTrace();
                   } finally {
                     serverFinished.countDown();
                     server.close();
                   }
                 }
               }.start();
               try {
                 serverStarted.await(1000, TimeUnit.MILLISECONDS);
               } catch (InterruptedException e) {
                 e.printStackTrace();
               }
               if (address instanceof Inet4Address) {
                 server.send(
                     new DatagramPacket(
                         probe.getBytes(),
                         probe.length(),
                         InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv4),
                         WS_DISCOVERY_PORT));
               } else {
                 server.send(
                     new DatagramPacket(
                         probe.getBytes(),
                         probe.length(),
                         InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv6),
                         WS_DISCOVERY_PORT));
               }
             } catch (Exception e) {
               e.printStackTrace();
             }
             try {
               serverFinished.await((WS_DISCOVERY_TIMEOUT), TimeUnit.MILLISECONDS);
             } catch (InterruptedException e) {
               e.printStackTrace();
             }
           }
         };
     executorService.submit(runnable);
   }
   try {
     executorService.shutdown();
     executorService.awaitTermination(WS_DISCOVERY_TIMEOUT + 2000, TimeUnit.MILLISECONDS);
   } catch (InterruptedException ignored) {
   }
   return addresses;
 }
コード例 #12
0
ファイル: PatternDecision.java プロジェクト: burgeje/SEURAT
  /**
   * Get the decision from the database, given its name
   *
   * @param name the decision name
   */
  public void fromDatabase(String name) {
    String findQuery = "";
    RationaleDB db = RationaleDB.getHandle();
    Connection conn = db.getConnection();

    this.name = name;
    name = RationaleDBUtil.escape(name);

    Statement stmt = null;
    ResultSet rs = null;
    try {
      stmt = conn.createStatement();
      findQuery = "SELECT *  FROM " + "PATTERNDECISIONS where name = '" + name + "'";
      //			***			System.out.println(findQuery);
      rs = stmt.executeQuery(findQuery);

      if (rs.next()) {
        id = rs.getInt("id");
        description = RationaleDBUtil.decode(rs.getString("description"));
        type = (DecisionType) DecisionType.fromString(rs.getString("type"));
        devPhase = (Phase) Phase.fromString(rs.getString("phase"));
        ptype = RationaleElementType.fromString(rs.getString("ptype"));
        parent = rs.getInt("parent");
        //				artifact = rs.getString("artifact");
        //				enabled = rs.getBoolean("enabled");
        status = (DecisionStatus) DecisionStatus.fromString(rs.getString("status"));
        String subdecs = rs.getString("subdecreq");
        if (subdecs.compareTo("Yes") == 0) {
          alts = false;
        } else {
          alts = true;
        }

        try {
          int desID = rs.getInt("designer");
          designer = new Designer();
          designer.fromDatabase(desID);
        } catch (SQLException ex) {
          designer = null; // nothing...
        }
      }
      rs.close();
      // need to read in the rest - recursive routines?
      subDecisions.removeAllElements();
      alternatives.removeAllElements();
      if (!alts) {
        Vector<String> decNames = new Vector<String>();
        findQuery =
            "SELECT name from PATTERNDECISIONS where "
                + "ptype = '"
                + RationaleElementType.DECISION.toString()
                + "' and parent = "
                + new Integer(id).toString();
        //				***					System.out.println(findQuery2);
        rs = stmt.executeQuery(findQuery);
        while (rs.next()) {
          decNames.add(RationaleDBUtil.decode(rs.getString("name")));
        }
        Enumeration decs = decNames.elements();
        while (decs.hasMoreElements()) {
          PatternDecision subDec = new PatternDecision();
          subDec.fromDatabase((String) decs.nextElement());
          subDecisions.add(subDec);
        }

      } else {
        Vector<String> altNames = new Vector<String>();
        findQuery =
            "SELECT name from ALTERNATIVES where "
                + "ptype = '"
                + RationaleElementType.DECISION.toString()
                + "' and parent = "
                + new Integer(id).toString();
        //				***					System.out.println(findQuery2);
        rs = stmt.executeQuery(findQuery);
        while (rs.next()) {
          altNames.add(RationaleDBUtil.decode(rs.getString("name")));
        }
        Enumeration alts = altNames.elements();
        while (alts.hasMoreElements()) {
          Alternative alt = new Alternative();
          alt.fromDatabase((String) alts.nextElement());
          alternatives.add(alt);
        }
      }

      // need to do questions too
      Vector<String> questNames = new Vector<String>();
      findQuery =
          "SELECT name from QUESTIONS where "
              + "ptype = '"
              + RationaleElementType.DECISION.toString()
              + "' and parent = "
              + new Integer(id).toString();
      //			***				System.out.println(findQuery3);
      rs = stmt.executeQuery(findQuery);
      while (rs.next()) {
        questNames.add(RationaleDBUtil.decode(rs.getString("name")));
      }
      Enumeration quests = questNames.elements();
      questions.removeAllElements();
      while (quests.hasMoreElements()) {
        Question quest = new Question();
        quest.fromDatabase((String) quests.nextElement());
        questions.add(quest);
      }

      // no, not last - need history too
      findQuery =
          "SELECT * from HISTORY where ptype = 'Decision' and "
              + "parent = "
              + Integer.toString(id);
      //			***			  System.out.println(findQuery5);
      rs = stmt.executeQuery(findQuery);
      history.removeAllElements();
      while (rs.next()) {
        History nextH = new History();
        nextH.setStatus(rs.getString("status"));
        nextH.setReason(RationaleDBUtil.decode(rs.getString("reason")));
        nextH.dateStamp = rs.getTimestamp("date");
        //				nextH.dateStamp = rs.getDate("date");
        history.add(nextH);
      }

      // now, get our constraints
      findQuery =
          "SELECT * from ConDecRelationships WHERE " + "decision = " + new Integer(id).toString();

      rs = stmt.executeQuery(findQuery);
      constraints.removeAllElements();
      if (rs != null) {
        while (rs.next()) {
          int ontID = rs.getInt("constr");
          Constraint cont = new Constraint();
          cont.fromDatabase(ontID);
          this.addConstraint(cont);
        }
        rs.close();
      }

      // now, candidate patterns
      findQuery =
          "SELECT * from pattern_decision WHERE parentType= 'Decision' and decisionID=" + this.id;
      rs = stmt.executeQuery(findQuery);
      if (rs != null) {
        while (rs.next()) {
          int patternID = rs.getInt("patternID");
          Pattern p = new Pattern();
          p.fromDatabase(patternID);
          this.addCandidatePattern(p);
        }
      }

    } catch (SQLException ex) {
      // handle any errors
      RationaleDB.reportError(ex, "Error in PatternDecision.fromDatabase", findQuery);

    } finally {
      RationaleDB.releaseResources(stmt, rs);
    }
  }
コード例 #13
0
ファイル: PatternDecision.java プロジェクト: burgeje/SEURAT
  /**
   * Save our decision to the database.
   *
   * @param parent - the parent of the decision
   * @param ptype - the parent's type
   * @return the unique ID
   */
  public int toDatabase(int parent, RationaleElementType ptype) {
    RationaleDB db = RationaleDB.getHandle();
    Connection conn = db.getConnection();
    String updateQuery = "";
    int ourid = 0;

    RationaleUpdateEvent l_updateEvent;

    // find out if this requirement is already in the database
    Statement stmt = null;
    ResultSet rs = null;

    String subsReq = "No";
    if (!alts) subsReq = "Yes";

    try {
      stmt = conn.createStatement();

      if (inDatabase(parent, ptype)) {
        // set up Designer update string
        String updateD;
        if (designer == null) updateD = "D.designer = null";
        else updateD = "D.designer = " + designer.getID();

        updateQuery =
            "UPDATE PATTERNDECISIONS D "
                + "SET D.parent = "
                + new Integer(parent).toString()
                + ", D.ptype = '"
                + ptype.toString()
                + "', D.phase = '"
                + devPhase.toString()
                + "', D.description = '"
                + RationaleDBUtil.escape(description)
                + "', D.type = '"
                + type.toString()
                + "', D.name = '"
                + RationaleDBUtil.escape(name)
                + "', D.status = '"
                + status.toString()
                + "', D.subdecreq = '"
                + subsReq
                + "', "
                + updateD
                + " WHERE "
                + "D.id = "
                + this.id
                + " ";
        stmt.execute(updateQuery);

        l_updateEvent = m_eventGenerator.MakeUpdated();
      } else {
        if (!fromXML) id = RationaleDB.findAvailableID("PATTERNDECISIONS");

        String parentSt;
        String parentTSt;

        // now, we have determined that the decision is new
        if ((this.parent < 0) || (ptype == null)) {
          parentSt = "NULL";
          parentTSt = "None";
        } else {
          parentSt = new Integer(this.parent).toString();
          parentTSt = ptype.toString();
        }
        String updateD;
        if (designer == null) updateD = "null";
        else updateD = new Integer(designer.getID()).toString();

        updateQuery =
            "INSERT INTO PATTERNDECISIONS "
                + "(id, name, description, type, status, phase, subdecreq, parent, ptype, designer) "
                + "VALUES ("
                + id
                + ", '"
                + RationaleDBUtil.escape(this.name)
                + "', '"
                + RationaleDBUtil.escape(this.description)
                + "', '"
                + this.type.toString()
                + "', '"
                + this.status.toString()
                + "', '"
                + this.devPhase.toString()
                + "', '"
                + subsReq
                + "', "
                + parentSt
                + ", '"
                + parentTSt
                + "', "
                + updateD
                + ")";

        stmt.execute(updateQuery);

        /*
        //Now, associate with pattern.
        //Get id first
        updateQuery = "SELECT id FROM patterndecisions where name='" +
        RationaleDBUtil.escape(this.name) + "'";
        rs = stmt.executeQuery(updateQuery);

        if (rs.next())
        {
        	ourid = rs.getInt("id");
        	rs.close();
        	//We have found out our ID and the insert is a success.
        	//get association set up.
        	updateQuery = "INSERT into pattern_decision values (" + parent +
        	"ourid" + "DECISION)";
        }

        //And now, we have patternID and patterndecisionID. We can insert into relationship entry
        updateQuery = "INSERT INTO pattern_decision values (" + parentPattern + ", " +
        ourid + ", " + "'Decision')";
        stmt.execute(updateQuery);
        */
        l_updateEvent = m_eventGenerator.MakeCreated();
      }
      // in either case, we want to update any sub-requirements in case
      // they are new!
      // now, we need to get our ID
      updateQuery =
          "SELECT id FROM PATTERNDECISIONS where name='" + RationaleDBUtil.escape(this.name) + "'";
      rs = stmt.executeQuery(updateQuery);

      if (rs.next()) {
        ourid = rs.getInt("id");
        rs.close();
      } else {
        ourid = -1;
      }
      this.id = ourid;

      Enumeration alts = alternatives.elements();
      while (alts.hasMoreElements()) {
        Alternative alt = (Alternative) alts.nextElement();
        //				System.out.println("Saving alternative from decision");
        alt.toDatabase(ourid, RationaleElementType.DECISION);
      }

      Enumeration decs = subDecisions.elements();
      while (decs.hasMoreElements()) {
        Decision dec = (Decision) decs.nextElement();
        dec.toDatabase(ourid, RationaleElementType.DECISION);
      }

      Enumeration quests = questions.elements();
      while (quests.hasMoreElements()) {
        Question quest = (Question) quests.nextElement();
        quest.toDatabase(ourid, RationaleElementType.DECISION);
      }

      // finally, the history

      Enumeration hist = history.elements();
      while (hist.hasMoreElements()) {
        History his = (History) hist.nextElement();
        his.toDatabase(ourid, RationaleElementType.DECISION);
      }

      // need to update our relationships with the constraints
      Enumeration conkids = this.constraints.elements();
      while (conkids.hasMoreElements()) {
        Constraint kid = (Constraint) conkids.nextElement();
        // if the parent ID is not zero, then update the parent-child relationship

        updateQuery =
            "SELECT * from ConDecRelationships WHERE "
                + "constr = "
                + new Integer(kid.getID()).toString()
                + " and decision = "
                + new Integer(ourid).toString();

        rs = stmt.executeQuery(updateQuery.toUpperCase());
        if (rs.next()) {
          rs.close();
        } else {
          String insertRel =
              "INSERT INTO ConDecRelationships (constr, decision) "
                  + "VALUES ("
                  + new Integer(kid.getID()).toString()
                  + ", "
                  + new Integer(ourid).toString()
                  + ")";
          System.out.println(insertRel.toUpperCase());
          stmt.execute(insertRel);
        }
        kid.toDatabase(ourid);
      } // checking parent

      m_eventGenerator.Broadcast(l_updateEvent);
    } catch (SQLException ex) {
      // handle any errors
      RationaleDB.reportError(ex, "Error in PatternDecision.toDatabase", updateQuery);

    } finally {
      RationaleDB.releaseResources(stmt, rs);
    }

    return ourid;
  }
コード例 #14
0
  /**
   * Edit the properties of a resource. The updates must refer to a Document containing a WebDAV
   * propertyupdates element as the document root.
   *
   * @param updates an XML Document containing propertyupdate elements
   * @return the result of making the updates describing the edits to be made.
   * @exception com.ibm.webdav.WebDAVException
   */
  public MultiStatus setProperties(Document propertyUpdates) throws WebDAVException {
    // create a MultiStatus to hold the results. It will hold a MethodResponse
    // for each update, and one for the method as a whole
    MultiStatus multiStatus = new MultiStatus();
    boolean errorsOccurred = false;

    // first, load the properties so they can be edited
    Document propertiesDocument = resource.loadProperties();
    Element properties = (Element) propertiesDocument.getDocumentElement();

    // be sure the updates have at least one update
    Element propertyupdate = (Element) propertyUpdates.getDocumentElement();
    String tagName = propertyupdate.getNamespaceURI() + propertyupdate.getLocalName();

    if (!tagName.equals("DAV:propertyupdate")) {
      throw new WebDAVException(
          WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "missing propertyupdate element");
    }

    NodeList updates = propertyupdate.getChildNodes();

    if (updates.getLength() == 0) {
      throw new WebDAVException(WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no updates in request");
    }

    Vector propsGood = new Vector(); // a list of properties that

    // were patched correctly or would have been if another
    // property hadn't gone bad.
    // apply the updates
    Node temp = null;

    for (int i = 0; i < updates.getLength(); i++) {
      temp = updates.item(i);

      // skip any ignorable TXText elements
      if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
        continue;
      }

      Element update = (Element) temp;
      int updateCommand = -1;
      tagName = update.getNamespaceURI() + update.getLocalName();

      if (tagName.equals("DAV:set")) {
        updateCommand = set;
      } else if (tagName.equals("DAV:remove")) {
        updateCommand = remove;
      } else {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY,
            update.getTagName() + " is not a valid property update request");
      }

      // iterate through the props in the set or remove element and update the
      // properties as directed
      Element prop = (Element) update.getElementsByTagNameNS("DAV:", "prop").item(0);

      if (prop == null) {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no propeprties in update request");
      }

      NodeList propsToUpdate = prop.getChildNodes();

      for (int j = 0; j < propsToUpdate.getLength(); j++) {
        temp = propsToUpdate.item(j);

        // skip any TXText elements??
        if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
          continue;
        }

        Element propToUpdate = (Element) temp;

        // find the property in the properties element
        Element property = null;
        PropertyName propertyName = new PropertyName(propToUpdate);

        if (((Element) propToUpdate).getNamespaceURI() != null) {
          property =
              (Element)
                  properties
                      .getElementsByTagNameNS(
                          propToUpdate.getNamespaceURI(), propToUpdate.getLocalName())
                      .item(0);
        } else {
          property = (Element) properties.getElementsByTagName(propToUpdate.getTagName()).item(0);
        }

        boolean liveone = isLive(propertyName.asExpandedString());

        if (liveone) {
          errorsOccurred = true;

          PropertyResponse response = new PropertyResponse(resource.getURL().toString());
          response.addProperty(propertyName, propToUpdate, WebDAVStatus.SC_FORBIDDEN);
          multiStatus.addResponse(response);
        }

        // do the update
        if (updateCommand == set) {
          if (property != null) {
            try {
              properties.removeChild(property);
            } catch (DOMException exc) {
            }
          }

          if (!liveone) {
            // I don't think we're allowed to update live properties
            //    here.  Doing so effects the cache.  A case in
            //    point is the lockdiscoveryproperty.  properties
            //    is actually the properites cache "document" of this
            //    resource.  Even though we don't "save" the request
            //    if it includes live properties, we don't remove
            //    it from the cache after we'd set it here, so it
            //    can affect other queries. (jlc 991002)
            properties.appendChild(propertiesDocument.importNode(propToUpdate, true));

            propsGood.addElement(propToUpdate);
          }
        } else if (updateCommand == remove) {
          try {
            if (property != null) {
              properties.removeChild(property);
              propsGood.addElement(propToUpdate);
            }
          } catch (DOMException exc) {
          }
        }
      }
    }

    {
      Enumeration els = propsGood.elements();

      for (; els.hasMoreElements(); ) {
        Object ob1 = els.nextElement();
        Element elProp = (Element) ob1;
        PropertyName pn = new PropertyName(elProp);
        PropertyResponse response = new PropertyResponse(resource.getURL().toString());
        response.addProperty(
            pn,
            (Element) elProp.cloneNode(false),
            (errorsOccurred ? WebDAVStatus.SC_FAILED_DEPENDENCY : WebDAVStatus.SC_OK));

        // todo: add code for responsedescription
        multiStatus.addResponse(response);
      }
    }

    // write out the properties
    if (!errorsOccurred) {
      resource.saveProperties(propertiesDocument);
    }

    return multiStatus;
  }
コード例 #15
0
ファイル: TDTEngine.java プロジェクト: max90727/fosstrak
  /** convert from a particular scheme / level */
  private String convertLevel(
      Scheme tdtscheme,
      Level tdtlevel,
      String input,
      Map<String, String> inputParameters,
      LevelTypeList outboundlevel) {

    String outboundstring;
    Map<String, String> extraparams =
        //	    new NoisyMap
        (new HashMap<String, String>(inputParameters));

    // get the scheme's option key, which is the name of a
    // parameter whose value is matched to the option key of the
    // level.

    String optionkey = tdtscheme.getOptionKey();
    String optionValue = extraparams.get(optionkey);
    // the name of a parameter which allows the appropriate option
    // to be selected

    // now consider the various options within the scheme and
    // level for each option element inside the level, check
    // whether the pattern attribute matches as a regular
    // expression

    String matchingOptionKey = null;
    Option matchingOption = null;
    Matcher prefixMatcher = null;
    for (Enumeration e = tdtlevel.enumerateOption(); e.hasMoreElements(); ) {
      Option opt = (Option) e.nextElement();
      if (optionValue == null || optionValue.equals(opt.getOptionKey())) {
        // possible match

        Matcher matcher = Pattern.compile(opt.getPattern()).matcher(input);
        if (matcher.matches()) {
          if (prefixMatcher != null) throw new TDTException("Multiple patterns matched");
          prefixMatcher = matcher;
          matchingOptionKey = opt.getOptionKey();
          matchingOption = opt;
        }
      }
    }
    if (prefixMatcher == null) throw new TDTException("No patterns matched");

    optionValue = matchingOptionKey;

    for (Enumeration e = matchingOption.enumerateField(); e.hasMoreElements(); ) {
      Field field = (Field) e.nextElement();
      int seq = field.getSeq();

      String strfieldname = field.getName();
      int fieldlength = field.getLength();
      String strfieldvalue = prefixMatcher.group(seq);
      // System.out.println("   processing field " + strfieldname + " = '" + strfieldvalue + "'");

      if (field.getCompaction() == null) {
        // if compaction is null, treat field as an integer

        if (field.getCharacterSet() != null) { // if the character set is specified
          Matcher charsetmatcher =
              Pattern.compile("^" + field.getCharacterSet() + "$").matcher(strfieldvalue);
          if (!charsetmatcher.matches()) {
            throw new TDTException(
                "field "
                    + strfieldname
                    + " ("
                    + strfieldvalue
                    + ") does not conform to the allowed character set ("
                    + field.getCharacterSet()
                    + ") ");
          }
        }

        BigInteger bigvalue = null;

        if (tdtlevel.getType() == LevelTypeList.BINARY) { // if the input was BINARY
          bigvalue = new BigInteger(strfieldvalue, 2);
          extraparams.put(strfieldname, bigvalue.toString());
        } else {
          if (field.getDecimalMinimum() != null || field.getDecimalMaximum() != null)
            bigvalue = new BigInteger(strfieldvalue);
          extraparams.put(strfieldname, strfieldvalue);
        }

        if (field.getDecimalMinimum() != null) { // if the decimal minimum is specified
          BigInteger bigmin = new BigInteger(field.getDecimalMinimum());

          if (bigvalue.compareTo(bigmin)
              == -1) { // throw an exception if the field value is less than the decimal minimum
            throw new TDTException(
                "field "
                    + strfieldname
                    + " ("
                    + bigvalue
                    + ") is less than DecimalMinimum ("
                    + field.getDecimalMinimum()
                    + ") allowed");
          }
        }

        if (field.getDecimalMaximum() != null) { // if the decimal maximum is specified
          BigInteger bigmax = new BigInteger(field.getDecimalMaximum());

          if (bigvalue.compareTo(bigmax)
              == 1) { // throw an excpetion if the field value is greater than the decimal maximum
            throw new TDTException(
                "field "
                    + strfieldname
                    + " ("
                    + bigvalue
                    + ") is greater than DecimalMaximum ("
                    + field.getDecimalMaximum()
                    + ") allowed");
          }
        }

        // after extracting the field, it may be necessary to pad it.

        padField(extraparams, field);

      } else {
        // compaction is specified - interpret binary as a string value using a truncated byte per
        // character

        CompactionMethodList compaction = field.getCompaction();
        PadDirectionList padDir = field.getPadDir();
        String padchar = field.getPadChar();
        String s;
        if (compaction == CompactionMethodList.VALUE_5)
          // "5-bit"
          s = bin2uppercasefive(strfieldvalue);
        else if (compaction == CompactionMethodList.VALUE_4)
          // 6-bit
          s = bin2alphanumsix(strfieldvalue);
        else if (compaction == CompactionMethodList.VALUE_3)
          // 7-bit
          s = bin2asciiseven(strfieldvalue);
        else if (compaction == CompactionMethodList.VALUE_2)
          // 8-bit
          s = bin2bytestring(strfieldvalue);
        else throw new Error("unsupported compaction method " + compaction);
        extraparams.put(strfieldname, stripPadChar(s, padDir, padchar));
      }
    } // for each field;

    /**
     * the EXTRACT rules are performed after parsing the input, in order to determine additional
     * fields that are to be derived from the fields obtained by the pattern match process
     */
    int seq = 0;
    for (Enumeration e = tdtlevel.enumerateRule(); e.hasMoreElements(); ) {
      Rule tdtrule = (Rule) e.nextElement();
      if (tdtrule.getType() == ModeList.EXTRACT) {
        assert seq < tdtrule.getSeq() : "Rule out of sequence order";
        seq = tdtrule.getSeq();
        processRules(extraparams, tdtrule);
      }
    }

    /**
     * Now we need to consider the corresponding output level and output option. The scheme must
     * remain the same, as must the value of optionkey (to select the corresponding option element
     * nested within the required outbound level)
     */
    Level tdtoutlevel = findLevel(tdtscheme, outboundlevel);
    Option tdtoutoption = findOption(tdtoutlevel, optionValue);

    /**
     * the FORMAT rules are performed before formatting the output, in order to determine additional
     * fields that are required for preparation of the outbound format
     */
    seq = 0;
    for (Enumeration e = tdtoutlevel.enumerateRule(); e.hasMoreElements(); ) {
      Rule tdtrule = (Rule) e.nextElement();
      if (tdtrule.getType() == ModeList.FORMAT) {
        assert seq < tdtrule.getSeq() : "Rule out of sequence order";
        seq = tdtrule.getSeq();
        processRules(extraparams, tdtrule);
      }
    }

    /**
     * Now we need to ensure that all fields required for the outbound grammar are suitably padded
     * etc. processPadding takes care of firstly padding the non-binary fields if padChar and
     * padDir, length are specified then (if necessary) converting to binary and padding the binary
     * representation to the left with zeros if the bit string is has fewer bits than the bitLength
     * attribute specifies. N.B. TDTv1.1 will be more specific about bit-level padding rather than
     * assuming that it is always to the left with the zero bit.
     */

    // System.out.println(" prior to processPadding, " + extraparams);
    for (Enumeration e = tdtoutoption.enumerateField(); e.hasMoreElements(); ) {
      Field field = (Field) e.nextElement();
      // processPadding(extraparams, field, outboundlevel, tdtoutoption);

      padField(extraparams, field);
      if (outboundlevel == LevelTypeList.BINARY) binaryPadding(extraparams, field);
    }

    /**
     * Construct the output from the specified grammar (in ABNF format) together with the field
     * values stored in inputparams
     */
    outboundstring = buildGrammar(tdtoutoption.getGrammar(), extraparams);

    // System.out.println("final extraparams = " + extraparams);
    // System.out.println("returned " + outboundstring);
    return outboundstring;
  }