Ejemplo n.º 1
0
 public static void main(String[] args) {
   Document xml = XMLUtil.readXML(".\\data\\movie\\2065063.xml");
   List<Danmaku> danmakuList = XMLUtil.extractFromFile(xml);
   Collections.sort(danmakuList);
   Global.init();
   Global.userID = new ExtractUtil(danmakuList).extractUser();
   NoiseWiper.dict_init();
   WindowBuilder windowBuilder = new WindowBuilder(WINDOW_SIZE, WINDOW_SLIDE_STEP);
   List<TimeWindow> timeWindowClipList = windowBuilder.buildWindowsFromFile(path);
   List userAlive = new ArrayList<Integer>();
   List numOfDanmaku = new ArrayList<Integer>();
   List averageLength = new ArrayList<Double>();
   Collections.sort(timeWindowClipList);
   for (TimeWindow timeWindow : timeWindowClipList) {
     userAlive.add(timeWindow.getUserAlive());
     numOfDanmaku.add(timeWindow.getNumOfDanmaku());
     averageLength.add(timeWindow.getAverageLength());
     Matrix matrix = new Matrix(timeWindow);
     int matrixID = Integer.parseInt(Long.toString(timeWindow.getId()));
     matrix.output(matrixID, " ");
   }
   Global.output();
   FileUtil.output2File(numOfDanmaku, "numOfDanmaku.txt");
   FileUtil.output2File(userAlive, "userAlive.txt");
   FileUtil.output2File(averageLength, "averageLength.txt");
 }
Ejemplo n.º 2
0
  private void populateLookup(String xml, int SymbologyStandard) {

    ArrayList<String> al = XMLUtil.getItemList(xml, "<SYMBOL>", "</SYMBOL>");
    for (int i = 0; i < al.size(); i++) {
      String data = (String) al.get(i);
      String ID = XMLUtil.parseTagValue(data, "<SYMBOLID>", "</SYMBOLID>");
      String description = XMLUtil.parseTagValue(data, "<DESCRIPTION>", "</DESCRIPTION>");
      String m1u = XMLUtil.parseTagValue(data, "<MAPPING1U>", "</MAPPING1U>");
      String m1f = XMLUtil.parseTagValue(data, "<MAPPING1F>", "</MAPPING1F>");
      String m1n = XMLUtil.parseTagValue(data, "<MAPPING1N>", "</MAPPING1N>");
      String m1h = XMLUtil.parseTagValue(data, "<MAPPING1H>", "</MAPPING1H>");
      String m2 = XMLUtil.parseTagValue(data, "<MAPPING2>", "</MAPPING2>");
      String c1 = XMLUtil.parseTagValue(data, "<MAPPING1COLOR>", "</MAPPING1COLOR>");
      String c2 = XMLUtil.parseTagValue(data, "<MAPPING2COLOR>", "</MAPPING2COLOR>");

      UnitFontLookupInfo uflTemp = null;

      // Check for bad font locations and remap
      m1u = checkMappingIndex(m1u);
      m1f = checkMappingIndex(m1f);
      m1n = checkMappingIndex(m1n);
      m1h = checkMappingIndex(m1h);
      m2 = checkMappingIndex(m2);
      ////////////////////////////////////////

      uflTemp = new UnitFontLookupInfo(ID, description, m1u, m1f, m1n, m1h, c1, m2, c2);

      if (uflTemp != null) {
        if (SymbologyStandard == RendererSettings.Symbology_2525Bch2_USAS_13_14)
          hashMapB.put(ID, uflTemp);
        else if (SymbologyStandard == RendererSettings.Symbology_2525C) hashMapC.put(ID, uflTemp);
      }
    }
  }
Ejemplo n.º 3
0
  static void validateAgainstAUDTDs(InputSource input, final Path updaterJar, final Task task)
      throws IOException, SAXException {
    XMLUtil.parse(
        input,
        true,
        false,
        XMLUtil.rethrowHandler(),
        new EntityResolver() {
          ClassLoader loader = new AntClassLoader(task.getProject(), updaterJar);

          public InputSource resolveEntity(String publicId, String systemId)
              throws SAXException, IOException {
            String remote = "http://www.netbeans.org/dtds/";
            if (systemId.startsWith(remote)) {
              String rsrc = "org/netbeans/updater/resources/" + systemId.substring(remote.length());
              URL u = loader.getResource(rsrc);
              if (u != null) {
                return new InputSource(u.toString());
              } else {
                task.log(rsrc + " not found in " + updaterJar, Project.MSG_WARN);
              }
            }
            return null;
          }
        });
  }
  public void writeXML(PrintWriter out, int indent) {
    XMLUtil.printIndent(out, indent++);
    out.println(
        "<register "
            + (hasId() ? ("id=\"" + getId() + "\" ") : "")
            + "type=\""
            + type
            + "\" variable-name=\""
            + variableName
            + "\">");

    Iterator iter = args.entrySet().iterator();

    while (iter.hasNext()) {
      Map.Entry entry = (Map.Entry) iter.next();
      XMLUtil.printIndent(out, indent);
      out.print("<arg name=\"");
      out.print(entry.getKey());
      out.print("\">");

      if ("beanshell".equals(type) || "bsf".equals(type)) {
        out.print("<![CDATA[");
        out.print(entry.getValue());
        out.print("]]>");
      } else {
        out.print(XMLUtil.encode(entry.getValue()));
      }

      out.println("</arg>");
    }

    XMLUtil.printIndent(out, --indent);
    out.println("</register>");
  }
  /** @param node */
  public RemoteMethodArg(Node node) throws GrpcException {
    this.mode = NgParamTypes.getModeVal(XMLUtil.getAttributeValue(node, attrIOMode));
    try {
      this.type = NgParamTypes.getTypeVal(XMLUtil.getAttributeValue(node, attrType));
    } catch (NumberFormatException e) {
      throw new NgXMLReadException(e);
    }

    // number of dimension
    this.nDims = XMLUtil.countChildNode(node, namespaceURI, RemoteMethodArgSubScript.elemSubscript);
    if (this.nDims == 0) {
      this.argSubScript = null; // no dimensions
    } else {
      // set for dimensions
      this.argSubScript = new RemoteMethodArgSubScript[this.nDims];

      // read information of subscript
      for (int i = 0; i < this.nDims; i++) {
        Node subscriptNode =
            XMLUtil.getChildNode(node, namespaceURI, RemoteMethodArgSubScript.elemSubscript, i);
        this.argSubScript[i] = new RemoteMethodArgSubScript(subscriptNode);
      }
    }

    // create RemoteMethodInfo for callback
    if (this.type == NgParamTypes.NG_TYPE_CALLBACK) {
      this.callbackInfo =
          new RemoteMethodInfo(
              XMLUtil.getChildNode(node, namespaceURI, RemoteMethodInfo.elemMethod));
    }
  }
 public void loadChildren(Element element, XModelObject o) {
   super.loadChildren(element, o);
   if (isFileSystems(element.getNodeName())) {
     Element e = XMLUtil.getUniqueChild(element, "web"); // $NON-NLS-1$
     if (e == null) e = XMLUtil.getUniqueChild(element, "WEB"); // $NON-NLS-1$
     XModelObject w = getWeb(o);
     if (w != null && e != null) load(e, w);
   }
 }
Ejemplo n.º 7
0
 @Test
 public void testWriteDocumentToDisk() {
   String xmlString =
       "<?xml version=\"1.0\"?><catalog><book id=\"bk101\"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price><publish_date>2000-10-01</publish_date><description>An in-depth look at creating applications with XML.</description></book></catalog>";
   Document doc = XMLUtil.getDocument(xmlString);
   try {
     XMLUtil.writeDocumentToDisk(doc, tempFolder.newFolder(), "sample.xml");
   } catch (IOException e) {
     fail(e.getMessage());
   }
 }
  public void readFileAndGenerate(boolean onlyUniquePeptides, ISpectrumDataFilter... filters) {
    @SuppressWarnings("UnusedDeclaration")
    int numberProcessed = 0;
    @SuppressWarnings("UnusedDeclaration")
    double lastRetentionTime = 0;

    @SuppressWarnings("UnusedDeclaration")
    int numberUnProcessed = 0;
    try {
      LineNumberReader rdr = new LineNumberReader(new FileReader(m_File));
      String line = rdr.readLine();
      while (line != null) {
        if (line.contains("<spectrum_query")) {
          String retention_time_sec = XMLUtil.extractAttribute(line, "retention_time_sec");
          scan_id = XMLUtil.extractAttribute(line, "start_scan");
          if (retention_time_sec == null) {
            lastRetentionTime = 0;
          } else {
            try {
              lastRetentionTime = Double.parseDouble(retention_time_sec.trim());
            } catch (NumberFormatException e) {
              lastRetentionTime = 0;
            }
          }
        }

        //noinspection StatementWithEmptyBody,StatementWithEmptyBody
        if (line.contains("<search_result")) {
          String[] searchHitLines = readSearchHitLines(line, rdr);
          //              System.out.println(line);
          boolean processed =
              handleSearchHit(searchHitLines, lastRetentionTime, onlyUniquePeptides, filters);
          if (processed) {
            for (int i = 0; i < searchHitLines.length; i++) {
              @SuppressWarnings("UnusedDeclaration")
              String searchHitLine = searchHitLines[i];
            }
            numberProcessed++;
          } else numberUnProcessed++;
        }
        line = rdr.readLine();
      }

      //noinspection UnnecessaryReturnStatement
      return;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 9
0
  public static void main(String args[]) throws Exception {
    if (args.length < 1) {
      printUsage();
      System.exit(1);
    } else {
      String inputConf = args[0] + "/conf/conf.xml";
      configuration = XMLUtil.getConfiguration(inputConf);
    }

    String outputConf = args[0] + "/output/partition-conf.xml";
    XMLUtil.writeToXML(configuration, outputConf);

    String outputPartitionInfo = args[0] + "/output/partitions";
    XMLUtil.writePartitionInfo(configuration, outputPartitionInfo);
  }
Ejemplo n.º 10
0
  public void writeXML(PrintWriter out, int indent) {
    ConditionsDescriptor conditions = getConditionsDescriptor();

    List list = conditions.getConditions();

    if (list.size() == 0) {
      return;
    }

    XMLUtil.printIndent(out, indent++);
    out.println("<restrict-to>");
    conditions.writeXML(out, indent);
    XMLUtil.printIndent(out, --indent);
    out.println("</restrict-to>");
  }
Ejemplo n.º 11
0
 /* (non-Javadoc)
  * @see org.eclipse.ohf.utilities.xml.IXMLWriter#element(java.lang.String, java.lang.String, java.lang.String)
  */
 @Override
 public void element(String namespace, String name, String content) throws IOException {
   if (!XMLUtil.isNMToken(name)) throw new IOException("XML name " + name + " is not valid");
   open(namespace, name);
   text(content);
   close();
 }
Ejemplo n.º 12
0
  /* (non-Javadoc)
   * @see org.eclipse.ohf.utilities.xml.IXMLWriter#open(java.lang.String, java.lang.String, java.lang.String)
   */
  @Override
  public void open(String namespace, String name, String comment) throws IOException {
    if (!XMLUtil.isNMToken(name)) throw new IOException("XML name " + name + " is not valid");
    checkStarted();
    if (pendingClose) {
      write('>');
      writePendingComment();
      pendingClose = false;
    }

    if (name == null) {
      throw new IOException("name is null");
    }
    newLevelIfRequired();
    levels.current().setName(name);
    levels.current().setNamespace(namespace);
    int col = writePretty();
    write('<');
    if (namespace == null) {
      write(name);
      col = col + name.length() + 1;
    } else {
      String n = getNSAbbreviation(namespace) + name;
      write(n);
      col = col + n.length() + 1;
    }
    writeAttributes(col);
    pendingOpen = false;
    pendingClose = true;
    pendingComment = comment;
  }
 public static IdentifiedPSM processPeptide(final String line, double retentionTime, String id) {
   String peptide = XMLUtil.extractAttribute(line, "peptide");
   if (peptide == null) throw new IllegalArgumentException("bad line " + line);
   Polypeptide polypeptide = Polypeptide.fromString(peptide);
   polypeptide.setRetentionTime(retentionTime);
   return new IdentifiedPSM(id, polypeptide);
 }
  protected void init(Element register) {
    this.type = register.getAttribute("type");
    this.variableName = register.getAttribute("variable-name");

    try {
      setId(Integer.parseInt(register.getAttribute("id")));
    } catch (NumberFormatException e) {
    }

    List args = XMLUtil.getChildElements(register, "arg");

    for (int l = 0; l < args.size(); l++) {
      Element arg = (Element) args.get(l);
      this.args.put(arg.getAttribute("name"), XMLUtil.getText(arg));
    }
  }
Ejemplo n.º 15
0
  public static Record exportToRecord(
      Node node, String baseWikiUri, String oaiUri, String oaiPrefix) throws Exception {
    String datestamp = XPathUtil.evalToString(node, DBPediaXPathUtil.getDatestampExpr());
    // System.out.println("DATESTAMP = " + datestamp);

    // System.out.println(XMLUtil.toString(node));

    String language = XPathUtil.evalToString(node, DBPediaXPathUtil.getLanguageExpr());
    String t = XPathUtil.evalToString(node, DBPediaXPathUtil.getTitleExpr());

    // http://en.wikipedia.org/wiki/Special:OAIRepository
    // MediawikiTitle title = MediawikiHelper.parseTitle(domainUri
    //		+ "/wiki/Special:OAIRepository", t);
    MediawikiTitle title = MediawikiHelper.parseTitle(oaiUri, t);

    String oaiId = oaiPrefix + XPathUtil.evalToString(node, DBPediaXPathUtil.getPageIdExpr());
    // String wikipediaUri = domainUri + "/wiki/" + URLEncoder.encode(title.getFullTitle(),
    // "UTF-8");
    String wikipediaUri = baseWikiUri + URLEncoder.encode(title.getFullTitle(), "UTF-8");
    String revision = XPathUtil.evalToString(node, DBPediaXPathUtil.getRevisionExpr());
    String username = XPathUtil.evalToString(node, DBPediaXPathUtil.getContributorNameExpr());
    String ip = XPathUtil.evalToString(node, DBPediaXPathUtil.getContributorIpExpr());
    String userId = XPathUtil.evalToString(node, DBPediaXPathUtil.getContributorIdExpr());

    String text = XPathUtil.evalToString(node, DBPediaXPathUtil.getTextExpr());

    RecordMetadata metadata =
        new RecordMetadata(
            language, title, oaiId, IRI.create(wikipediaUri), revision, username, ip, userId);

    RecordContent content = new RecordContent(text, revision, XMLUtil.toString(node));

    return new Record(metadata, content);
  }
 /**
  * This method returns a Document from the contents of the XML file as contained in the String
  * xmlFile, with no restriction as to the root element.
  */
 public Document loadXMLFile(String xmlFile) {
   if (!StringUtil.blank(xmlFile)) {
     Document CipresDoc = XMLUtil.getDocumentFromString(xmlFile);
     return CipresDoc;
   }
   return null;
 }
Ejemplo n.º 17
0
 @Test
 public void testGetDocumentString() {
   String xmlString =
       "<?xml version=\"1.0\"?><catalog><book id=\"bk101\"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price><publish_date>2000-10-01</publish_date><description>An in-depth look at creating applications with XML.</description></book></catalog>";
   Document doc = XMLUtil.getDocument(xmlString);
   assertNotNull(doc);
 }
Ejemplo n.º 18
0
 /** Конструктор по умолчанию */
 public FormatXMLWriter() {
   try {
     outline = new OutlineXMLWriter(createXMLWriter(System.out));
   } catch (XMLStreamException ex) {
     XMLUtil.fireException(ex);
     outline = null;
   }
 }
Ejemplo n.º 19
0
 @Override
 protected Object getNodeValue(Node node, String name, Class<?> clasz) {
   if (name.equals("description")) { // $NON-NLS-1$
     return XMLUtil.readTextNode(node);
   } else {
     return super.getNodeValue(node, name, clasz);
   }
 }
Ejemplo n.º 20
0
 /**
  * Returns the encoding.
  *
  * @param charset
  * @return encoding
  * @throws IOException
  */
 public static String getXMLCharsetName(String charset) throws IOException {
   if (charset == null || charset.equals("")) return "UTF-8";
   else if (charset.equals("US-ASCII")) return "UTF-8";
   else if (XMLUtil.charSetImpliesAscii(charset)) return "ISO-8859-1";
   else if (charset.equals("UTF-8")) return "UTF-8";
   else if (charset.equals("UTF-16") || charset.equals("UTF-16BE") || charset.equals("UTF-16LE"))
     return "UTF-16";
   else throw new IOException("Unknown charset encoding " + charset);
 }
Ejemplo n.º 21
0
 /**
  * Sets the {@linkplain #rootTag} property.
  *
  * @param rootTag to be used as XML root tag
  * @throws IllegalArgumentException if tag is null or empty
  * @throws IllegalStateException if write isn't in initial state
  */
 public void setRootTag(String rootTag) {
   if (!XMLUtil.isLegalXMLTag(rootTag)) {
     throw new IllegalArgumentException("rootTag: illegal: " + rootTag);
   }
   if (!this.isInitialState()) {
     throw new IllegalStateException("writer write in progress");
   }
   this.checkNotSharedConfiguration();
   this.rootTag = rootTag;
 }
Ejemplo n.º 22
0
  protected void init(Element restriction) {
    List conditionNodes = XMLUtil.getChildElements(restriction, "conditions");
    int length = conditionNodes.size();

    for (int i = 0; i < length; ++i) {
      Element condition = (Element) conditionNodes.get(i);
      ConditionsDescriptor conditionDescriptor =
          DescriptorFactory.getFactory().createConditionsDescriptor(condition);
      conditionDescriptor.setParent(this);
      this.conditions.add(conditionDescriptor);
    }
  }
Ejemplo n.º 23
0
 /* (non-Javadoc)
  * @see org.eclipse.ohf.utilities.xml.IXMLWriter#text(java.lang.String, boolean)
  *
  * Replace escapeText()
  */
 @Override
 public void text(String content, boolean dontEscape) throws IOException {
   checkInElement();
   if (content != null) {
     if (pendingClose) {
       write(">");
       writePendingComment();
       pendingClose = false;
     }
     if (dontEscape) write(content);
     else write(XMLUtil.escapeXML(content, charset, false));
   }
 }
Ejemplo n.º 24
0
 protected void setAttribute(String name, String value) throws IOException {
   newLevelIfRequired();
   if (attributes == null) addAttribute(name, value, false);
   else {
     for (int i = 0; i < attributes.length; i++) {
       if (attributes[i][0].equals(name)) {
         attributes[i][1] = XMLUtil.escapeXML(value, charset, false);
         return;
       }
     }
     addAttribute(name, value);
   }
 }
Ejemplo n.º 25
0
  /**
   * @param deviceDef
   * @param maxAge
   * @param vendorFirmware
   * @param discoveryUSN
   * @param discoveryUDN
   * @return a new {@link RootDevice}, or <code>null</code>
   */
  public static RootDevice build(
      String myIP,
      URL deviceDef,
      String maxAge,
      String vendorFirmware,
      String discoveryUSN,
      String discoveryUDN) {
    Document xml = XMLUtil.getXML(deviceDef);

    URL baseURL = null;

    try {
      String base = XMLUtil.xpath.evaluate("/root/URLBase", xml);

      try {
        if (base != null && base.trim().length() > 0) {
          baseURL = new URL(base);
        }
      } catch (MalformedURLException malformedEx) {
        // crappy urlbase provided
        // log.warn( "Error occured during device baseURL " + base
        // + " parsing, building it from device default location",
        // malformedEx );
        malformedEx.printStackTrace();
      }

      if (baseURL == null) {
        String URL =
            deviceDef.getProtocol() + "://" + deviceDef.getHost() + ":" + deviceDef.getPort();
        String path = deviceDef.getPath();
        if (path != null) {
          int lastSlash = path.lastIndexOf('/');
          if (lastSlash != -1) {
            URL += path.substring(0, lastSlash);
          }
        }
        try {
          baseURL = new URL(URL);
        } catch (MalformedURLException e) {
          e.printStackTrace();
        }
      }

      return new RootDevice(
          myIP, xml, baseURL, maxAge, deviceDef, vendorFirmware, discoveryUSN, discoveryUDN);
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    return null;
  }
Ejemplo n.º 26
0
  private void addAttribute(String name, String value, boolean noLines) throws IOException {
    if (!XMLUtil.isNMToken(name))
      throw new IOException("XML name " + name + " is not valid for value '" + value + "'");

    newLevelIfRequired();
    value = XMLUtil.escapeXML(value, charset, noLines);

    if (attributes == null) attributes = new String[][] {{name, value}};
    else {
      String[][] newattr = new String[attributes.length + 1][];
      for (int i = 0; i < attributes.length; i++) {
        condition(
            !attributes[i][0].equals(name),
            "attempt to define attribute with name "
                + name
                + " more than once for value '"
                + value
                + "'");
        newattr[i] = attributes[i];
      }
      attributes = newattr;
      attributes[attributes.length - 1] = new String[] {name, value};
    }
  }
Ejemplo n.º 27
0
  public FormatXMLWriter(File file, Charset encoding) throws FileNotFoundException {
    if (file == null) {
      throw new IllegalArgumentException("file == null");
    }
    if (encoding == null) {
      throw new IllegalArgumentException("encoding == null");
    }

    FileOutputStream fout = null;
    fout = new FileOutputStream(file);
    Writer wr = new OutputStreamWriter(fout, encoding);

    try {
      outline = new OutlineXMLWriter(createXMLWriter(wr));
    } catch (XMLStreamException ex) {
      XMLUtil.fireException(ex);
      outline = null;
    }
  }
  public @Override void execute() throws BuildException {
    String p = getProject().getProperty("javahelpbin.exclude.modules");
    excludedModulesSet = parseExcludeModulesProperty(p);
    for (FileSet fs : filesets) {
      FileScanner scanner = fs.getDirectoryScanner(getProject());
      File dir = scanner.getBasedir();
      String[] files = scanner.getIncludedFiles();

      URLClassLoader globalClassLoader;
      Map<String, URLClassLoader> classLoaderMap;
      try {
        globalClassLoader = createGlobalClassLoader(dir, files);
        classLoaderMap = createClassLoaderMap(dir, files);
        NbDocsStreamHandler.NbDocsURLConnection.globalClassLoader.set(globalClassLoader);
        NbDocsStreamHandler.NbDocsURLConnection.classLoaderMap.set(classLoaderMap);
        CheckLinks.handlerFactory.set(new NbDocsStreamHandler.Factory());
        for (Map.Entry<String, URLClassLoader> entry : classLoaderMap.entrySet()) {
          String cnb = entry.getKey();
          if (excludedModulesSet.contains(cnb)) {
            log("skipping module: " + cnb, Project.MSG_INFO);
            continue;
          }
          URLClassLoader l = entry.getValue();
          Manifest m;
          InputStream is = l.getResourceAsStream("META-INF/MANIFEST.MF");
          if (is != null) {
            try {
              m = new Manifest(is);
            } finally {
              is.close();
            }
          } else {
            log("No manifest in " + Arrays.toString(l.getURLs()), Project.MSG_WARN);
            continue;
          }
          for (String resource :
              new String[] {
                m.getMainAttributes().getValue("OpenIDE-Module-Layer"),
                "META-INF/generated-layer.xml"
              }) {
            if (resource == null) {
              continue;
            }
            URL layer = l.getResource(resource);
            if (layer == null) {
              log("No layer " + resource, Project.MSG_VERBOSE);
              continue;
            }
            Document doc;
            try {
              doc = XMLUtil.parse(new InputSource(layer.toString()), false, false, null, NO_DTDS);
            } catch (SAXException x) {
              log("Could not parse " + layer, x, Project.MSG_WARN);
              continue;
            }
            for (Element services : XMLUtil.findSubElements(doc.getDocumentElement())) {
              if (!services.getTagName().equals("folder")
                  || !services.getAttribute("name").equals("Services")) {
                continue;
              }
              for (Element javahelp : XMLUtil.findSubElements(services)) {
                if (!javahelp.getTagName().equals("folder")
                    || !javahelp.getAttribute("name").equals("JavaHelp")) {
                  continue;
                }
                JAVAHELP:
                for (Element registration : XMLUtil.findSubElements(javahelp)) {
                  if (!registration.getTagName().equals("file")) {
                    continue;
                  }
                  InputSource input = null;
                  String url = registration.getAttribute("url");
                  if (!url.isEmpty()) {
                    input = new InputSource(new URL(layer, url).toString());
                  } else {
                    NodeList nl = registration.getChildNodes();
                    for (int i = 0; i < nl.getLength(); i++) {
                      if (nl.item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
                        if (input == null) {
                          input = new InputSource(new StringReader(nl.item(i).getNodeValue()));
                        } else {
                          log(
                              "Multiple content for "
                                  + registration.getAttribute("name")
                                  + " in "
                                  + layer,
                              Project.MSG_WARN);
                          continue JAVAHELP;
                        }
                      }
                    }
                    if (input == null) {
                      log(
                          "No content for " + registration.getAttribute("name") + " in " + layer,
                          Project.MSG_WARN);
                    }
                  }
                  Document doc2;
                  try {
                    doc2 = XMLUtil.parse(input, false, false, null, NO_DTDS);
                  } catch (SAXException x) {
                    log(
                        "Could not parse " + registration.getAttribute("name") + " in " + layer,
                        x,
                        Project.MSG_WARN);
                    continue;
                  }
                  URI helpsetref = URI.create(doc2.getDocumentElement().getAttribute("url"));
                  if ("nbdocs".equals(helpsetref.getScheme())
                      && helpsetref.getAuthority() == null) {
                    try {
                      helpsetref =
                          new URI(
                              helpsetref.getScheme(),
                              cnb,
                              helpsetref.getPath(),
                              helpsetref.getQuery(),
                              helpsetref.getFragment());
                    } catch (URISyntaxException x) {
                      throw new BuildException(x);
                    }
                  }
                  log("checking: " + helpsetref, Project.MSG_INFO);
                  checkHelpSetURL(
                      CheckLinks.toURL(helpsetref), globalClassLoader, l, classLoaderMap, cnb);
                }
              }
            }
          }
        }
      } catch (IOException x) {
        throw new BuildException(x);
      } finally {
        NbDocsStreamHandler.NbDocsURLConnection.globalClassLoader.set(null);
        NbDocsStreamHandler.NbDocsURLConnection.classLoaderMap.set(null);
        CheckLinks.handlerFactory.set(null);
      }
    }
  }
Ejemplo n.º 29
0
  /**
   * @param chnlId
   * @param xmlStr
   * @param chnlStr
   * @return
   */
  public String processXMLForChnls(String chnlId, String xmlStr, final String chnlStr) {
    if ("106".equals(chnlId) || "102".equals(chnlId)) {
      try {
        xmlStr = URLEncoder.encode(xmlStr.trim(), "UTF-8");
      } catch (UnsupportedEncodingException e) {
      }
      xmlStr = "xml=".concat(xmlStr);

    } else if ("103".equals(chnlId) && !"Route1_CONT".equals(chnlStr)) {

      xmlStr =
          "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
              + "<soap:Header>"
              + "<SOAP-SEC:Signature xmlns:SOAP-SEC=\"http://schemas.xmlsoap.org/soap/security/2000-12\">"
              + "</SOAP-SEC:Signature>"
              + "</soap:Header>".concat(xmlStr).concat("</soap:Envelope>");
      try {

        // Create a DOM XMLSignatureFactory that will be used to
        // generate the enveloped signature.
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        Reference ref =
            fac.newReference(
                "#Body",
                fac.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(
                    fac.newTransform(
                        "http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null)),
                null,
                null);

        // Create the SignedInfo.
        SignedInfo si =
            fac.newSignedInfo(
                fac.newCanonicalizationMethod(
                    CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                Collections.singletonList(ref));

        // Load the KeyStore and get the signing key and
        // certificate.
        KeyStore ks = KeyStore.getInstance("JKS");

        String certFileNm = "";
        // commonConfigHelper.getConfigMap().get(
        // "ROUTE1_CERTIFICATE_JSK");
        String pwd = ""; // commonConfigHelper.getConfigMap().get(
        // "ROUTE1_CERTIFICATE_PASSWORD");
        String aliasNm = ""; // commonConfigHelper.getConfigMap().get(
        // "ROUTE1_CERTIFICATE_ALIAS");
        ks.load(new FileInputStream(certFileNm), pwd.toCharArray());
        KeyStore.PrivateKeyEntry keyEntry =
            (KeyStore.PrivateKeyEntry)
                ks.getEntry(aliasNm, new KeyStore.PasswordProtection(pwd.toCharArray()));
        X509Certificate cert = (X509Certificate) keyEntry.getCertificate();

        // Create the KeyInfo containing the X509Data.
        KeyInfoFactory kif = fac.getKeyInfoFactory();
        List x509Content = new ArrayList();
        // x509Content.add(cert.getSubjectX500Principal().getName());
        x509Content.add(cert.getIssuerX500Principal().getName());
        X509Data xd = kif.newX509Data(x509Content);
        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));

        // Instantiate the document to be signed.
        // Document doc = xmlUtil.getDocumentFromString(xmlStr);
        Document doc = null;

        // Create a DOMSignContext and specify the RSA PrivateKey
        // and
        // location of the resulting XMLSignature's parent element.
        DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());

        // Create the XMLSignature, but don't sign it yet.
        XMLSignature signature = fac.newXMLSignature(si, ki);

        // Marshal, generate, and sign the enveloped signature.
        signature.sign(dsc);

        // Output the resulting document.

        xmlStr = xmlUtil.convertXMLDocToString(doc);

      } catch (Exception e) {
      }
    }
    return xmlStr;
  }
  protected void init(Element root) {
    NodeList children = root.getChildNodes();

    for (int i = 0; i < children.getLength(); i++) {
      Node child = children.item(i);

      if (child.getNodeName().equals("meta")) {
        Element meta = (Element) child;
        String value = XMLUtil.getText(meta);
        this.metaAttributes.put(meta.getAttribute("name"), value);
      }
    }

    // handle registers - OPTIONAL
    Element r = XMLUtil.getChildElement(root, "registers");

    if (r != null) {
      List registers = XMLUtil.getChildElements(r, "register");

      for (int i = 0; i < registers.size(); i++) {
        Element register = (Element) registers.get(i);
        RegisterDescriptor registerDescriptor =
            DescriptorFactory.getFactory().createRegisterDescriptor(register);
        registerDescriptor.setParent(this);
        this.registers.add(registerDescriptor);
      }
    }

    // handle global-conditions - OPTIONAL
    Element globalConditionsElement = XMLUtil.getChildElement(root, "global-conditions");

    if (globalConditionsElement != null) {
      Element globalConditions = XMLUtil.getChildElement(globalConditionsElement, "conditions");

      ConditionsDescriptor conditionsDescriptor =
          DescriptorFactory.getFactory().createConditionsDescriptor(globalConditions);
      conditionsDescriptor.setParent(this);
      this.globalConditions = conditionsDescriptor;
    }

    // handle initial-steps - REQUIRED
    Element intialActionsElement = XMLUtil.getChildElement(root, "initial-actions");
    List initialActions = XMLUtil.getChildElements(intialActionsElement, "action");

    for (int i = 0; i < initialActions.size(); i++) {
      Element initialAction = (Element) initialActions.get(i);
      ActionDescriptor actionDescriptor =
          DescriptorFactory.getFactory().createActionDescriptor(initialAction);
      actionDescriptor.setParent(this);
      this.initialActions.add(actionDescriptor);
    }

    // handle global-actions - OPTIONAL
    Element globalActionsElement = XMLUtil.getChildElement(root, "global-actions");

    if (globalActionsElement != null) {
      List globalActions = XMLUtil.getChildElements(globalActionsElement, "action");

      for (int i = 0; i < globalActions.size(); i++) {
        Element globalAction = (Element) globalActions.get(i);
        ActionDescriptor actionDescriptor =
            DescriptorFactory.getFactory().createActionDescriptor(globalAction);
        actionDescriptor.setParent(this);
        this.globalActions.add(actionDescriptor);
      }
    }

    // handle common-actions - OPTIONAL
    //   - Store actions in HashMap for now. When parsing Steps, we'll resolve
    //      any common actions into local references.
    Element commonActionsElement = XMLUtil.getChildElement(root, "common-actions");

    if (commonActionsElement != null) {
      List commonActions = XMLUtil.getChildElements(commonActionsElement, "action");

      for (int i = 0; i < commonActions.size(); i++) {
        Element commonAction = (Element) commonActions.get(i);
        ActionDescriptor actionDescriptor =
            DescriptorFactory.getFactory().createActionDescriptor(commonAction);
        actionDescriptor.setParent(this);
        addCommonAction(actionDescriptor);
      }
    }

    // handle timer-functions - OPTIONAL
    Element timerFunctionsElement = XMLUtil.getChildElement(root, "trigger-functions");

    if (timerFunctionsElement != null) {
      List timerFunctions = XMLUtil.getChildElements(timerFunctionsElement, "trigger-function");

      for (int i = 0; i < timerFunctions.size(); i++) {
        Element timerFunction = (Element) timerFunctions.get(i);
        Integer id = new Integer(timerFunction.getAttribute("id"));
        FunctionDescriptor function =
            DescriptorFactory.getFactory()
                .createFunctionDescriptor(XMLUtil.getChildElement(timerFunction, "function"));
        function.setParent(this);
        this.timerFunctions.put(id, function);
      }
    }

    // handle steps - REQUIRED
    Element stepsElement = XMLUtil.getChildElement(root, "steps");
    List steps = XMLUtil.getChildElements(stepsElement, "step");

    for (int i = 0; i < steps.size(); i++) {
      Element step = (Element) steps.get(i);
      StepDescriptor stepDescriptor =
          DescriptorFactory.getFactory().createStepDescriptor(step, this);
      this.steps.add(stepDescriptor);
    }

    // handle splits - OPTIONAL
    Element splitsElement = XMLUtil.getChildElement(root, "splits");

    if (splitsElement != null) {
      List split = XMLUtil.getChildElements(splitsElement, "split");

      for (int i = 0; i < split.size(); i++) {
        Element s = (Element) split.get(i);
        SplitDescriptor splitDescriptor = DescriptorFactory.getFactory().createSplitDescriptor(s);
        splitDescriptor.setParent(this);
        this.splits.add(splitDescriptor);
      }
    }

    // handle joins - OPTIONAL:
    Element joinsElement = XMLUtil.getChildElement(root, "joins");

    if (joinsElement != null) {
      List join = XMLUtil.getChildElements(joinsElement, "join");

      for (int i = 0; i < join.size(); i++) {
        Element s = (Element) join.get(i);
        JoinDescriptor joinDescriptor = DescriptorFactory.getFactory().createJoinDescriptor(s);
        joinDescriptor.setParent(this);
        this.joins.add(joinDescriptor);
      }
    }
  }