Пример #1
0
 private boolean checkElement(List<Element> els, String name, String localTypeName) {
   for (Element e : els) {
     if (name.equals(e.getAttribute("name"))) {
       String type = e.getAttribute("type");
       if (!StringUtils.isEmpty(type)) {
         if (checkTypeName(e, type, localTypeName)) {
           return true;
         }
       } else if ("books".equals(name) || "thebook2s".equals(name)) {
         boolean thebooks2 = "thebook2s".equals(name);
         Element ctElement =
             (Element)
                 e.getElementsByTagNameNS(Constants.URI_2001_SCHEMA_XSD, "complexType").item(0);
         Element seqElement =
             (Element)
                 ctElement
                     .getElementsByTagNameNS(Constants.URI_2001_SCHEMA_XSD, "sequence")
                     .item(0);
         Element xsElement =
             (Element)
                 seqElement
                     .getElementsByTagNameNS(Constants.URI_2001_SCHEMA_XSD, "element")
                     .item(0);
         String ref = xsElement.getAttribute("ref");
         if (checkTypeName(e, ref, thebooks2 ? "thebook2" : "thebook")) {
           return true;
         }
       }
     }
   }
   return false;
 }
Пример #2
0
  @Before
  public void dbInit() throws Exception {
    String configFileName = System.getProperty("user.home");
    if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
      configFileName += "/.pokerth/config.xml";
    } else {
      configFileName += "/AppData/Roaming/pokerth/config.xml";
    }
    File file = new File(configFileName);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    Element configNode = (Element) doc.getElementsByTagName("Configuration").item(0);

    Element dbAddressNode = (Element) configNode.getElementsByTagName("DBServerAddress").item(0);
    String dbAddress = dbAddressNode.getAttribute("value");

    Element dbUserNode = (Element) configNode.getElementsByTagName("DBServerUser").item(0);
    String dbUser = dbUserNode.getAttribute("value");

    Element dbPasswordNode = (Element) configNode.getElementsByTagName("DBServerPassword").item(0);
    String dbPassword = dbPasswordNode.getAttribute("value");

    Element dbNameNode = (Element) configNode.getElementsByTagName("DBServerDatabaseName").item(0);
    String dbName = dbNameNode.getAttribute("value");

    final String dbUrl = "jdbc:mysql://" + dbAddress + ":3306/" + dbName;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    dbConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
  }
 private BxBounds parseElementContainingVertexes(Element el) {
   ArrayList<Element> vs = getChildren("Vertex", el);
   if (vs.isEmpty()) {
     return null;
   }
   ArrayList<ComparablePair<Integer, Integer>> list =
       new ArrayList<ComparablePair<Integer, Integer>>();
   int minx = Integer.MAX_VALUE;
   int maxx = Integer.MIN_VALUE;
   int miny = Integer.MAX_VALUE;
   int maxy = Integer.MIN_VALUE;
   for (Element v : vs) {
     int x = Integer.parseInt(v.getAttribute("x"));
     if (x < minx) minx = x;
     if (x > maxx) maxx = x;
     int y = Integer.parseInt(v.getAttribute("y"));
     if (y < miny) miny = y;
     if (y > maxy) maxy = y;
     list.add(new ComparablePair<Integer, Integer>(x, y));
   }
   Collections.sort(list);
   ComparablePair<Integer, Integer> mine = list.get(0);
   ComparablePair<Integer, Integer> maxe = list.get(list.size() - 1);
   BxBounds ret = new BxBounds(minx, miny, maxx - minx, maxy - miny);
   if (ret.getHeight() == 0 || ret.getWidth() == 0) {
     log.warn("problems with height or width points are:");
     for (ComparablePair<Integer, Integer> pa : list) {
       log.warn("\t" + pa.o1 + " , " + pa.o2);
     }
   }
   return ret;
 }
Пример #4
0
  private Guard createGuard(Element element) {
    Guard guard = IrFactory.eINSTANCE.createGuard();
    String id = element.getAttribute("id");
    guard.setId(id);
    doAnnotations(guard, element);

    addIrObject(id, guard);

    Action action = (Action) findIrObject(element.getAttribute("outer-scope"));
    guard.setOuter(action);

    List<Element> decls = getChildren(element, "Decl");
    for (Element e : decls) {
      Declaration decl = createDeclaration(e);
      guard.getDeclarations().add(decl);
    }

    List<Element> peeks = getChildren(element, "PortPeek");
    for (Element e : peeks) {
      PortPeek peek = createPortPeek(action, e);
      guard.getPeeks().add(peek);
    }

    Expression body = createExpression(getChild(element, "Expr"));
    guard.setBody(body);

    guard.setType(TypeSystem.createTypeBool());

    return guard;
  }
Пример #5
0
  public Key(Node keyNode, Element commandElement) {
    this(keyNode.getTextContent().trim());

    if (keyNode instanceof Element) {
      Element keyElem = (Element) keyNode;
      String key = keyElem.getAttribute("jawskey");
      if ((key != null) && (key.length() > 0)) {
        jawsKey = new Key(key);
      }
      String jawsHandleVal = keyElem.getAttribute("jawshandle");
      if (jawsHandleVal != null) {
        if (jawsHandleVal.trim().equals("true")) {
          jawsHandle = true;
        }
      }
      String jawsSayAllStopVal = keyElem.getAttribute("jawsSayAllStop");
      if (jawsSayAllStopVal != null) {
        if (jawsSayAllStopVal.trim().equals("false")) {
          jawsSayAllStop = false;
        }
      }
      String jawsScriptVal = keyElem.getAttribute("jawsscript");
      if (jawsScriptVal != null) {
        if (jawsScriptVal.trim().equals("false")) {
          jawsScript = false;
        }
      }
      if ("speakAll".equals(commandElement.getTagName())) {
        jawsSayAllStopIgnore = true;
      }
    }
  }
Пример #6
0
 private static Condition parse(Element element, LogHeaderDefinition definition) {
   String name = element.getTagName();
   if ("message".equals(name))
     try {
       return new MessageCondition(Pattern.compile(element.getTextContent()));
     } catch (PatternSyntaxException ex) {
       throw new RuntimeException(
           "[LogFilter] invalid regex " + element.getTextContent() + " in message element", ex);
     }
   else if ("field".equals(name)) {
     Attr attr = element.getAttributeNode("name");
     if (attr == null)
       throw new IllegalArgumentException("[LogFilter] name attribute missing in field element");
     int index = Arrays.asList(definition.groupNames).indexOf(attr.getNodeValue());
     try {
       Pattern pattern = Pattern.compile(element.getTextContent());
       return new FieldCondition(pattern, index);
     } catch (PatternSyntaxException ex) {
       throw new RuntimeException(
           "[LogFilter] invalid regex " + element.getTextContent() + " in field element", ex);
     }
   } else if ("and".equals(name)) return new AndCondition(getChildConditions(element, definition));
   else if ("or".equals(name)) return new OrCondition(getChildConditions(element, definition));
   else if ("not".equals(name)) {
     return new NotCondition(getChildConditions(element, definition)[0]);
   } else if ("index".equals(name)) {
     return new IndexCondition(Integer.parseInt(element.getTextContent()));
   } else if ("following".equals(name)) {
     boolean includeSelf = Boolean.parseBoolean(element.getAttribute("includeSelf"));
     return new FollowingCondition(getChildConditions(element, definition)[0], includeSelf);
   } else if ("preceding".equals(name)) {
     boolean includeSelf = Boolean.parseBoolean(element.getAttribute("includeSelf"));
     return new PrecedingCondition(getChildConditions(element, definition)[0], includeSelf);
   } else throw new RuntimeException("[LogFilter] invalid element " + name);
 }
  public void enrich(EObject model, Element e) {
    String defaultNamespace = e.getAttribute("base");
    sigNodeMap = createMapping(theoryXPath, e, "name");
    viewNodeMap = createMapping(viewXPath, e, "name");
    sigObjMap = new HashMap<String, EObject>();
    viewObjMap = new HashMap<String, EObject>();

    TreeIterator<EObject> iter = model.eAllContents();
    while (iter.hasNext()) {
      EObject obj = iter.next();
      if (obj instanceof signatureDeclaration) {
        signatureDeclaration sig = (signatureDeclaration) obj;
        if (sigNodeMap.containsKey(sig.getSigName())) {
          sigObjMap.put(sig.getSigName(), obj);
          Element elem = sigNodeMap.get(sig.getSigName());
          String bs = defaultNamespace;
          if (elem.hasAttribute("base")) bs = elem.getAttribute("base");
          sig.setFullURI(bs + "?" + sig.getSigName());
          syncConstructs(sig.getDefs().getConstucts(), elem);
        }
      }
      if (obj instanceof viewDeclaration) {
        viewDeclaration view = (viewDeclaration) obj;
        if (viewNodeMap.containsKey(view.getViewID())) {
          Element elem = sigNodeMap.get(view.getViewID());
          viewObjMap.put(view.getViewID(), obj);
          String bs = defaultNamespace;
          if (elem.hasAttribute("base")) bs = elem.getAttribute("base");
          view.setFullURI(bs + "?" + view.getViewID());
          syncConstructs(view.getViewDefs().getConstucts(), elem);
        }
      }
    }
  }
 public static AbstractCanvasObject createShape(Element elt, Map<Location, Instance> pins) {
   String name = elt.getTagName();
   if (name.equals("circ-anchor") || name.equals("circ-origin")) {
     Location loc = getLocation(elt);
     AbstractCanvasObject ret = new AppearanceAnchor(loc);
     if (elt.hasAttribute("facing")) {
       Direction facing = Direction.parse(elt.getAttribute("facing"));
       ret.setValue(AppearanceAnchor.FACING, facing);
     }
     return ret;
   } else if (name.equals("circ-port")) {
     Location loc = getLocation(elt);
     String[] pinStr = elt.getAttribute("pin").split(",");
     Location pinLoc =
         Location.create(Integer.parseInt(pinStr[0].trim()), Integer.parseInt(pinStr[1].trim()));
     Instance pin = pins.get(pinLoc);
     if (pin == null) {
       return null;
     } else {
       return new AppearancePort(loc, pin);
     }
   } else {
     return SvgReader.createShape(elt);
   }
 }
Пример #9
0
 /**
  * ct.
  *
  * @param param der XML-Knoten mit den Daten.
  */
 private Param(Element param) {
   Node content = param.getFirstChild();
   this.path = content != null ? content.getNodeValue() : null;
   this.type = param.getAttribute("type");
   this.conditionName = param.getAttribute("condition-name");
   this.conditionValue = param.getAttribute("condition-value");
 }
  /** 创建指定的TypeFilter。 */
  private TypeFilter createTypeFilter(Element element, ClassLoader classLoader) {
    String filterType = defaultIfNull(trimToNull(element.getAttribute("type")), "wildcard");
    String expression =
        assertNotNull(
            trimToNull(element.getAttribute("expression")), "expression for %s" + filterType);

    try {
      if ("assignable".equals(filterType)) {
        return new AssignableTypeFilter(classLoader.loadClass(expression));
      } else if ("aspectj".equals(filterType)) {
        return new AspectJTypeFilter(expression, classLoader);
      } else if ("wildcard".equals(filterType)) {
        return new RegexPatternTypeFilter(
            ClassNameWildcardCompiler.compileClassName(
                expression, ClassNameWildcardCompiler.MATCH_PREFIX));
      } else if ("custom".equals(filterType)) {
        Class<?> filterClass = classLoader.loadClass(expression);

        assertTrue(
            TypeFilter.class.isAssignableFrom(filterClass),
            "Class is not assignable to TypeFilter: %s",
            expression);

        return (TypeFilter) BeanUtils.instantiateClass(filterClass);
      } else {
        unreachableCode("Unsupported filter type: %s", filterType);
        return null;
      }
    } catch (ClassNotFoundException e) {
      throw new FatalBeanException(
          "Failed to create TypeFilter of type " + filterType + ": " + expression, e);
    }
  }
  /**
   * Waits for an authentication response from the server. It must be called after the <code>
   * sendAuthentication</code> method call.
   *
   * @return true when the authentication hat been succesful, false othercase.
   * @throws IOException When the conection have not been initialized.
   */
  public boolean receiveAuthenticationResult() throws IOException {

    try {
      Document doc = receiveDocument();
      Element root = doc.getDocumentElement();
      if (root == null) return false;
      if (!root.getAttribute("type").equalsIgnoreCase("auth-response")) return false;
      NodeList nl = root.getChildNodes();
      Element authresult = null;
      for (int i = 0; i < nl.getLength(); i++) {
        Node n = nl.item(i);
        if (n.getNodeType() == Element.ELEMENT_NODE
            && n.getNodeName().equalsIgnoreCase("authentication")) {
          authresult = (Element) n;
          break;
        }
      }
      if (authresult != null && !authresult.getAttribute("result").equalsIgnoreCase("ok"))
        return false;
    } catch (SAXException e) {
      e.printStackTrace();
      return false;
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
      return false;
    } catch (SocketClosedException e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }
Пример #12
0
  /**
   * Gets the albums' list.
   *
   * @param element
   * @return Albums
   */
  protected GalleryAlbums getAlbums(Element element) {
    GalleryAlbums galleryAlbums = new GalleryAlbums();

    String galleryName =
        element.getElementsByTagName("galleryName").item(0).getFirstChild().getNodeValue();
    String galleryHomePage =
        element.getElementsByTagName("homePage").item(0).getFirstChild().getNodeValue();

    String[] tags = null;

    NodeList albums = element.getElementsByTagName("album");
    int albumsCount = albums.getLength();
    AlbumBean[] photoAlbums = new AlbumBean[albumsCount];

    for (int i = 0; i < albumsCount; i++) {
      Element elAlbum = (Element) albums.item(i);

      String allCategories = elAlbum.getAttribute("tags");
      tags = allCategories.split(JcsPhotoGalleryConstants.ALBUM_SEPARATOR);
      photoAlbums[i] =
          new AlbumBean(
              elAlbum.getAttribute("img"),
              elAlbum.getAttribute("folderName"),
              elAlbum.getAttribute("name"),
              tags,
              i);
      photoAlbums[i].setParent(galleryAlbums);
    }

    galleryAlbums.setGalleryName(galleryName);
    galleryAlbums.setGalleryHomePage(galleryHomePage);
    galleryAlbums.setAlbums(photoAlbums);

    return galleryAlbums;
  }
Пример #13
0
 /**
  * Constructor creates <code>SPProvidedNameIdentifier</code> object from Document Element.
  *
  * @param spProvidedNameIdentifierElement the Document Element.
  * @throws FSMsgException on errors.
  */
 public SPProvidedNameIdentifier(Element spProvidedNameIdentifierElement) throws FSMsgException {
   Element elt = (Element) spProvidedNameIdentifierElement;
   String eltName = elt.getLocalName();
   if (eltName == null) {
     if (FSUtils.debug.messageEnabled()) {
       FSUtils.debug.message("SPProvidedNameIdentifier(Element): " + "local name missing");
     }
     throw new FSMsgException("nullInput", null);
   }
   if (!(eltName.equals("SPProvidedNameIdentifier"))) {
     if (FSUtils.debug.messageEnabled()) {
       FSUtils.debug.message("SPProvidedNameIdentifier(Element: " + "invalid root element");
     }
     throw new FSMsgException("invalidElement", null);
   }
   String read = elt.getAttribute("NameQualifier");
   if (read != null) {
     setNameQualifier(read);
   }
   read = elt.getAttribute("Format");
   if (read != null) {
     setFormat(read);
   }
   read = XMLUtils.getElementValue(elt);
   if ((read == null) || (read.length() == 0)) {
     if (FSUtils.debug.messageEnabled()) {
       FSUtils.debug.message("SPProvidedNameIdentifier(Element:  " + "null input specified");
     }
     throw new FSMsgException("nullInput", null);
   } else {
     setName(read);
   }
 }
Пример #14
0
 private static AbstractCanvasObject createLine(Element elt) {
   int x0 = Integer.parseInt(elt.getAttribute("x1"));
   int y0 = Integer.parseInt(elt.getAttribute("y1"));
   int x1 = Integer.parseInt(elt.getAttribute("x2"));
   int y1 = Integer.parseInt(elt.getAttribute("y2"));
   return new Line(x0, y0, x1, y1);
 }
Пример #15
0
  /**
   * Reads a run from a DOM node representing an XML parameter file.
   *
   * @param n the DOM node to read the run from
   */
  public void readFromNode(Element e) {
    String mclass = null, expRunnerClass = null;
    mclass = e.getAttribute("model");
    expRunnerClass = e.getAttribute("expRunner");
    if (mclass == "") mclass = null;
    if (expRunnerClass == "") expRunnerClass = null;

    try {
      if (mclass != null) model = (Model) Class.forName(mclass).newInstance();
      if (expRunnerClass != null) {
        expRunner = (ExperimentRunner) Class.forName(expRunnerClass).newInstance();
      } else if (expRunner == null) {
        expRunner = createDefaultExperimentRunner();
        System.out.println(
            "** WARNING: No ExperimentRunner specified. Using desmoj.util.ExperimentRunner");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      model = null;
      expRunner = null;
    }

    Node settings = null, params = null;
    NodeList nl = e.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
      Node n = nl.item(i);
      if (n.getNodeName().equals("exp")) settings = n;
      if (n.getNodeName().equals("model")) params = n;
    }

    if (settings != null) readParamList(settings, expSettings);

    if (params != null) readParamList(params, modelParams);
  }
Пример #16
0
  public static ArrayList<ArticleData> readJArticlesFromFile(String path)
      throws ParserConfigurationException, SAXException, IOException, ParseException {
    ArrayList<ArticleData> result = new ArrayList<ArticleData>();

    File file = new File(path);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    NodeList nodeLst = doc.getElementsByTagName("art");
    for (int s = 0; s < nodeLst.getLength(); s++) {
      Node fstNode = nodeLst.item(s);
      if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
        ArticleData article = new ArticleData();
        Element fstElmnt = (Element) fstNode;
        article.acc = Integer.parseInt(fstElmnt.getAttribute("ac"));
        article.refId = Integer.parseInt(fstElmnt.getAttribute("id"));
        article.pub = Boolean.getBoolean(fstElmnt.getAttribute("published"));
        article.translationType = PMDataTypes.DITT_JARTICLE;
        article.title = StringUtils.getXMLFromElement(fstElmnt, "title");
        article.www = StringUtils.getXMLFromElement(fstElmnt, "www");
        result.add(article);
      }
    }
    return result;
  }
Пример #17
0
 private double[] retrieveFcReadings(NodeList cycleList) {
   // Check the the first cycle is cycle #1, else throw an error dialog
   Element firstCycleElement = (Element) cycleList.item(0);
   String firstCycleNumber = firstCycleElement.getAttribute("X");
   if (!firstCycleNumber.contains("1")) {
     // TODO present an error dialog and terminate import
     // ...pretty harsh but this is essential for baseline subtraction
   }
   NumberFormat numFormat =
       NumberFormat.getInstance(); // Need to convert comma decimal seperators to periods
   ArrayList<Double> fcDataSet = Lists.newArrayList();
   // Cycle through the cycles and collect the Fc readings
   for (int j = 0; j < cycleList.getLength(); j++) {
     // This assumes that the first cycle is cycle 1
     Element cycleElement = (Element) cycleList.item(j);
     try {
       // NumberFormat needed to prevent locale differences in numbers (e.g. comma vs period)
       Number value = numFormat.parse(cycleElement.getAttribute("Y"));
       fcDataSet.add(value.doubleValue());
     } catch (Exception e) {
     }
   }
   double[] fcArray = new double[fcDataSet.size()];
   for (int k = 0; k < fcDataSet.size(); k++) {
     fcArray[k] = fcDataSet.get(k);
   }
   return fcArray;
 }
Пример #18
0
  private void getAutoFieldsServiceTag(Element element, Set<String> fieldNames)
      throws GenericServiceException {
    String serviceName = UtilFormatOut.checkNull(element.getAttribute("service-name"));
    String defaultFieldType = UtilFormatOut.checkNull(element.getAttribute("default-field-type"));
    if (UtilValidate.isNotEmpty(serviceName) && (!("hidden".equals(defaultFieldType)))) {
      ModelService modelService = dispatchContext.getModelService(serviceName);
      List<ModelParam> modelParams = modelService.getInModelParamList();
      Iterator<ModelParam> modelParamIter = modelParams.iterator();
      while (modelParamIter.hasNext()) {
        ModelParam modelParam = modelParamIter.next();
        // skip auto params that the service engine populates...
        if ("userLogin".equals(modelParam.name)
            || "locale".equals(modelParam.name)
            || "timeZone".equals(modelParam.name)) {
          continue;
        }
        if (modelParam.formDisplay) {
          if (UtilValidate.isNotEmpty(modelParam.entityName)
              && UtilValidate.isNotEmpty(modelParam.fieldName)) {
            ModelEntity modelEntity;
            modelEntity = delegator.getModelEntity(modelParam.entityName);

            if (modelEntity != null) {
              ModelField modelField = modelEntity.getField(modelParam.fieldName);

              if (modelField != null) {
                fieldNames.add(modelField.getName());
              }
            }
          }
        }
      }
    }
  }
Пример #19
0
  public IHETransactionITI44(Element el, Registration reg, Configuration cfg) {
    try {
      regx = new RegistrationXml(el, reg, cfg);
      transformer = IHETransactionTransformerFactory.getITI44Transformer();
    } catch (Exception e) {
      throw new IllegalArgumentException("Error creating ITI44 Transaction.", e);
    }

    this.reg = reg;
    this.cfg = cfg;
    wrapper = null;
    saveMessages = false;

    soapVersion = el.getAttribute("soapVersion").trim();
    if (soapVersion == null || soapVersion.equals("")) {
      soapVersion = "SOAP_1_2";
    }

    hl7URL = el.getAttribute("hl7URL").trim();
    if (hl7URL == null || hl7URL.equals("")) {
      throw new IllegalArgumentException("Missing hl7URL attribute.");
    }
    receivingApplication = el.getAttribute("receivingApplication").trim();
    receivingFacility = el.getAttribute("receivingFacility").trim();
  }
Пример #20
0
  // private?
  public static Set<AimQuantification> parseQuantifications(
      Element rootElement,
      AimImagingObservationCharacteristic aimImagingObservationCharacteristic) {

    System.out.println(
        "aimImagingObservationCharacteristic:" + aimImagingObservationCharacteristic);

    Set<AimQuantification> results = new HashSet<AimQuantification>();

    // ns1:ImagingObservationCharacteristic
    NodeList imagingQuantifications =
        rootElement.getElementsByTagNameNS(AIM_NS, "CharacteristicQuantification");

    for (int i = 0; i < imagingQuantifications.getLength(); i++) {
      Element imagingQuantification = (Element) imagingQuantifications.item(i);

      String name = imagingQuantification.getAttribute("name");
      String value = imagingQuantification.getAttribute("value");
      String type = imagingQuantification.getAttributeNS(XSI_NS, "type");

      AimQuantification aimQuantification = new AimQuantification();
      aimQuantification.setName(name);
      aimQuantification.setValue(value);
      aimQuantification.setType(filterNameSpace(type));
      aimQuantification.setAimImagingObservationCharacteristic(aimImagingObservationCharacteristic);

      results.add(aimQuantification);
    }
    return results;
  }
Пример #21
0
  private ExternalActor createExternalActor(Element element) {
    ExternalActor actor = IrFactory.eINSTANCE.createExternalActor();
    String id = element.getAttribute("id");
    doAnnotations(actor, element);

    addIrObject(id, actor);

    actor.setType((TypeActor) createType(getChild(element, "Type")));

    List<Element> declarations = getChildren(element, "Decl");
    for (Element e : declarations) {
      Variable var = (Variable) createDeclaration(e);
      actor.getDeclarations().add(var);
      if (var.isParameter()) actor.getParameters().add(var);
    }

    List<Element> ports = getChildren(element, "Port");
    for (Element e : ports) {
      Port port = createPort(e);
      if (element.getAttribute("direction").equals("in")) {
        actor.getInputPorts().add(port);
      } else {
        actor.getOutputPorts().add(port);
      }
    }

    return actor;
  }
Пример #22
0
  private static void loadFromStream(InputSource inputSource, Map<IPath, String> oldLocations)
      throws CoreException {
    Element cpElement;
    try {
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      parser.setErrorHandler(new DefaultHandler());
      cpElement = parser.parse(inputSource).getDocumentElement();
    } catch (SAXException e) {
      throw createException(e, CorextMessages.JavaDocLocations_error_readXML);
    } catch (ParserConfigurationException e) {
      throw createException(e, CorextMessages.JavaDocLocations_error_readXML);
    } catch (IOException e) {
      throw createException(e, CorextMessages.JavaDocLocations_error_readXML);
    }

    if (cpElement == null) return;
    if (!cpElement.getNodeName().equalsIgnoreCase(NODE_ROOT)) {
      return;
    }
    NodeList list = cpElement.getChildNodes();
    int length = list.getLength();
    for (int i = 0; i < length; ++i) {
      Node node = list.item(i);
      short type = node.getNodeType();
      if (type == Node.ELEMENT_NODE) {
        Element element = (Element) node;
        if (element.getNodeName().equalsIgnoreCase(NODE_ENTRY)) {
          String varPath = element.getAttribute(NODE_PATH);
          String varURL = parseURL(element.getAttribute(NODE_URL)).toExternalForm();

          oldLocations.put(Path.fromPortableString(varPath), varURL);
        }
      }
    }
  }
Пример #23
0
  private VariableReference createVariableReference(Element element) {
    VariableReference varRef = IrFactory.eINSTANCE.createVariableReference();
    varRef.setId(element.getAttribute("id"));
    doAnnotations(varRef, element);
    Element child = getChild(element, "Type");
    if (child != null) {
      varRef.setType(createType(child));
    }
    varRef.setDeclaration((Variable) findIrObject(element.getAttribute("decl-id")));

    Element indices = getChild(element, "Indices");
    if (indices != null) {
      for (Element index : getChildren(indices, "Expr")) {
        varRef.getIndex().add(createExpression(index));
      }
    }

    Element members = getChild(element, "Members");
    if (members != null) {
      for (Element member : getChildren(members, "Member")) {
        varRef.getMember().add(createMember(member));
      }
    }

    return varRef;
  }
Пример #24
0
  private void emitMenu(SourceWriter writer, Element el) throws UnableToCompleteException {
    for (Node n = el.getFirstChild(); n != null; n = n.getNextSibling()) {
      if (n.getNodeType() != Node.ELEMENT_NODE) continue;

      Element child = (Element) n;

      if (child.getTagName().equals("cmd")) {
        String cmdId = child.getAttribute("refid");
        writer.print("callback.addCommand(");
        writer.print("\"" + Generator.escape(cmdId) + "\", ");
        writer.println("this.cmds." + cmdId + "());");
      } else if (child.getTagName().equals("separator")) {
        writer.println("callback.addSeparator();");
      } else if (child.getTagName().equals("menu")) {
        String label = child.getAttribute("label");
        writer.println("callback.beginMenu(\"" + Generator.escape(label) + "\");");
        emitMenu(writer, child);
        writer.println("callback.endMenu();");
      } else if (child.getTagName().equals("dynamic")) {
        String dynamicClass = child.getAttribute("class");
        writer.println("new " + dynamicClass + "().execute(callback);");
      } else {
        logger_.log(TreeLogger.Type.ERROR, "Unexpected tag " + el.getTagName() + " in menu");
        throw new UnableToCompleteException();
      }
    }
  }
Пример #25
0
  private String getSAMLVersion(HttpServletRequest request) {
    String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY);
    String version;

    try {
      Document samlDocument =
          toSAMLResponseDocument(samlResponse, "POST".equalsIgnoreCase(request.getMethod()));
      Element element = samlDocument.getDocumentElement();

      // let's try SAML 2.0 Version attribute first
      version = element.getAttribute("Version");

      if (isNullOrEmpty(version)) {
        // fallback to SAML 1.1 Minor and Major attributes
        String minorVersion = element.getAttribute("MinorVersion");
        String majorVersion = element.getAttribute("MajorVersion");

        version = minorVersion + "." + majorVersion;
      }
    } catch (Exception e) {
      throw new RuntimeException("Could not extract version from SAML Response.", e);
    }

    return version;
  }
Пример #26
0
  @Override
  public boolean hasAttribute(Entity entity, String attribute)
      throws EntityNotFoundException, SchemeException {

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
      dBuilder = dbFactory.newDocumentBuilder();
      Document doc;
      doc = dBuilder.parse(getURL().openStream());
      NodeList nodes = doc.getElementsByTagName("xs:element");
      for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        if (element.getAttribute("name").equals(entity.getName())) {
          NodeList childNodes = element.getElementsByTagName("xs:attribute");
          for (int j = 0; j < childNodes.getLength(); j++) {
            element = (Element) childNodes.item(j);
            if (element.getAttribute("name").equals(attribute)) {
              return true;
            }
          }
        }
      }
    } catch (Exception e) {
      throw new SchemeException(e);
    }

    throw new EntityNotFoundException(entity.getName());
  }
Пример #27
0
  private void loadDecoratorMappers(NodeList nodes) {
    clearDecoratorMappers();
    Properties emptyProps = new Properties();

    pushDecoratorMapper("com.opensymphony.module.sitemesh.mapper.NullDecoratorMapper", emptyProps);

    // note, this works from the bottom node up.
    for (int i = nodes.getLength() - 1; i > 0; i--) {
      if (nodes.item(i) instanceof Element) {
        Element curr = (Element) nodes.item(i);
        if ("mapper".equalsIgnoreCase(curr.getTagName())) {
          String className = curr.getAttribute("class");
          Properties props = new Properties();
          // build properties from <param> tags.
          NodeList children = curr.getChildNodes();
          for (int j = 0; j < children.getLength(); j++) {
            if (children.item(j) instanceof Element) {
              Element currC = (Element) children.item(j);
              if ("param".equalsIgnoreCase(currC.getTagName())) {
                String value = currC.getAttribute("value");
                props.put(currC.getAttribute("name"), replaceProperties(value));
              }
            }
          }
          // add mapper
          pushDecoratorMapper(className, props);
        }
      }
    }

    pushDecoratorMapper(
        "com.opensymphony.module.sitemesh.mapper.InlineDecoratorMapper", emptyProps);
  }
Пример #28
0
  @Override
  public void loadFromSnapshot(Document doc, Element node) {
    NodeList nl = node.getElementsByTagName("player");
    for (int i = 0; i < nl.getLength(); i++) {
      Element playerEl = (Element) nl.item(i);
      Player player = game.getPlayer(Integer.parseInt(playerEl.getAttribute("index")));
      castles.put(player, Integer.parseInt(playerEl.getAttribute("castles")));
    }

    nl = node.getElementsByTagName("castle");
    for (int i = 0; i < nl.getLength(); i++) {
      Element castleEl = (Element) nl.item(i);
      Position pos = XMLUtils.extractPosition(castleEl);
      Location loc = Location.valueOf(castleEl.getAttribute("location"));
      Castle castle = convertCityToCastle(pos, loc, true);
      boolean isNew = XMLUtils.attributeBoolValue(castleEl, "new");
      boolean isCompleted = XMLUtils.attributeBoolValue(castleEl, "completed");
      if (isNew) {
        newCastles.add(castle);
      } else if (isCompleted) {
        emptyCastles.add(castle);
      } else {
        scoreableCastleVicinity.put(castle, castle.getVicinity());
      }
    }
  }
Пример #29
0
  public ArrayList<Entity> getEntitiesFromFile(String filePath) {
    ArrayList<Entity> entities = new ArrayList<>();
    try {
      d = db.parse(filePath);

      NodeList entityMentions = d.getElementsByTagName("entity_mention");
      for (int i = 0; i < entityMentions.getLength(); i++) {
        Element entityMention = (Element) entityMentions.item(i);
        NodeList heads = entityMention.getElementsByTagName("head");
        Element head = (Element) heads.item(0);
        NodeList charseqs = head.getElementsByTagName("charseq");
        Element charseq = (Element) charseqs.item(0);
        int start = Integer.parseInt(charseq.getAttribute("START"));
        int end = Integer.parseInt(charseq.getAttribute("END"));
        String value = charseq.getFirstChild().getNodeValue();
        // value = value.replaceAll("\n", "");
        String id = entityMention.getAttribute("ID");
        Element entityParent = (Element) entityMention.getParentNode();
        String type = entityParent.getAttribute("TYPE");
        // String subType = entityParent.getAttribute("SUBTYPE");
        Entity entity = new Entity(value, start, end, type, id);
        entities.add(entity);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return entities;
  }
Пример #30
0
  private ArrayList processConsequents(Element rule) {
    NodeList antecedents = rule.getElementsByTagName("consequents");
    ArrayList<String> itemset = new ArrayList();

    if (antecedents != null && antecedents.getLength() > 0) {
      Element antecedent = (Element) antecedents.item(0);

      // Get attributes (items)
      NodeList attributes = antecedent.getElementsByTagName("attribute");
      if (attributes != null && attributes.getLength() > 0) {
        for (int i = 0; i < attributes.getLength(); i++) {
          Element attr = (Element) attributes.item(i);

          String itemId =
              attr.getAttribute("name") + itemNameValueSeparator + attr.getAttribute("value");
          if (!items.containsKey(itemId)) {
            items.put(itemId, itemCounter);
            itemCounter++;
          }
          // Save item to generate itemsets after..
          itemset.add(itemId);
        }
      }
    }

    return itemset;
  }