Java 类javax.xml.parsers.ParserConfigurationException 实例源码

项目:apache-tomcat-7.0.73-with-comment    文件:XercesParser.java   
/**
 * Configure schema validation as recommended by the JAXP 1.2 spec.
 * The <code>properties</code> object may contains information about
 * the schema local and language. 
 * @param properties parser optional info
 */
private static void configureOldXerces(SAXParser parser, 
                                       Properties properties) 
        throws ParserConfigurationException, 
               SAXNotSupportedException {

    String schemaLocation = (String)properties.get("schemaLocation");
    String schemaLanguage = (String)properties.get("schemaLanguage");

    try{
        if (schemaLocation != null) {
            parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
            parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
        }
    } catch (SAXNotRecognizedException e){
        log.info(parser.getClass().getName() + ": " 
                                    + e.getMessage() + " not supported."); 
    }

}
项目:fritz-home-skill    文件:SwitchService.java   
private String getSessionId() throws IOException, ParserConfigurationException, SAXException, NoSuchAlgorithmException {

    HttpURLConnection con = createConnection(SID_REQUEST_URL);

    handleResponseCode(con.getResponseCode());

    Document doc = xmlFactory.newDocumentBuilder().parse(con.getInputStream());
    logger.trace("response:\n{}", XmlUtils.docToString(doc, true));
    if (doc == null) {
      throw new IOException("SessionInfo element not available");
    }
    String sid = XmlUtils.getValue(doc.getDocumentElement(), "SID");

    if (EMPTY_SID.equals(sid)) {
      String challenge = XmlUtils.getValue(doc.getDocumentElement(), "Challenge");
      sid = getSessionId(challenge);
    }

    if (sid == null || EMPTY_SID.equals(sid)) {
      throw new IOException("sid request failed: " + sid);
    }
    return sid;

  }
项目:openjdk-jdk10    文件:JAXPTestUtilities.java   
/**
 * Compare contents of golden file with test output file by their document
 * representation.
 * Here we ignore the white space and comments. return true if they're
 * lexical identical.
 * @param goldfile Golden output file name.
 * @param resultFile Test output file name.
 * @return true if two file's document representation are identical.
 *         false if two file's document representation are not identical.
 * @throws javax.xml.parsers.ParserConfigurationException if the
 *         implementation is not available or cannot be instantiated.
 * @throws SAXException If any parse errors occur.
 * @throws IOException if an I/O error occurs reading from the file or a
 *         malformed or unmappable byte sequence is read .
 */
public static boolean compareDocumentWithGold(String goldfile, String resultFile)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setCoalescing(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setIgnoringComments(true);
    DocumentBuilder db = factory.newDocumentBuilder();

    Document goldD = db.parse(Paths.get(goldfile).toFile());
    goldD.normalizeDocument();
    Document resultD = db.parse(Paths.get(resultFile).toFile());
    resultD.normalizeDocument();
    return goldD.isEqualNode(resultD);
}
项目:xtf    文件:PomModifier.java   
public PomModifier(final Path projectDirectory, final Path gitDirectory) {
    if (builderFactory == null) {
        builderFactory = DocumentBuilderFactory.newInstance();
        transformerFactory = TransformerFactory.newInstance();
        try {
            builder = builderFactory.newDocumentBuilder();
            transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        } catch (ParserConfigurationException | TransformerConfigurationException e) {
            throw new IllegalStateException(e);
        }
    }
    this.projectPomFile = gitDirectory.resolve("pom.xml");
    this.projectDirectory = projectDirectory;
    this.gitDirectory = gitDirectory;
}
项目:DIA-Umpire-Maven    文件:PepXMLParser.java   
public PepXMLParser(LCMSID singleLCMSID, String FileName, float threshold, boolean CorrectMassDiff) throws ParserConfigurationException, SAXException, IOException, XmlPullParserException {
    this.singleLCMSID = singleLCMSID;
    this.CorrectMassDiff = CorrectMassDiff;
    this.FileName = FileName;
    this.threshold = threshold;
    Logger.getRootLogger().info("Parsing pepXML: " + FileName + "....");
    try {
        ParseSAX();
    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        Logger.getRootLogger().info("Parsing pepXML: " + FileName + " failed. Trying to fix the file...");
        insert_msms_run_summary(new File(FileName));
        ParseSAX();
    }
    //System.out.print("done\n");
}
项目:rapidminer    文件:DatabaseService.java   
public static void saveUserDefinedProperties() throws XMLException {
    Document doc;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException var4) {
        throw new XMLException("Failed to create document: " + var4, var4);
    }

    Element root = doc.createElement("drivers");
    doc.appendChild(root);
    Iterator var2 = getJDBCProperties().iterator();

    while(var2.hasNext()) {
        JDBCProperties props = (JDBCProperties)var2.next();
        if(props.isUserDefined()) {
            root.appendChild(props.getXML(doc));
        }
    }

    XMLTools.stream(doc, getUserJDBCPropertiesFile(), StandardCharsets.UTF_8);
}
项目:Reer    文件:IvyXmlModuleDescriptorParser.java   
public static void parse(
        URL xmlURL, URL schema, DefaultHandler handler)
        throws SAXException, IOException, ParserConfigurationException {
    InputStream xmlStream = URLHandlerRegistry.getDefault().openStream(xmlURL);
    try {
        InputSource inSrc = new InputSource(xmlStream);
        inSrc.setSystemId(xmlURL.toExternalForm());
        parse(inSrc, schema, handler);
    } finally {
        try {
            xmlStream.close();
        } catch (IOException e) {
            // ignored
        }
    }
}
项目:lams    文件:LessonManagerServlet.java   
/**
    * Starts preview lesson on LAMS server. Launches it.
    */
   private void start(HttpServletRequest request, HttpServletResponse response, Context ctx) throws IOException, ServletException, PersistenceException, ParseException, ValidationException, ParserConfigurationException, SAXException {

    BbPersistenceManager bbPm = PersistenceServiceFactory.getInstance().getDbPersistenceManager();

//store newly created LAMS lesson
User user = ctx.getUser();
BlackboardUtil.storeBlackboardContent(request, response, user);

// constuct strReturnUrl
String courseIdStr = request.getParameter("course_id");
String contentIdStr = request.getParameter("content_id");
// internal Blackboard IDs for the course and parent content item
Id courseId = bbPm.generateId(Course.DATA_TYPE, courseIdStr);
Id folderId = bbPm.generateId(CourseDocument.DATA_TYPE, contentIdStr);
String returnUrl = PlugInUtil.getEditableContentReturnURL(folderId, courseId);
request.setAttribute("returnUrl", returnUrl);

request.getRequestDispatcher("/modules/startLessonSuccess.jsp").forward(request, response);
   }
项目:Reer    文件:MavenMetadataLoader.java   
private void parseMavenMetadataInto(ExternalResource metadataResource, final MavenMetadata mavenMetadata) {
    LOGGER.debug("parsing maven-metadata: {}", metadataResource);
    metadataResource.withContent(new ErroringAction<InputStream>() {
        public void doExecute(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException {
            XMLHelper.parse(inputStream, null, new ContextualSAXHandler() {
                public void endElement(String uri, String localName, String qName)
                        throws SAXException {
                    if ("metadata/versioning/snapshot/timestamp".equals(getContext())) {
                        mavenMetadata.timestamp = getText();
                    }
                    if ("metadata/versioning/snapshot/buildNumber".equals(getContext())) {
                        mavenMetadata.buildNumber = getText();
                    }
                    if ("metadata/versioning/versions/version".equals(getContext())) {
                        mavenMetadata.versions.add(getText().trim());
                    }
                    super.endElement(uri, localName, qName);
                }
            }, null);
        }
    });
}
项目:TuLiPA-frames    文件:DOMderivationBuilder.java   
public static Document buildDOMderivation(ArrayList<ParseTreeCollection> all, String sentence) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder constructor    = factory.newDocumentBuilder();
        derivDoc                       = constructor.newDocument();
        derivDoc.setXmlVersion("1.0");
        derivDoc.setXmlStandalone(false);

        Element root = derivDoc.createElement("parses");
        root.setAttribute("sentence", sentence);
           for (ParseTreeCollection ptc : all)
           {
            buildOne(root, ptc.getDerivationTree().getDomNodes().get(0), ptc.getDerivedTree().getDomNodes().get(0), ptc.getSemantics(), ptc.getSpecifiedSemantics());
           }
        // finally we do not forget the root
        derivDoc.appendChild(root);
        return derivDoc;

    } catch (ParserConfigurationException e) {
        System.err.println(e);
        return null;
    }       
}
项目:jmt    文件:Measure.java   
/**
 * Creates a DOM (Document Object Model) <code>Document<code>.
 */
private void createDOM() {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        //data is a Document
        Document data = builder.newDocument();
        Element root = data.createElement("measure");
        root.setAttribute("name", name);
        root.setAttribute("meanValue", "null");
        root.setAttribute("upperBound", "null");
        root.setAttribute("lowerBound", "null");
        root.setAttribute("progress", Double.toString(getSamplesAnalyzedPercentage()));
        root.setAttribute("data", "null");
        root.setAttribute("finished", "false");
        root.setAttribute("discarded", "0");
        root.setAttribute("precision", Double.toString(analyzer.getPrecision()));
        root.setAttribute("maxSamples", Double.toString(getMaxSamples()));
        data.appendChild(root);
    } catch (FactoryConfigurationError factoryConfigurationError) {
        factoryConfigurationError.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}
项目:rapidminer    文件:UserDefinedOperatorService.java   
private static void saveOperatorDocBundle(File file) {
    try {
        Document document = DocumentBuilderFactory
                .newInstance()
                .newDocumentBuilder()
                .newDocument();

        document.setXmlVersion("1.0");
        document.setXmlStandalone(false);
        Attr attr = document.createAttribute("encoding");
        attr.setValue("UTF-8");

        Element operatorHelp = document.createElement("operatorHelp");
        for (OperatorDescription deac: getAllUserDefinedOperators()) {
            addOperatorDoc(document, operatorHelp, deac.getName(), deac.getKey());
        }
        document.appendChild(operatorHelp);

        XMLTools.stream(document, file, Charset.forName("UTF-8"));
    } catch (ParserConfigurationException | XMLException e) {
        SwingTools.showSimpleErrorMessage(ioErrorKey, e);
    }
}
项目:lams    文件:XMLSchedulingDataProcessor.java   
/**
 * Process the xmlfile named <code>fileName</code> with the given system
 * ID.
 * 
 * @param fileName
 *          meta data file name.
 * @param systemId
 *          system ID.
 */
protected void processFile(String fileName, String systemId)
    throws ValidationException, ParserConfigurationException,
        SAXException, IOException, SchedulerException,
        ClassNotFoundException, ParseException, XPathException {

    prepForProcessing();

    log.info("Parsing XML file: " + fileName + 
            " with systemId: " + systemId);
    InputSource is = new InputSource(getInputStream(fileName));
    is.setSystemId(systemId);

    process(is);

    maybeThrowValidationException();
}
项目:read_13f    文件:file_processor_new.java   
private static NodeList get_node_list(List<String> xml_lines, String addition) {
    StringBuilder sb = new StringBuilder();

    for(String line : xml_lines) { sb.append(line); }
    String xml_string = sb.toString();

    try {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml_string));

        Document doc = db.parse(is);

        if(!addition.equals("")) {
            addition = addition + ":";
        }
        return doc.getElementsByTagName(addition + "infoTable");

    } catch (ParserConfigurationException | IOException | SAXException e) {
        e.printStackTrace();
    }

    return null;
}
项目:oscm    文件:MigrationBillingResultSteppedPrices.java   
protected String migrateBillingResultXml(String billingXml)
        throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, TransformerException {

    // create a document from the xml file
    Document document = XMLConverter.convertToDocument(billingXml, false);

    // iterate over all stepped prices elements, if any
    NodeList steppedPrices = XMLConverter.getNodeListByXPath(document,
            XPATH_STEPPEDPRICES);
    for (int i = 0; i < steppedPrices.getLength(); i++) {
        Node steppedPricesElement = steppedPrices.item(i);

        // proceed only if amount attribute is not present
        if (!isAmountAttributeAlreadyPresent(steppedPricesElement)) {
            long value = getValue(steppedPricesElement);
            StepData relevantStep = getStepData(steppedPricesElement, value);
            BigDecimal price = calculateStepPrice(relevantStep);
            createAttribute(steppedPricesElement, price);
        }
    }

    return XMLConverter.convertToString(document, false);
}
项目:hashsdn-controller    文件:DataStoreAppConfigDefaultXMLReader.java   
@SuppressWarnings("unchecked")
public T createDefaultInstance(final FallbackConfigProvider fallback) throws ConfigXMLReaderException,
        URISyntaxException, ParserConfigurationException, XMLStreamException, SAXException, IOException {
    YangInstanceIdentifier yangPath = bindingSerializer.toYangInstanceIdentifier(bindingContext.appConfigPath);

    LOG.debug("{}: Creating app config instance from path {}, Qname: {}", logName, yangPath,
            bindingContext.bindingQName);

    checkNotNull(schemaService, "%s: Could not obtain the SchemaService OSGi service", logName);

    SchemaContext schemaContext = schemaService.getGlobalContext();

    Module module = schemaContext.findModuleByNamespaceAndRevision(bindingContext.bindingQName.getNamespace(),
            bindingContext.bindingQName.getRevision());
    checkNotNull(module, "%s: Could not obtain the module schema for namespace %s, revision %s",
            logName, bindingContext.bindingQName.getNamespace(), bindingContext.bindingQName.getRevision());

    DataSchemaNode dataSchema = module.getDataChildByName(bindingContext.bindingQName);
    checkNotNull(dataSchema, "%s: Could not obtain the schema for %s", logName, bindingContext.bindingQName);

    checkCondition(bindingContext.schemaType.isAssignableFrom(dataSchema.getClass()),
            "%s: Expected schema type %s for %s but actual type is %s", logName,
            bindingContext.schemaType, bindingContext.bindingQName, dataSchema.getClass());

    NormalizedNode<?, ?> dataNode = parsePossibleDefaultAppConfigXMLFile(schemaContext, dataSchema);
    if (dataNode == null) {
        dataNode = fallback.get(schemaService.getGlobalContext(), dataSchema);
    }

    DataObject appConfig = bindingSerializer.fromNormalizedNode(yangPath, dataNode).getValue();

    // This shouldn't happen but need to handle it in case...
    checkNotNull(appConfig, "%s: Could not create instance for app config binding %s", logName,
            bindingContext.appConfigBindingClass);

    return (T) appConfig;
}
项目:javaide    文件:XmlLoader.java   
/**
 * Loads a xml document from its {@link String} representation without doing xml validation and
 * return a {@link XmlDocument}
 * @param sourceLocation the source location to use for logging and record collection.
 * @param xml the persisted xml.
 * @return the initialized {@link XmlDocument}
 * @throws IOException this should never be thrown.
 * @throws SAXException if the xml is incorrect
 * @throws ParserConfigurationException if the xml engine cannot be configured.
 */
public static XmlDocument load(
        KeyResolver<String> selectors,
        KeyBasedValueResolver<SystemProperty> systemPropertyResolver,
        SourceLocation sourceLocation,
        String xml,
        XmlDocument.Type type,
        Optional<String> mainManifestPackageName)
        throws IOException, SAXException, ParserConfigurationException {
    PositionXmlParser positionXmlParser = new PositionXmlParser();
    Document domDocument = positionXmlParser.parse(xml);
    return domDocument != null
            ? new XmlDocument(
                    positionXmlParser,
                    sourceLocation,
                    selectors,
                    systemPropertyResolver,
                    domDocument.getDocumentElement(),
                    type,
                    mainManifestPackageName)
            : null;
}
项目:DIA-Umpire-Maven    文件:DIAPack.java   
private void MS1PeakDetection() throws SQLException, InterruptedException, ExecutionException, IOException, ParserConfigurationException, SAXException, FileNotFoundException, Exception {
    //Remove existing pseudo MS/MS MGF files
    RemoveMGF();

    MS1FeatureMap = new LCMSPeakMS1(Filename, NoCPUs);
    MS1FeatureMap.datattype = dIA_Setting.dataType;
    MS1FeatureMap.SetParameter(parameter);
    MS1FeatureMap.Resume = Resume;
    //Assign MS1 feature maps
    MS1FeatureMap.SetMS1Windows(dIA_Setting.MS1Windows);
    MS1FeatureMap.CreatePeakFolder();
    MS1FeatureMap.ExportPeakCurveTable = false;

    MS1FeatureMap.SetSpectrumParser(GetSpectrumParser());
    Logger.getRootLogger().info("Processing MS1 peak detection");
    MS1FeatureMap.ExportPeakClusterTable = ExportPrecursorPeak;
    //Start MS1 feature detection
    MS1FeatureMap.PeakClusterDetection();

    Logger.getRootLogger().info("==================================================================================");
}
项目:AndroidApktool    文件:ResXmlPatcher.java   
/**
 * Removes "debug" tag from file
 *
 * @param file AndroidManifest file
 * @throws AndrolibException
 */
public static void removeApplicationDebugTag(File file) throws AndrolibException {
    if (file.exists()) {
        try {
            Document doc = loadDocument(file);
            Node application = doc.getElementsByTagName("application").item(0);

            // load attr
            NamedNodeMap attr = application.getAttributes();
            Node debugAttr = attr.getNamedItem("android:debuggable");

            // remove application:debuggable
            if (debugAttr != null) {
                attr.removeNamedItem("android:debuggable");
            }

            saveDocument(file, doc);

        } catch (SAXException | ParserConfigurationException | IOException | TransformerException ignored) {
        }
    }
}
项目:openjdk-jdk10    文件:XPathImplUtil.java   
/**
 * Parse the input source and return a Document.
 * @param source The {@code InputSource} of the document
 * @return a DOM Document
 * @throws XPathExpressionException if there is an error parsing the source.
 */
Document getDocument(InputSource source)
    throws XPathExpressionException {
    requireNonNull(source, "Source");
    try {
        // we'd really like to cache those DocumentBuilders, but we can't because:
        // 1. thread safety. parsers are not thread-safe, so at least
        //    we need one instance per a thread.
        // 2. parsers are non-reentrant, so now we are looking at having a
        // pool of parsers.
        // 3. then the class loading issue. The look-up procedure of
        //    DocumentBuilderFactory.newInstance() depends on context class loader
        //    and system properties, which may change during the execution of JVM.
        //
        // so we really have to create a fresh DocumentBuilder every time we need one
        // - KK
        DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(useServiceMechanism);
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        return dbf.newDocumentBuilder().parse(source);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new XPathExpressionException (e);
    }
}
项目:OpenJSharp    文件:ExsltStrings.java   
/**
* @return an instance of DOM Document
  */
private static Document getDocument()
{
     try
     {
         if (System.getSecurityManager() == null) {
             return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
         } else {
             return DocumentBuilderFactory.newInstance(JDK_DEFAULT_DOM, null).newDocumentBuilder().newDocument();
         }
     }
     catch(ParserConfigurationException pce)
     {
         throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(pce);
     }
 }
项目:openjdk-jdk10    文件:Parser.java   
private XMLReader createReader() throws SAXException {
    try {
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setValidating(true);
        pfactory.setNamespaceAware(true);

        // Enable schema validation
        SchemaFactory sfactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        InputStream stream = Parser.class.getResourceAsStream("graphdocument.xsd");
        pfactory.setSchema(sfactory.newSchema(new Source[]{new StreamSource(stream)}));

        return pfactory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException ex) {
        throw new SAXException(ex);
    }
}
项目:eSaskaita    文件:AbstractSignatureHelper.java   
@Test
public void signRequest() throws JAXBException, ParserConfigurationException, CertificateException, KeyException, MarshalException, NoSuchAlgorithmException, SOAPException, XPathExpressionException, XMLSignatureException, InvalidAlgorithmParameterException, java.security.cert.CertificateException, NoSuchProviderException, KeyStoreException, IOException, UnrecoverableKeyException {
    Serializable payload = createRequest();

    SOAPMessage signedRequest = sign(
            marshall(
                    payload,
                    getMarshaller(payload.getClass())
            ),
            getClient()
    );

    System.out.println("============ SIGNED SOAP MESSAGE ================");
    signedRequest.writeTo(System.out);
    System.out.println("\n=================================================");
}
项目:https-github.com-hyb1996-NoRootScriptDroid    文件:XmlConverter.java   
public static String convertToAndroidLayout(InputSource source) throws ParserConfigurationException, IOException, SAXException {
    StringBuilder layoutXml = new StringBuilder();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(source);
    handleNode(document.getFirstChild(), "xmlns:android=\"http://schemas.android.com/apk/res/android\"", layoutXml);
    return layoutXml.toString();
}
项目:cyberduck    文件:DictionaryLicense.java   
private NSDictionary read(final Local file) {
    try {
        return (NSDictionary) XMLPropertyListParser.parse(file.getInputStream());
    }
    catch(ParserConfigurationException
            | IOException
            | SAXException
            | PropertyListFormatException
            | ParseException
            | AccessDeniedException e) {
        log.warn(String.format("Failure %s reading dictionary from %s", e.getMessage(), file));
    }
    return null;
}
项目:s-store    文件:JDBCSQLXML.java   
/**
 * <p>Creates a new instance of SAX2DOMBuilder, which creates
 * a new document. The document is available via
 * {@link #getDocument()}.</p>
 * @throws javax.xml.parsers.ParserConfigurationException
 */
public SAX2DOMBuilder() throws ParserConfigurationException {

    DocumentBuilderFactory documentBuilderFactory;
    DocumentBuilder        documentBuilder;

    documentBuilderFactory = DocumentBuilderFactory.newInstance();

    documentBuilderFactory.setValidating(false);
    documentBuilderFactory.setNamespaceAware(true);

    documentBuilder  = documentBuilderFactory.newDocumentBuilder();
    this.document    = documentBuilder.newDocument();
    this.currentNode = this.document;
}
项目:OpenJSharp    文件:ParserPool.java   
public SAXParser get() throws ParserConfigurationException,
            SAXException {

    try {
        return (SAXParser) queue.take();
    } catch (InterruptedException ex) {
        throw new SAXException(ex);
    }

}
项目:wrdocletbase    文件:DubboDocBuilder.java   
/**
 * @param dubboConfigFilePath
 * @return HashMap, key protocol id, value "dubbo" or "http"
    */
protected static HashMap<String, String> getDubboProtocols(String dubboConfigFilePath) throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
    HashMap<String, String> result = new HashMap<>();
    if(!StringUtils.isEmpty(dubboConfigFilePath)) {
        Document dubboConfig = readXMLConfig(dubboConfigFilePath);
        XPath xPath = XPathFactory.newInstance().newXPath();
        xPath.setNamespaceContext(new UniversalNamespaceCache(dubboConfig,
                false));
        NodeList serviceNodes = (NodeList) xPath.evaluate(
                "//:beans/dubbo:protocol", dubboConfig,
                XPathConstants.NODESET);
        for (int i = 0; i < serviceNodes.getLength(); i++) {
            Node node = serviceNodes.item(i);
            String id = getAttributeValue(node, "id");
            String name = getAttributeValue(node, "name");
            String server = getAttributeValue(node, "server");
            if(StringUtils.isEmpty(id)) {
                id = name;
            }
            if("servlet".equalsIgnoreCase(server) || "jetty".equalsIgnoreCase(server)) {
                result.put(id, "http");
            } else {
                result.put(id, "dubbo");
            }
        }
    }
    return result;
}
项目:azeroth    文件:XLSX2CSV.java   
/**
 * Parses and shows the content of one sheet using the specified styles and
 * shared-strings tables.
 *
 * @param styles
 * @param strings
 * @param sheetInputStream
 */
public void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, SheetContentsHandler sheetHandler,
                         InputStream sheetInputStream) throws IOException, ParserConfigurationException, SAXException {
    DataFormatter formatter = new DataFormatter();
    InputSource sheetSource = new InputSource(sheetInputStream);
    try {
        XMLReader sheetParser = SAXHelper.newXMLReader();
        ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, sheetHandler, formatter, false);
        sheetParser.setContentHandler(handler);
        sheetParser.parse(sheetSource);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
    }
}
项目:LibScout    文件:LibraryProfiler.java   
public LibraryProfiler(File libraryFile, File libDescriptionFile) throws ParserConfigurationException, SAXException, IOException, ParseException {
    this.libraryFile = libraryFile;

    // read library description
    libDesc = XMLParser.readLibraryXML(libDescriptionFile);

    // set identifier for logging
    String logIdentifier = CliOptions.logDir.getAbsolutePath() + File.separator;
    logIdentifier += libDesc.name.replaceAll(" ", "-") + "_" + libDesc.version;

    MDC.put("appPath", logIdentifier);
}
项目:oscm    文件:SupplierPaymentReport.java   
/**
 * Creates the supplier payment result report containing the status of the
 * interactions (debiting processes) of BES with the payment service
 * provider.
 */
public void buildReport(long supplierKey, VOReportResult result)
        throws XPathExpressionException, ParserConfigurationException {
    result.setServerTimeZone(DateConverter.getCurrentTimeZoneAsUTCString());

    List<ReportResultData> reportData = paymentDao
            .retrievePaymentInformationData(supplierKey);
    ReportDataConverter converter = new ReportDataConverter(subscriptionDao);
    Map<String, String> columnXPathMap = new HashMap<String, String>();
    columnXPathMap.put("processingresult",
            "/Response/Transaction/Processing/Return/text()");
    converter.convertToXml(reportData, result.getData(), columnXPathMap);
}
项目:ChronoBike    文件:XMLMerger.java   
public XMLMerger(OnlineSession appSession)
{
    m_AppSession = appSession ;
    m_tab = new Hashtable<String, Element>() ;
    try
    {
        m_docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    }
    catch (ParserConfigurationException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
项目:parsel    文件:Utils.java   
public static DocumentBuilder getDocumentBuilder() {
    try {
        return DocumentBuilderFactory.newInstance().newDocumentBuilder();
    } catch(ParserConfigurationException e) {
        LOG.severe(e.getMessage());
    }
    return null;
}
项目:alvisnlp    文件:XMLReader.java   
private void processFile(ProcessingContext<Corpus> ctx, Logger logger, Corpus corpus, InputStream file, Transformer transformer) throws ModuleException, IOException {
    try {
        String name = sourcePath.getStreamName(file);
        logger.finer("reading: " + name);
        transformer.reset();
        transformer.setParameter(SOURCE_PATH_PARAMETER, name);
        transformer.setParameter(SOURCE_BASENAME_PARAMETER, new File(name).getName());
        transformer.setParameter(XML_READER_CONTEXT_PARAMETER, new XMLReaderContext(this, corpus));
        Source source = getSource(ctx, file);
        doTransform(ctx, transformer, source);
    }
    catch (TransformerException|SAXException|ParserConfigurationException e) {
        rethrow(e);
    }
}
项目:openjdk-jdk10    文件:DOMForest.java   
public DOMForest( InternalizationLogic logic, Options opt ) {

        if (opt == null) throw new AssertionError("Options object null");
        this.options = opt;

        try {
            DocumentBuilderFactory dbf = XmlFactory.createDocumentBuilderFactory(opt.disableXmlSecurity);
            this.documentBuilder = dbf.newDocumentBuilder();
            this.parserFactory = XmlFactory.createParserFactory(opt.disableXmlSecurity);
        } catch( ParserConfigurationException e ) {
            throw new AssertionError(e);
        }

        this.logic = logic;
    }
项目:nfse    文件:AssinaturaDigital.java   
private Document documentFactory(String xml)
    throws SAXException, IOException, ParserConfigurationException {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  Document document =
      factory.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
  return document;
}
项目:GitJourney    文件:WidgetDataAtomParser.java   
@Override
public List<GitHubJourneyWidgetDataEntry> parse(String url) throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilder builder = dBFactory.newDocumentBuilder();
    Document xmlDoc = builder.parse(url);
    NodeList nodeList = xmlDoc.getElementsByTagName("entry");

    List<GitHubJourneyWidgetDataEntry> dataEntriesList = new ArrayList<>(nodeList.getLength());
    for (int i = 0; i < nodeList.getLength(); i++) {
        GitHubJourneyWidgetDataEntry entry = parseItem((Element) nodeList.item(i));
        dataEntriesList.add(entry);
    }
    return dataEntriesList;
}
项目:pgsqlblocks    文件:DBController.java   
private void saveBlockedProcessesToFile(List<DBBlocksJournalProcess> processes) throws ParserConfigurationException, IOException, SAXException {

        String fileName = String.format("%s-%s.xml", this.model.getName(), dateUtils.dateToString(blocksJournalCreateDate));
        Path blocksJournalsDirPath = PathBuilder.getInstance().getBlocksJournalsDir();
        Path currentJournalPath = Paths.get(blocksJournalsDirPath.toString(), fileName);
        File currentJournalFile = currentJournalPath.toFile();

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        boolean fileExists = currentJournalFile.exists();
        Document document;
        Element rootElement;
        if (fileExists) {
            document = documentBuilder.parse(currentJournalFile);
            rootElement = document.getDocumentElement();
        } else {
            document = documentBuilder.newDocument();
            rootElement = document.createElement("blocksJournal");
        }
        DBBlocksJournalProcessSerializer serializer = new DBBlocksJournalProcessSerializer();
        processes.forEach(journalProcess -> {
            Element el = serializer.serialize(document, journalProcess);
            rootElement.appendChild(el);
        });
        if (!fileExists) {
            document.appendChild(rootElement);
        }
        XmlDocumentWorker documentWorker = new XmlDocumentWorker();
        documentWorker.save(document, currentJournalFile);
    }
项目:oscm    文件:PortLocatorBean.java   
@Override
public PaymentServiceProviderAdapter getPort(String wsdl)
        throws IOException, WSDLException, ParserConfigurationException {

    WSPortConnector portConnector = new WSPortConnector(wsdl, null, null);

    SupportedVersions supportedNS = getSupportedVersion(portConnector);
    PaymentServiceProviderAdapter adapter = getAdapterForNamespace(supportedNS);

    final Object port = portConnector.getPort(supportedNS.getLocalWSDL(),
            supportedNS.getServiceClass(), timeout);
    adapter.setPaymentServiceProviderService(port);

    return adapter;
}
项目:openjdk-jdk10    文件:Sources.java   
/**
 * Returns an instance of XMLReader.
 *
 * @return an instance of XMLReader.
 */
private XMLReader getXMLReader() {
    XMLReader reader = null;
    try {
        reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    } catch (ParserConfigurationException | SAXException ex) {}
    return reader;
}