private void load() {
    try {
      File f = new File("./data/xml/admin_commands_rights.xml");
      Document doc = XMLDocumentFactory.getInstance().loadDocument(f);

      Node n = doc.getFirstChild();
      for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
        if (d.getNodeName().equalsIgnoreCase("aCar")) {
          NamedNodeMap attrs = d.getAttributes();

          String adminCommand = attrs.getNamedItem("name").getNodeValue();
          String accessLevels = attrs.getNamedItem("accessLevel").getNodeValue();
          _adminCommandAccessRights.put(
              adminCommand, new L2AdminCommandAccessRight(adminCommand, accessLevels));
        }
      }
    } catch (Exception e) {
      _log.log(
          Level.WARNING,
          "AdminCommandAccessRights: Error loading from database:" + e.getMessage(),
          e);
    }

    _log.info(
        "AdminCommandAccessRights: Loaded "
            + _adminCommandAccessRights.size()
            + " commands accesses' rights.");
  }
Пример #2
0
  private void loadInfo() {
    try {
      Document doc;

      doc = AppUtils.downloadXML(new URL(Repo.VERSION_XML));
      if (doc == null) {
        return;
      }
      NamedNodeMap updateAttributes = doc.getDocumentElement().getAttributes();
      latest = Integer.parseInt(updateAttributes.getNamedItem("currentBuild").getTextContent());
      char[] temp = String.valueOf(latest).toCharArray();
      for (int i = 0; i < (temp.length - 1); i++) {
        verString += temp[i] + ".";
      }
      verString += temp[temp.length - 1];
      String downloadAddress = updateAttributes.getNamedItem("downloadURL").getTextContent();
      if (downloadAddress.indexOf("http") != 0) {
        downloadAddress = LaunchFrame.getFullLink(downloadAddress);
      }
      downloadUrl = new URL(downloadAddress);
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    } catch (SAXException e) {
    } catch (NoSuchAlgorithmException e) {
    }
  }
  /**
   * Reads XML that contains the specifications of a given device.
   *
   * @return {@link LayoutDevicesType} representing the device read.
   * @throws ParserConfigurationException
   * @throws SAXException
   * @throws IOException
   */
  public LayoutDevicesType read() throws ParserConfigurationException, SAXException, IOException {
    LayoutDevicesType layoutDevicesType = ObjectFactory.getInstance().createLayoutDevicesType();

    NodeList deviceList = document.getElementsByTagName(D_DEVICE);
    for (int i = 0; i < deviceList.getLength(); i++) {
      Node deviceNode = deviceList.item(i);
      NamedNodeMap deviceNodeAttrs = deviceNode.getAttributes();

      Node deviceIdAtr = deviceNodeAttrs.getNamedItem("id");
      if ((deviceIdAtr != null) && !deviceIdAtr.getNodeValue().trim().equals("")) // $NON-NLS-1$
      {
        // add device
        Device dev = new Device();
        dev.setId(deviceIdAtr.getNodeValue());

        dev.setName(extractValueFromAttributes(deviceNodeAttrs, "name"));
        dev.setProvider(extractValueFromAttributes(deviceNodeAttrs, "provider"));

        NodeList defaultOrConfigList = deviceNode.getChildNodes();
        for (int j = 0; j < defaultOrConfigList.getLength(); j++) {
          Node defaultOrConfigNode = defaultOrConfigList.item(j);
          if ((defaultOrConfigNode != null)
              && (defaultOrConfigNode.getNodeType() == Node.ELEMENT_NODE)) {
            if (defaultOrConfigNode.getNodeName().equalsIgnoreCase(D_SUPPORTED_FEATURES)) {
              NodeList paramsList = defaultOrConfigNode.getChildNodes();
              for (int z = 0; z < paramsList.getLength(); z++) {
                Node supportedFeatureNode = paramsList.item(z);
                if ((supportedFeatureNode != null)
                    && (supportedFeatureNode.getNodeType() == Node.ELEMENT_NODE)) {
                  Node valueNode = supportedFeatureNode.getFirstChild();
                  String supportedFeatureValue = valueNode.getNodeValue();
                  if ((supportedFeatureValue != null) && !supportedFeatureValue.equals("")) {
                    dev.getSupportedFeatures().add(new Feature(supportedFeatureValue));
                  }
                }
              }
            } else {
              boolean isDefault = defaultOrConfigNode.getNodeName().equalsIgnoreCase(D_DEFAULT);
              ParametersType paramTypes = extractParamTypes(defaultOrConfigNode, isDefault);
              if (!(paramTypes instanceof ConfigType)) {
                // default
                dev.setDefault(paramTypes);
              } else {
                // config
                NamedNodeMap configAttrs = defaultOrConfigNode.getAttributes();
                Node configAtr = configAttrs.getNamedItem("name");
                if ((configAtr != null) && !configAtr.getNodeValue().trim().equals("")) {
                  ConfigType type = (ConfigType) paramTypes;
                  type.setName(configAtr.getNodeValue());
                  dev.addConfig(type);
                }
              }
            }
          }
        }
        layoutDevicesType.getDevices().add(dev);
      }
    }
    return layoutDevicesType;
  }
  private void addRunConfigurationFromXMLTree(Element treeTop, String runManagerName) {
    NodeList list = treeTop.getChildNodes();

    for (int i = 0; i < list.getLength(); i++) {
      NamedNodeMap nodeMap = list.item(i).getAttributes();
      if (nodeMap != null && nodeMap.getNamedItem("name") != null) {
        if (!runManagerName.equals(nodeMap.getNamedItem("name").getNodeValue())) {
          continue;
        }
        NodeList configList = list.item(i).getChildNodes();
        for (int j = 0; j < configList.getLength(); j++) {
          NamedNodeMap configNodeMap = configList.item(j).getAttributes();
          if (configNodeMap != null
              && configNodeMap.getNamedItem("default") != null
              && configNodeMap.getNamedItem("default").getNodeValue() != null
              && configNodeMap.getNamedItem("default").getNodeValue().equals("false")) {
            try {
              runConfigurations.add(new ASIdeaRunConfiguration(configList.item(j)));
            } catch (ASExternalImporterException e) {
              // Ignore
            }
          }
        }
      }
    }
  }
  private void DisplayUserSelect() {

    if (UserAcountModel.getInstance().getDocument() == null) return;

    NodeList nodeList = UserAcountModel.getInstance().getDocument().getElementsByTagName("user");
    userSelect = new Button[nodeList.getLength()];
    for (int i = 0; i < nodeList.getLength(); i++) {
      Node node = nodeList.item(i);
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        NamedNodeMap attributes = node.getAttributes();

        Button select = new Button(this);
        TextView text = new TextView(this);
        select.setTag(attributes.getNamedItem("id").getTextContent());
        text.setText(
            attributes.getNamedItem("firstname").getTextContent()
                + " "
                + attributes.getNamedItem("lastname").getTextContent()
                + ": "
                + attributes.getNamedItem("username").getTextContent());
        select.setText(attributes.getNamedItem("id").getTextContent());
        userSelect[i] = select;
        LinearLayout llSelectUser = (LinearLayout) findViewById(R.id.llSelectUsers);
        llSelectUser.addView(text);
        llSelectUser.addView(userSelect[i]);
        userSelect[i].setOnClickListener(handleOnClick(userSelect[i]));
      }
    }
  }
Пример #6
0
 static {
   try {
     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
     Document document = dbBuilder.parse(PROPERTIES_FILE_PATH);
     Node root = document.getFirstChild();
     if (root != null && "properties".equals(root.getNodeName())) {
       NodeList childNodes = root.getChildNodes();
       for (int i = 0; i < childNodes.getLength(); i++) {
         Node node = childNodes.item(i);
         if ("property".equals(node.getNodeName())) {
           NamedNodeMap attributes = node.getAttributes();
           Node keyNode = attributes.getNamedItem("key");
           Node valueNode = attributes.getNamedItem("value");
           if (keyNode != null && valueNode != null) {
             String key = keyNode.getNodeValue();
             String value = valueNode.getNodeValue();
             if (key != null && !key.isEmpty() && value != null && !value.isEmpty()) {
               PROPERTIES_FILE.put(key, value);
             }
           }
         }
       }
     }
   } catch (ParserConfigurationException | SAXException | IOException ex) {
   }
 }
Пример #7
0
  public void createOrUpdateProject(NamedNodeMap nodeMap, ProjectDAO dao) {
    Project project = new Project(); // проект из БД

    // поля синхронизации
    String name = nodeMap.getNamedItem("name").getNodeValue().trim(); // название проекта
    String idProject = nodeMap.getNamedItem("id").getNodeValue(); // id проекта
    String status = nodeMap.getNamedItem("status").getNodeValue(); // статус проекта
    String pmLdap = nodeMap.getNamedItem("pm").getNodeValue(); // руководитель проекта
    String hcLdap = nodeMap.getNamedItem("hc").getNodeValue(); // hc

    // ищем в БД запись о проекте
    Project findingProject = dao.findByProjectId(idProject);
    if (findingProject == null) { // если проекта еще нет в БД
      project.setActive(newStatus.contains(status)); // установим ему новый статус
    } else {
      // если проект уже существовал - статус менять не будем
      // см. //APLANATS-408
      project.setActive(findingProject.isActive());
    }

    project.setName(name);
    project.setProjectId(idProject);

    if (project.isActive()) {
      if (!setPM(project, pmLdap)) {
        return; // если не указан РП или его нет в БД, то проект не сохраняем, переходим к
                // следующему
      }
      setDivision(project, hcLdap); // установим подразделение пользователя
    }
    dao.store(project); // запишем в БД
  }
Пример #8
0
 /**
  * Description: Extracts the Minor Fonts names with their script name and typeface then save the
  * extracted Minor Fonts in hash Map with their scripts names as key
  *
  * <p>
  *
  * @param its input will be Minor Font node + its children from theme.xml
  * @param its output contains hash map having schema Minor Fonts
  */
 public void loadPPTXMinorFonts(NodeList minorFontChildren) {
   for (int index = 0; index < minorFontChildren.getLength(); index++) {
     Node child = minorFontChildren.item(index);
     String nodeName = child.getNodeName();
     NamedNodeMap childAttributes = child.getAttributes();
     if (childAttributes != null) {
       if (nodeName.equalsIgnoreCase(PPTXConstants.PPTX_FONT_LATIN)) {
         pptxMinorFonts.put(
             PPTXConstants.PPTX_FONT_LATIN.substring(2),
             childAttributes.getNamedItem("typeface").getNodeValue());
       } else if (nodeName.equalsIgnoreCase(PPTXConstants.PPTX_FONT_EASTASSIAN)) {
         pptxMinorFonts.put(
             PPTXConstants.PPTX_FONT_EASTASSIAN.substring(2),
             childAttributes.getNamedItem("typeface").getNodeValue());
       } else if (nodeName.equalsIgnoreCase(PPTXConstants.PPTX_FONT_COMPLEXSCRIPT)) {
         pptxMinorFonts.put(
             PPTXConstants.PPTX_FONT_COMPLEXSCRIPT.substring(2),
             childAttributes.getNamedItem("typeface").getNodeValue());
       } else if (nodeName.equalsIgnoreCase(PPTXConstants.PPTX_FONT)) {
         pptxMinorFonts.put(
             childAttributes.getNamedItem("script").getNodeValue(),
             childAttributes.getNamedItem("typeface").getNodeValue());
       }
     }
   }
 }
Пример #9
0
  public static List<Location> getPoints(File gpxFile) throws Exception {
    List<Location> points;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    FileInputStream fis = new FileInputStream(gpxFile);
    Document dom = builder.parse(fis);
    Element root = dom.getDocumentElement();
    NodeList items = root.getElementsByTagName("trkpt");

    points = new ArrayList<Location>();

    for (int j = 0; j < items.getLength(); j++) {
      Node item = items.item(j);
      NamedNodeMap attrs = item.getAttributes();
      NodeList props = item.getChildNodes();

      Location pt = new Location("test");

      pt.setLatitude(Double.parseDouble(attrs.getNamedItem("lat").getNodeValue()));
      pt.setLongitude(Double.parseDouble(attrs.getNamedItem("lon").getNodeValue()));

      for (int k = 0; k < props.getLength(); k++) {
        Node item2 = props.item(k);
        String name = item2.getNodeName();

        if (name.equalsIgnoreCase("ele")) {
          pt.setAltitude(Double.parseDouble(item2.getFirstChild().getNodeValue()));
        }
        if (name.equalsIgnoreCase("course")) {
          pt.setBearing(Float.parseFloat(item2.getFirstChild().getNodeValue()));
        }
        if (name.equalsIgnoreCase("speed")) {
          pt.setSpeed(Float.parseFloat(item2.getFirstChild().getNodeValue()));
        }
        if (name.equalsIgnoreCase("hdop")) {
          pt.setAccuracy(Float.parseFloat(item2.getFirstChild().getNodeValue()) * 5);
        }
        if (name.equalsIgnoreCase("time")) {
          pt.setTime((getDateFormatter().parse(item2.getFirstChild().getNodeValue())).getTime());
        }
      }

      for (int y = 0; y < props.getLength(); y++) {
        Node item3 = props.item(y);
        String name = item3.getNodeName();
        if (!name.equalsIgnoreCase("ele")) {
          continue;
        }
        pt.setAltitude(Double.parseDouble(item3.getFirstChild().getNodeValue()));
      }

      points.add(pt);
    }

    fis.close();

    return points;
  }
Пример #10
0
  /**
   * Parses the given XML document into a lookup table of services.
   *
   * @param doc XML document
   * @return a map of service names to service objects
   */
  public static Map<String, Service> parseXML(Document doc) {
    Map<String, Service> services = new HashMap<String, Service>();

    Element root = doc.getDocumentElement();
    for (Node child = root.getFirstChild(); child != null; child = child.getNextSibling()) {
      if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals("service")) {
        try {
          NamedNodeMap attributes = child.getAttributes();
          String name = attributes.getNamedItem("name").getNodeValue();
          String format = attributes.getNamedItem("format").getNodeValue();
          String desc = attributes.getNamedItem("description").getNodeValue();

          services.put(name, new Service(name, format, desc));

        } catch (NullPointerException e) {
          LOG.log(Level.WARNING, "Malformed XML attribute. Skipping.");
          continue;
        }
      } else {
        LOG.log(Level.WARNING, "Malformed XML received. Skipping.");
        continue;
      }
    }

    return services;
  }
Пример #11
0
  /**
   * @return a <code>Map</code> of of textual values keyed off the values of any lang or xml:lang
   *     attributes specified on an attribute. If no such attribute exists, then the key {@link
   *     ApplicationResourceBundle#DEFAULT_KEY} will be used (i.e. this represents the default
   *     Locale).
   * @param list a list of nodes representing textual elements such as description or display-name
   */
  protected Map<String, String> getTextMap(List<Node> list) {

    if (list != null && !list.isEmpty()) {
      int len = list.size();
      HashMap<String, String> names = new HashMap<String, String>(len, 1.0f);
      for (int i = 0; i < len; i++) {
        Node node = list.get(i);
        String textValue = getNodeText(node);
        if (textValue != null) {
          if (node.hasAttributes()) {
            NamedNodeMap attributes = node.getAttributes();
            String lang = getNodeText(attributes.getNamedItem("lang"));
            if (lang == null) {
              lang = getNodeText(attributes.getNamedItem("xml:lang"));
            }
            if (lang != null) {
              names.put(lang, textValue);
            } else {
              names.put(ApplicationResourceBundle.DEFAULT_KEY, textValue);
            }
          } else {
            names.put(ApplicationResourceBundle.DEFAULT_KEY, textValue);
          }
        }
      }

      return names;
    }

    return null;
  }
Пример #12
0
  private void getConnectionProperties(final Node node) {
    final NodeList childNodes = node.getChildNodes();

    for (int i = 0; i < childNodes.getLength(); ++i) {
      final Node childNode = childNodes.item(i);

      if (childNode.getNodeType() == Node.ELEMENT_NODE) {
        final String nodeName = childNode.getNodeName();
        if (nodeName.equals("property")) {
          final NamedNodeMap attributes = childNode.getAttributes();

          Node n = attributes.getNamedItem("name");
          ThreadContext.assertError(
              n != null,
              "DbAnalyse-options/connection-properties/property must contain a 'name' attribute");
          final String name = n.getNodeValue();

          n = attributes.getNamedItem("value");
          ThreadContext.assertError(
              n != null,
              "DbAnalyse-options/connection-properties/property must contain a 'value' attribute");
          final String value = n.getNodeValue();

          m_options.m_connectionProperties.add(E2.of(name, value));
        } else {
          ThreadContext.assertError(
              false, "[%s] unknown option element [%s]", getClass().getSimpleName(), nodeName);
        }
      }
    }
  }
Пример #13
0
  TableMeta(Node tableNode) {
    NamedNodeMap attribs = tableNode.getAttributes();

    name = attribs.getNamedItem("name").getNodeValue();

    Node commentNode = attribs.getNamedItem("comments");
    if (commentNode != null) {
      String tmp = commentNode.getNodeValue().trim();
      comments = tmp.length() == 0 ? null : tmp;
    } else {
      comments = null;
    }

    Node remoteSchemaNode = attribs.getNamedItem("remoteSchema");
    if (remoteSchemaNode != null) {
      remoteSchema = remoteSchemaNode.getNodeValue().trim();
    } else {
      remoteSchema = null;
    }

    logger.fine(
        "Found XML table metadata for "
            + name
            + " remoteSchema: "
            + remoteSchema
            + " comments: "
            + comments);

    NodeList columnNodes = ((Element) tableNode.getChildNodes()).getElementsByTagName("column");

    for (int i = 0; i < columnNodes.getLength(); ++i) {
      Node colNode = columnNodes.item(i);
      columns.add(new TableColumnMeta(colNode));
    }
  }
Пример #14
0
  private Area loadScreenArea(String pngFile) throws Exception {
    Area area = null;
    String xmlArea = "./workspace/" + file.substring(0, file.indexOf("/")) + "/screen_area.xml";
    System.out.println(xmlArea);
    XmlUtil xmlUtil = new XmlUtil(xmlArea);
    Document doc = xmlUtil.parse(xmlArea);
    Element root = doc.getDocumentElement();

    NodeList childs = root.getChildNodes();
    if (childs != null) {
      for (int i = 0; i < childs.getLength(); i++) {
        Node node = childs.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
          NamedNodeMap map = node.getAttributes();
          String fileName = map.getNamedItem("file").getNodeValue();
          if (fileName.equals(pngFile)) {
            area = new Area();
            area.setFile(fileName);
            area.setX(Integer.parseInt(map.getNamedItem("x").getNodeValue()));
            area.setY(Integer.parseInt(map.getNamedItem("y").getNodeValue()));
            area.setWidth(Integer.parseInt(map.getNamedItem("width").getNodeValue()));
            area.setHeight(Integer.parseInt(map.getNamedItem("height").getNodeValue()));
          }
        }
      }
    }
    return area;
  }
  @Override
  protected void addTagInsertionProposals(
      ContentAssistRequest contentAssistRequest,
      int childPosition,
      CompletionProposalInvocationContext context) {
    int offset = contentAssistRequest.getReplacementBeginPosition();
    int length = contentAssistRequest.getReplacementLength();
    Node node = contentAssistRequest.getNode();
    // Current node can be 'parent' when the cursor is just before the end tag of the parent.
    Node parentNode = node.getNodeType() == Node.ELEMENT_NODE ? node : node.getParentNode();
    if (parentNode.getNodeType() != Node.ELEMENT_NODE) return;

    String tagName = parentNode.getNodeName();
    NamedNodeMap tagAttrs = parentNode.getAttributes();
    // Result mapping proposals.
    if ("resultMap".equals(tagName))
      generateResults(
          contentAssistRequest, offset, length, parentNode, tagAttrs.getNamedItem("type"));
    else if ("collection".equals(tagName))
      generateResults(
          contentAssistRequest, offset, length, parentNode, tagAttrs.getNamedItem("ofType"));
    else if ("association".equals(tagName))
      generateResults(
          contentAssistRequest, offset, length, parentNode, tagAttrs.getNamedItem("javaType"));

    Node statementNode = MybatipseXmlUtil.findEnclosingStatementNode(parentNode);
    if (statementNode == null) return;
    proposeStatementText(contentAssistRequest, statementNode);
  }
 /** get all the categories of all tv programs */
 public static ArrayList<OnlineVideo> getAllCategory(final Context context) {
   ArrayList<OnlineVideo> result = new ArrayList<OnlineVideo>();
   DocumentBuilderFactory docBuilderFactory = null;
   DocumentBuilder docBuilder = null;
   Document doc = null;
   try {
     docBuilderFactory = DocumentBuilderFactory.newInstance();
     docBuilder = docBuilderFactory.newDocumentBuilder();
     // xml file is set in 'assets' folder
     doc = docBuilder.parse(context.getResources().getAssets().open("online.xml"));
     // root element
     Element root = doc.getDocumentElement();
     NodeList nodeList = root.getElementsByTagName("category");
     for (int i = 0; i < nodeList.getLength(); i++) {
       Node node = nodeList.item(i); // category
       OnlineVideo ov = new OnlineVideo();
       NamedNodeMap attr = node.getAttributes();
       ov.title = attr.getNamedItem("name").getNodeValue();
       ov.id = attr.getNamedItem("id").getNodeValue();
       ov.category = 1;
       ov.level = 2;
       ov.is_category = true;
       result.add(ov);
       // Read Node
     }
   } catch (IOException e) {
   } catch (SAXException e) {
   } catch (ParserConfigurationException e) {
   } finally {
     doc = null;
     docBuilder = null;
     docBuilderFactory = null;
   }
   return result;
 }
Пример #17
0
  private LinkedList<Neighbor> loadNeighbors(String xmlFile) throws ParserConfigurationException {
    LinkedList<Neighbor> ns = new LinkedList<Neighbor>();
    try {
      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(new File(xmlFile));
      doc.getDocumentElement().normalize();
      NodeList neighborsList = doc.getElementsByTagName("neighbor");
      for (int i = 0; i < neighborsList.getLength(); i++) {
        Neighbor n = new Neighbor();
        NamedNodeMap atributes = neighborsList.item(i).getAttributes();
        n.setIp(InetAddress.getByName(atributes.getNamedItem("ip").getNodeValue()));
        n.setNumberOfOcupiedSlots(0);
        n.setNumberOfSlots(
            Integer.parseInt(atributes.getNamedItem("availableSlots").getNodeValue()));
        n.setPort(Integer.parseInt(atributes.getNamedItem("listenPort").getNodeValue()));
        ns.add(n);
      }

    } catch (SAXException ex) {
      Logger.getLogger(Neighborhood.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(Neighborhood.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ns;
  }
Пример #18
0
  private void getProperties(NamedNodeMap attributes) throws MessageException {
    if (attributes.getNamedItem("name") != null) {
      setName(attributes.getNamedItem("name").getNodeValue());
    }

    String identifier = xmlNode.getChildStringValue("identifier");
    setIdentifier(identifier);
    String identifierType = xmlNode.getChildStringValue("identifierType");
    setIdentifierType(identifierType);

    String type = xmlNode.getChildStringValue("type");
    setType(type);
    String text = xmlNode.getChildStringValue("text");
    setText(text);
    String interaction = xmlNode.getChildStringValue("interaction");
    setInteraction(interaction);
    String value = xmlNode.getChildStringValue("value");
    setValue(value);
    Integer timeout = xmlNode.getChildIntegerValue("timeout");
    setTimeout(timeout);
    String selectBy = xmlNode.getChildStringValue("selectBy");
    if (!selectBy.equals("")) {
      setSelectBy(selectBy);
    }
  }
Пример #19
0
  /**
   * Recursively loads the sounds within a given list of nodes representing sound resources. Adds
   * user-defined gestures to the control panel if this program is not being run from the command
   * line.
   *
   * @param soundNodes a NodeList representing SoundResources to be loaded.
   * @return a list of Sounds that make up the gesture.
   */
  private List<SoundResource> getSoundResources(NodeList soundNodes) {

    List<SoundResource> soundResources = new ArrayList<SoundResource>();

    for (int i = 0; i < soundNodes.getLength(); i++) {
      Node soundNode = soundNodes.item(i);

      // ignore all nodes that are not element nodes
      if (soundNode.getNodeType() != Node.ELEMENT_NODE) continue;

      // get the attributes of the sound resource
      NamedNodeMap soundAttr = soundNode.getAttributes();

      // get the delay and track of this sound
      int delay = Integer.parseInt(soundAttr.getNamedItem("delay").getNodeValue());
      int track = Integer.parseInt(soundAttr.getNamedItem("track").getNodeValue());

      // create or reuse the sound resource
      SoundResource resource;
      if (soundNode.getNodeName().equals("gesture")) {

        String gestureName = soundAttr.getNamedItem("name").getNodeValue();
        if (model.isGestureNameTaken(gestureName)) {
          // gesture is already built, so just reuse it
          resource = model.getResourceFromGestureName(gestureName);
        } else {
          // build gesture recursively
          List<SoundResource> resourcesInGesture = getSoundResources(soundNode.getChildNodes());

          // get the delays associated with the resources in gesture
          List<Integer> delays = new ArrayList<Integer>();
          for (int j = 0; j < resourcesInGesture.size(); j++) {
            delays.add(resourcesInGesture.get(j).getDelay());
          }
          GestureSound gestureSound = new GestureSound(resourcesInGesture, delays);
          resource = new SoundResource(gestureName, gestureSound, delay, track);

          // add it to the model and possibly control panel
          if (controlPanel == null) {
            // playing from command line, don't update JControlPanel
            model.addUserDefinedGesture(resource);
          } else {
            controlPanel.addUserDefinedGesture(gestureName, resource, model);
          }
        }
      } else {
        // this is a ClipSound
        String soundFilename = soundAttr.getNamedItem("audio").getNodeValue();
        resource = model.getResourceFromSoundFilename(soundFilename);
      }

      // wrap the resource
      SoundResource wrappedResource = new SoundResource(resource, delay, track);
      soundResources.add(wrappedResource);
    }
    return soundResources;
  }
Пример #20
0
 public static ClassStats makeClassStats(final Node node) {
   if (node.getNodeName().equals("ClassStats")) {
     final NamedNodeMap nnMap = node.getAttributes();
     final String classname = nnMap.getNamedItem("class").getNodeValue();
     final int bugs = Integer.parseInt(nnMap.getNamedItem("bugs").getNodeValue());
     return new ClassStats(classname, bugs);
   }
   return null;
 }
  private Paragraph processListItem(Node listItem, boolean expandURLs) {
    NodeList children = listItem.getChildNodes();
    NamedNodeMap atts = listItem.getAttributes();
    Node addSpaceAtt = atts.getNamedItem("addVerticalSpace"); // $NON-NLS-1$
    Node styleAtt = atts.getNamedItem("style"); // $NON-NLS-1$
    Node valueAtt = atts.getNamedItem("value"); // $NON-NLS-1$
    Node indentAtt = atts.getNamedItem("indent"); // $NON-NLS-1$
    Node bindentAtt = atts.getNamedItem("bindent"); // $NON-NLS-1$
    int style = BulletParagraph.CIRCLE;
    int indent = -1;
    int bindent = -1;
    String text = null;
    boolean addSpace = true;

    if (addSpaceAtt != null) {
      String value = addSpaceAtt.getNodeValue();
      addSpace = value.equalsIgnoreCase("true"); // $NON-NLS-1$
    }
    if (styleAtt != null) {
      String value = styleAtt.getNodeValue();
      if (value.equalsIgnoreCase("text")) { // $NON-NLS-1$
        style = BulletParagraph.TEXT;
      } else if (value.equalsIgnoreCase("image")) { // $NON-NLS-1$
        style = BulletParagraph.IMAGE;
      } else if (value.equalsIgnoreCase("bullet")) { // $NON-NLS-1$
        style = BulletParagraph.CIRCLE;
      }
    }
    if (valueAtt != null) {
      text = valueAtt.getNodeValue();
      if (style == BulletParagraph.IMAGE) text = "i." + text; // $NON-NLS-1$
    }
    if (indentAtt != null) {
      String value = indentAtt.getNodeValue();
      try {
        indent = Integer.parseInt(value);
      } catch (NumberFormatException e) {
      }
    }
    if (bindentAtt != null) {
      String value = bindentAtt.getNodeValue();
      try {
        bindent = Integer.parseInt(value);
      } catch (NumberFormatException e) {
      }
    }

    BulletParagraph p = new BulletParagraph(addSpace);
    p.setIndent(indent);
    p.setBulletIndent(bindent);
    p.setBulletStyle(style);
    p.setBulletText(text);

    processSegments(p, children, expandURLs);
    return p;
  }
  /**
   * Returns the publication type attribute (Journal, Book, etc) of a citation node.
   *
   * @param citationNode citation element
   * @return publication type
   */
  private String getCitationType(Node citationNode) {
    NamedNodeMap nnm = citationNode.getAttributes();
    Node nnmNode = nnm.getNamedItem("citation-type");

    // nlm 3.0 has this attribute listed as 'publication-type'
    nnmNode = nnmNode == null ? nnm.getNamedItem("publication-type") : nnmNode;

    // some old articles do not have this attribute
    return nnmNode == null ? null : nnmNode.getTextContent();
  }
  void readLPw() {
    FileInputStream str = null;
    DocumentBuilderFactory docBuilderFactory = null;
    DocumentBuilder docBuilder = null;
    Document doc = null;
    if (mVendorBackupSettingsFilename.exists()) {
      try {
        str = new FileInputStream(mVendorBackupSettingsFilename);
        if (mVendorSettingsFilename.exists()) {
          /// M: If both the backup and vendor settings file exist, we
          /// ignore the settings since it might have been corrupted.
          Slog.w(PackageManagerService.TAG, "Cleaning up settings file");
          mVendorSettingsFilename.delete();
        }
      } catch (java.io.IOException e) {

      }
    }

    try {
      if (str == null) {
        if (!mVendorSettingsFilename.exists()) {
          return;
        }
        str = new FileInputStream(mVendorSettingsFilename);
      }
      docBuilderFactory = DocumentBuilderFactory.newInstance();
      docBuilder = docBuilderFactory.newDocumentBuilder();
      doc = docBuilder.parse(str);
      Element root = doc.getDocumentElement();
      NodeList nodeList = root.getElementsByTagName(TAG_PACKAGE);
      Node node = null;
      NamedNodeMap nodeMap = null;
      String packageName = null;
      String installStatus = null;
      for (int i = 0; i < nodeList.getLength(); i++) {
        node = nodeList.item(i);
        if (node.getNodeName().equals(TAG_PACKAGE)) {
          nodeMap = node.getAttributes();
          packageName = nodeMap.getNamedItem(ATTR_PACKAGE_NAME).getTextContent();
          installStatus = nodeMap.getNamedItem(ATTR_INSTALL_STATUS).getTextContent();
          mVendorPackages.put(
              packageName,
              new VendorPackageSetting(packageName, installStatus.equals(VAL_INSTALLED)));
        }
      }
    } catch (java.io.IOException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    }
  }
  private void handleTrkPt(Node item, int zoomLevel, int corridorSize) {
    NamedNodeMap attrs = item.getAttributes();
    if (attrs.getNamedItem("lat") != null && attrs.getNamedItem("lon") != null) {
      try {
        Double lat = Double.parseDouble(attrs.getNamedItem("lat").getTextContent());
        Double lon = Double.parseDouble(attrs.getNamedItem("lon").getTextContent());
        int minDownloadTileXIndex = 0;
        int maxDownloadTileXIndex = 0;
        int minDownloadTileYIndex = 0;
        int maxDownloadTileYIndex = 0;
        if (corridorSize > 0) {
          double minLat = lat - 360 * (corridorSize * 1000 / Constants.EARTH_CIRC_POLE);
          double minLon =
              lon
                  - 360
                      * (corridorSize
                          * 1000
                          / (Constants.EARTH_CIRC_EQUATOR * Math.cos(lon * Math.PI / 180)));
          double maxLat = lat + 360 * (corridorSize * 1000 / Constants.EARTH_CIRC_POLE);
          double maxLon =
              lon
                  + 360
                      * (corridorSize
                          * 1000
                          / (Constants.EARTH_CIRC_EQUATOR * Math.cos(lon * Math.PI / 180)));
          minDownloadTileXIndex = calculateTileX(minLon, zoomLevel);
          maxDownloadTileXIndex = calculateTileX(maxLon, zoomLevel);
          minDownloadTileYIndex = calculateTileY(minLat, zoomLevel);
          maxDownloadTileYIndex = calculateTileY(maxLat, zoomLevel);
        } else {
          minDownloadTileXIndex = calculateTileX(lon, zoomLevel);
          maxDownloadTileXIndex = minDownloadTileXIndex;
          minDownloadTileYIndex = calculateTileY(lat, zoomLevel);
          maxDownloadTileYIndex = minDownloadTileYIndex;
        }

        for (int tileXIndex = Math.min(minDownloadTileXIndex, maxDownloadTileXIndex);
            tileXIndex <= Math.max(minDownloadTileXIndex, maxDownloadTileXIndex);
            tileXIndex++) {
          for (int tileYIndex = Math.min(minDownloadTileYIndex, maxDownloadTileYIndex);
              tileYIndex <= Math.max(minDownloadTileYIndex, maxDownloadTileYIndex);
              tileYIndex++) {
            Tile tile = new Tile(tileXIndex, tileYIndex, zoomLevel);
            if (!tilesToDownload.contains(tile)) {
              log.fine("add " + tile + " to download list.");
              tilesToDownload.add(tile);
            }
          }
        }
      } catch (NumberFormatException e) {
        // ignore ;)
      }
    }
  }
  /**
   * Parses protocol.
   *
   * @param xmlString protocol as XML string
   * @return protocol
   * @throws ProtocolException if error parsing protocol
   */
  public Protocol parseProtocol(String xmlString) {
    try {
      Document doc = DomUtil.makeDomFromString(xmlString, false);

      String protocolName = "";
      long flags = 0;
      List<String> vDest = null;
      StringAttributeMap properties = new StringAttributeMap();
      NodeList protocolNL = doc.getElementsByTagName("protocol");

      if (protocolNL.getLength() >= 1) {
        Node protocolN = protocolNL.item(0);

        NamedNodeMap attributes = protocolN.getAttributes();

        Node protocolTypeN = attributes.getNamedItem("type");
        protocolName = Val.chkStr(protocolTypeN != null ? protocolTypeN.getNodeValue() : "");

        Node flagsN = attributes.getNamedItem("flags");
        flags = flagsN != null ? Val.chkLong(Val.chkStr(flagsN.getNodeValue()), 0) : 0;

        Node destinationsN = attributes.getNamedItem("destinations");
        String sDest = destinationsN != null ? Val.chkStr(destinationsN.getNodeValue()) : null;
        vDest = sDest != null ? Arrays.asList(sDest.split(",")) : null;

        NodeList propertiesNL = protocolN.getChildNodes();
        for (int i = 0; i < propertiesNL.getLength(); i++) {
          Node property = propertiesNL.item(i);
          String propertyName = property.getNodeName();
          String propertyValue = property.getTextContent();
          properties.set(propertyName, propertyValue);
        }
      }

      ProtocolFactory protocolFactory = get(protocolName);
      if (protocolFactory == null) {
        throw new IllegalArgumentException("Unsupported protocol: " + protocolName);
      }

      Protocol protocol = protocolFactory.newProtocol();
      protocol.setFlags(flags);
      protocol.applyAttributeMap(properties);
      ProtocolInvoker.setDestinations(protocol, vDest);

      return protocol;
    } catch (ParserConfigurationException ex) {
      throw new IllegalArgumentException("Error parsing protocol.", ex);
    } catch (SAXException ex) {
      throw new IllegalArgumentException("Error parsing protocol.", ex);
    } catch (IOException ex) {
      throw new IllegalArgumentException("Error parsing protocol.", ex);
    }
  }
  private void annotateText(String text, JCas aJCas, int textOffset) {
    HttpPost httpPost = new HttpPost("http://spotlight.dbpedia.org/rest/annotate/");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("disambiguator", "Default"));
    nvps.add(new BasicNameValuePair("confidence", Float.toString(confidence)));
    nvps.add(new BasicNameValuePair("support", Integer.toString(support)));
    nvps.add(new BasicNameValuePair("text", text));
    httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
    httpPost.addHeader("Accept", "text/xml");
    try {
      httpPost.setEntity(new UrlEncodedFormEntity(nvps));

      HttpResponse response = httpClient.execute(httpPost);
      System.out.println(response.getStatusLine());

      HttpEntity entity = response.getEntity();

      Document doc = dBuilder.parse(entity.getContent());

      NodeList resources = doc.getElementsByTagName("Resource");
      int numOfResources = resources.getLength();
      System.out.println(String.format("Creating %d resources in text.", numOfResources));
      for (int i = 0; i < numOfResources; i++) {
        Node resource = resources.item(i);
        NamedNodeMap attributes = resource.getAttributes();
        String uri = attributes.getNamedItem("URI").getNodeValue();
        int offset =
            Integer.parseInt(attributes.getNamedItem("offset").getNodeValue()) + textOffset;
        double similarity =
            Double.parseDouble(attributes.getNamedItem("similarityScore").getNodeValue());
        String surface = attributes.getNamedItem("surfaceForm").getNodeValue();
        String types = attributes.getNamedItem("types").getNodeValue();

        createDbpediaResource(aJCas, uri, offset, surface, similarity, types);
      }
      System.out.println("Finish creating resources");

      EntityUtils.consume(entity);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } finally {
      httpPost.releaseConnection();
    }
  }
Пример #27
0
  /** @param configFile configuration file */
  private void parseConfigFile(final InputStream configFile) {

    String ribElementName;
    String ribElementClassName;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse(configFile);
    } catch (ParserConfigurationException pce) {
      logger.error(pce.toString());
    } catch (IOException ioe) {
      logger.error(ioe.toString());
    } catch (SAXException spe) {
      logger.error(spe.toString());
    } catch (IllegalArgumentException iae) {
      logger.error(iae.toString());
    }

    // Get the root
    Element root = document.getDocumentElement();

    // Get all the packages
    NodeList ribPackages = root.getElementsByTagName("package");

    // Loop through all the packages
    for (int i = 0; i < ribPackages.getLength(); i++) {

      Node ribPackage = ribPackages.item(i);

      NodeList ribElements = ribPackage.getChildNodes();
      String packageName = ribPackage.getAttributes().getNamedItem("name").getNodeValue();

      logger.debug("Package: " + packageName);

      // Loop through all elements in this package
      for (int x = 0; x < ribElements.getLength(); x++) {

        // Get values
        Node ribElement = ribElements.item(x);

        if (ribElement.getNodeType() == Node.ELEMENT_NODE) {
          NamedNodeMap ribElementAttributes = ribElement.getAttributes();
          ribElementName = ribElementAttributes.getNamedItem("name").getNodeValue();
          ribElementClassName = ribElementAttributes.getNamedItem("classname").getNodeValue();
          rib.put(ribElementName, packageName + "." + ribElementClassName);
          logger.debug("Class name: " + ribElementClassName);
        }
      }
    }
  }
 public static Player fromXml(Node playerRoot, int num, Color color) {
   StrategyPlayer player = new StrategyPlayer(StrategyPlayer.class.getSimpleName(), num, color);
   NamedNodeMap attrs = playerRoot.getAttributes();
   if (attrs.getNamedItem("strategy") != null) {
     try {
       Field field = PlayoutStrategy.class.getField(attrs.getNamedItem("strategy").getNodeValue());
       player.description = String.format("strategy=%s", field.getName());
       player.strategy = (PlayoutStrategy) field.get(null);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return player;
 }
Пример #29
0
  private static Category parseCategory(Node n) {
    NamedNodeMap atts = n.getAttributes();
    String name = atts.getNamedItem("name").getNodeValue();
    String desc = atts.getNamedItem("description").getNodeValue();

    Category cat = new Category(name, desc);

    NodeList children = n.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
      parseNode(children.item(i), cat);
    }

    return cat;
  }
  private static void createProjectDirective(GenerationTarget target, Node node) {
    NamedNodeMap attrs = node.getAttributes();
    Node attr = attrs.getNamedItem("file");
    String templateFile = attr.getNodeValue();

    attr = attrs.getNamedItem("baseName");
    String baseName = attr.getNodeValue();

    attr = attrs.getNamedItem("output");
    String pattern = attr.getNodeValue();

    ProjectDirective directive = new ProjectDirective(templateFile, baseName, pattern);
    target.directives.add(directive);
  }