Example usage for javax.xml.parsers DocumentBuilderFactory setValidating

List of usage examples for javax.xml.parsers DocumentBuilderFactory setValidating

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setValidating.

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:de.interactive_instruments.ShapeChange.Target.ReplicationSchema.ReplicationXmlSchema.java

@Override
public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly)
        throws ShapeChangeAbortException {

    schemaPi = p;/*from w  w w . ja va 2s.c  o m*/
    model = m;
    options = o;
    result = r;
    diagnosticsOnly = diagOnly;

    result.addDebug(this, 1, schemaPi.name());

    outputDirectory = options.parameter(this.getClass().getName(), "outputDirectory");
    if (outputDirectory == null)
        outputDirectory = options.parameter("outputDirectory");
    if (outputDirectory == null)
        outputDirectory = options.parameter(".");

    outputFilename = schemaPi.name().replace("/", "_").replace(" ", "_") + ".xsd";

    // Check if we can use the output directory; create it if it
    // does not exist
    outputDirectoryFile = new File(outputDirectory);
    boolean exi = outputDirectoryFile.exists();
    if (!exi) {
        try {
            FileUtils.forceMkdir(outputDirectoryFile);
        } catch (IOException e) {
            result.addError(null, 600, e.getMessage());
            e.printStackTrace(System.err);
        }
        exi = outputDirectoryFile.exists();
    }
    boolean dir = outputDirectoryFile.isDirectory();
    boolean wrt = outputDirectoryFile.canWrite();
    boolean rea = outputDirectoryFile.canRead();
    if (!exi || !dir || !wrt || !rea) {
        result.addFatalError(null, 601, outputDirectory);
        throw new ShapeChangeAbortException();
    }

    File outputFile = new File(outputDirectoryFile, outputFilename);

    // check if output file already exists - if so, attempt to delete it
    exi = outputFile.exists();
    if (exi) {

        result.addInfo(this, 3, outputFilename, outputDirectory);

        try {
            FileUtils.forceDelete(outputFile);
            result.addInfo(this, 4);
        } catch (IOException e) {
            result.addInfo(null, 600, e.getMessage());
            e.printStackTrace(System.err);
        }
    }

    // identify map entries defined in the target configuration
    List<ProcessMapEntry> mapEntries = options.getCurrentProcessConfig().getMapEntries();

    if (mapEntries == null || mapEntries.isEmpty()) {

        result.addFatalError(this, 9);
        throw new ShapeChangeAbortException();

    } else {

        for (ProcessMapEntry pme : mapEntries) {
            this.mapEntryByType.put(pme.getType(), pme);
        }
    }

    // reset processed flags on all classes in the schema
    for (Iterator<ClassInfo> k = model.classes(schemaPi).iterator(); k.hasNext();) {
        ClassInfo ci = k.next();
        ci.processed(getTargetID(), false);
    }

    // ======================================
    // Parse configuration parameters
    // ======================================

    objectIdentifierFieldName = options.parameter(this.getClass().getName(),
            PARAM_OBJECT_IDENTIFIER_FIELD_NAME);
    if (objectIdentifierFieldName == null || objectIdentifierFieldName.trim().length() == 0) {
        objectIdentifierFieldName = DEFAULT_OBJECT_IDENTIFIER_FIELD_NAME;
    }

    suffixForPropWithFeatureValueType = options.parameter(this.getClass().getName(),
            PARAM_SUFFIX_FOR_PROPERTIES_WITH_FEATURE_VALUE_TYPE);
    if (suffixForPropWithFeatureValueType == null || suffixForPropWithFeatureValueType.trim().length() == 0) {
        suffixForPropWithFeatureValueType = "";
    }

    suffixForPropWithObjectValueType = options.parameter(this.getClass().getName(),
            PARAM_SUFFIX_FOR_PROPERTIES_WITH_OBJECT_VALUE_TYPE);
    if (suffixForPropWithObjectValueType == null || suffixForPropWithObjectValueType.trim().length() == 0) {
        suffixForPropWithObjectValueType = "";
    }

    targetNamespaceSuffix = options.parameter(this.getClass().getName(), PARAM_TARGET_NAMESPACE_SUFFIX);
    if (targetNamespaceSuffix == null || objectIdentifierFieldName.trim().length() == 0) {
        targetNamespaceSuffix = "";
    }

    String defaultSizeByConfig = options.parameter(this.getClass().getName(), PARAM_SIZE);
    if (defaultSizeByConfig != null) {
        try {
            defaultSize = Integer.parseInt(defaultSizeByConfig);
        } catch (NumberFormatException e) {
            MessageContext mc = result.addWarning(this, 8, PARAM_SIZE, e.getMessage());
            mc.addDetail(this, 0);
        }
    }

    // ======================================
    // Set up the document and create root
    // ======================================

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(Options.JAXP_SCHEMA_LANGUAGE, Options.W3C_XML_SCHEMA);
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        result.addFatalError(null, 2);
        throw new ShapeChangeAbortException();
    }
    document = db.newDocument();

    root = document.createElementNS(Options.W3C_XML_SCHEMA, "schema");
    document.appendChild(root);

    addAttribute(root, "xmlns", Options.W3C_XML_SCHEMA);
    addAttribute(root, "elementFormDefault", "qualified");

    addAttribute(root, "version", schemaPi.version());
    targetNamespace = schemaPi.targetNamespace() + targetNamespaceSuffix;
    addAttribute(root, "targetNamespace", targetNamespace);
    addAttribute(root, "xmlns:" + schemaPi.xmlns(), targetNamespace);

    hook = document.createComment("XML Schema document created by ShapeChange - http://shapechange.net/");
    root.appendChild(hook);
}

From source file:de.interactive_instruments.ShapeChange.ShapeChangeResult.java

public ShapeChangeResult(Options o) {
    init();//from w ww.  ja  va2s .com

    options = o;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setAttribute(Options.JAXP_SCHEMA_LANGUAGE, Options.W3C_XML_SCHEMA);
        DocumentBuilder db = dbf.newDocumentBuilder();
        document = db.newDocument();

        root = document.createElementNS(Options.SCRS_NS, "ShapeChangeResult");
        document.appendChild(root);
        root.setAttribute("resultCode", "0");
        root.setAttribute("xmlns:r", Options.SCRS_NS);
        root.setAttribute("start", (new Date()).toString());

        String version = "[dev]";
        InputStream stream = getClass().getResourceAsStream("/sc.properties");
        if (stream != null) {
            Properties properties = new Properties();
            properties.load(stream);
            version = properties.getProperty("sc.version");
        }
        root.setAttribute("version", version);

        messages = document.createElementNS(Options.SCRS_NS, "Messages");
        root.appendChild(messages);

        resultFiles = document.createElementNS(Options.SCRS_NS, "Results");
        root.appendChild(resultFiles);
    } catch (ParserConfigurationException e) {
        System.err.println("Bootstrap Error: XML parser was unable to be configured.");
        String m = e.getMessage();
        if (m != null) {
            System.err.println(m);
        }
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (Exception e) {
        System.err.println("Bootstrap Error: " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(1);
    }

    outputFormat.setProperty("encoding", "UTF-8");
    outputFormat.setProperty("indent", "yes");
    outputFormat.setProperty("{http://xml.apache.org/xalan}indent-amount", "2");
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java

private Document createKBDescribeLayerResponse(DataWrapper dw, List<DescribeLayerData> describeLayerData)
        throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    dbf.setNamespaceAware(true);/*from w ww.ja  v a  2s .  co  m*/
    DocumentBuilder db = dbf.newDocumentBuilder();
    DOMImplementation di = db.getDOMImplementation();

    // <!DOCTYPE WMS_DescribeLayerResponse SYSTEM "http://schemas.opengis.net/wms/1.1.1/WMS_DescribeLayerResponse.dtd">
    // [ <WMS_DescribeLayerResponse version="1.1.1" > (...) </WMS_DescribeLayerResponse>]        
    DocumentType dt = di.createDocumentType("WMS_DescribeLayerResponse", null,
            CallWMSServlet.DESCRIBELAYER_DTD);
    Document dom = di.createDocument(null, "WMS_DescribeLayerResponse", dt);
    Element rootElement = dom.getDocumentElement();
    rootElement.setAttribute("version", "1.1.1"); //describeLayer version in kbconfig?

    String spAbbrUrl = dw.getOgcrequest().getServiceProviderName();

    String personalUrl = this.user.getPersonalURL(dw.getRequest(), spAbbrUrl);

    Integer[] orgIds = this.user.getOrganizationIds();

    WFSProviderDAO wfsProviderDao = new WFSProviderDAO();
    String[] validLayerNames = wfsProviderDao.getAuthorizedFeatureTypeNames(orgIds, null, false);
    //it is not possible to use getSeviceProviderURLS because that will call getValidObjects implementation of WMSRequestHandler
    //therefore build spInfo here in loop
    //also, B3PLayering is not relevant here, because describeLayer should not be subject to pricing
    List spInfo = new ArrayList();
    for (String name : validLayerNames) {
        SpLayerSummary layerInfo = wfsProviderDao.getAuthorizedFeatureTypeSummary(name, orgIds, false);
        if (layerInfo == null) {
            continue;
        }
        spInfo.add(layerInfo);
    }

    for (DescribeLayerData resp : describeLayerData) {
        for (LayerDescription descr : resp.getDescribeLayerResponse().getLayerDescs()) {
            Element layerDescriptionElement = dom.createElement("LayerDescription");
            if (spAbbrUrl != null && !spAbbrUrl.equals("")) {
                layerDescriptionElement.setAttribute("name", descr.getName());
            } else {
                layerDescriptionElement.setAttribute("name",
                        OGCCommunication.attachSp(resp.getWmsPrefix(), descr.getName()));
            }
            descr.getOwsURL();

            //additional info should only be returned for WMS layer that has corresponding WFS type that is served by Kaartenbalie
            String wfsPrefix = getAuthorizedWFSPrefix(spInfo, descr);
            if (wfsPrefix != null) {
                layerDescriptionElement.setAttribute("wfs", personalUrl);
                layerDescriptionElement.setAttribute("owsType", descr.getOwsType());
                layerDescriptionElement.setAttribute("owsURL", personalUrl);

                Element queryElement = dom.createElement("Query");
                queryElement.setAttribute("typeName", OGCCommunication.attachSp(wfsPrefix, descr.getName()));
                layerDescriptionElement.appendChild(queryElement);
            }
            rootElement.appendChild(layerDescriptionElement);
        }
    }
    return dom;
}

From source file:com.silverwrist.venice.std.TrackbackManager.java

/**
 * Only one instance of this class can/should exist.
 *//*from w ww . jav a  2  s.c  o  m*/
private TrackbackManager() {
    m_page_cache = new HashMap();
    m_item_cache = new HashMap();
    m_end_recognizers = new HashMap();
    m_http_client = new HttpClient();

    try { // create the XML parsers we use
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        fact.setCoalescing(true);
        fact.setExpandEntityReferences(true);
        fact.setIgnoringComments(true);
        fact.setNamespaceAware(true);
        fact.setValidating(false);
        m_rdf_parser = fact.newDocumentBuilder();
        fact.setCoalescing(true);
        fact.setExpandEntityReferences(true);
        fact.setIgnoringComments(true);
        fact.setNamespaceAware(false);
        fact.setValidating(false);
        m_tbresp_parser = fact.newDocumentBuilder();

    } // end try
    catch (ParserConfigurationException e) { // this is bad!
        logger.fatal("XML parser creation failed", e);

    } // end catch

}

From source file:com.edgenius.wiki.installation.UpgradeServiceImpl.java

/**
 * @param root/*from   ww  w  . ja va  2s .co m*/
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
private void mergeCustomizedThemesOnVersion2180(String root)
        throws ParserConfigurationException, SAXException, IOException {

    File rootFile = FileUtil.getFile(root);
    File dir = new File(rootFile, "data/themes/customized");
    if (dir.exists() && dir.isDirectory()) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setCoalescing(true);
        factory.setIgnoringComments(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Map<Integer, List<PageTheme>> map = new HashMap<Integer, List<PageTheme>>();
        File[] files = dir.listFiles((FilenameFilter) FileFilterUtils.suffixFileFilter(".xml"));
        for (File file : files) {
            //get space setting - file.getName();
            //parse customized theme, and get back the 
            List<PageTheme> list = new ArrayList<PageTheme>();
            Document dom = builder.parse(file);
            NodeList elements = dom.getElementsByTagName("com.edgenius.wiki.PageTheme");
            for (int idx = 0; idx < elements.getLength(); idx++) {
                PageTheme pTheme = new PageTheme();
                Node element = elements.item(idx);
                NodeList children = element.getChildNodes();

                for (int idj = 0; idj < children.getLength(); idj++) {
                    String value = children.item(idj).getTextContent();
                    if ("bodyMarkup".equals(children.item(idj).getNodeName())) {
                        pTheme.setBodyMarkup(value);
                    } else if ("sidebarMarkup".equals(children.item(idj).getNodeName())) {
                        pTheme.setSidebarMarkup(value);
                    } else if ("welcome".equals(children.item(idj).getNodeName())) {
                        pTheme.setWelcome(value);
                    } else if ("type".equals(children.item(idj).getNodeName())) {
                        String scope;
                        if ("0".equals(value)) {
                            scope = PageTheme.SCOPE_DEFAULT;
                        } else if ("1".equals(value)) {
                            scope = PageTheme.SCOPE_HOME;
                        } else {
                            scope = value;
                        }
                        pTheme.setScope(scope);
                    }
                }
                list.add(pTheme);
            }
            if (!file.delete()) {
                file.deleteOnExit();
            }
            if (list.size() > 0) {
                int uid = NumberUtils.toInt(file.getName().substring(0, file.getName().length() - 4), -1);
                if (uid != -1) {
                    map.put(uid, list);
                }
            }

        }
        //Convert  <com.edgenius.wiki.PageTheme> to <PageTheme>
        Server server = new Server();
        Properties prop = FileUtil.loadProperties(root + Server.FILE);
        server.syncFrom(prop);
        String type = server.getDbType();

        DBLoader loader = new DBLoader();
        ConnectionProxy conn = null;

        XStream xs = new XStream();
        xs.processAnnotations(PageTheme.class);
        xs.processAnnotations(BlogMeta.class);
        xs.processAnnotations(BlogCategory.class);

        try {
            conn = loader.getConnection(type, server.getDbUrl(), server.getDbSchema(), server.getDbUsername(),
                    server.getDbPassword());
            for (Entry<Integer, List<PageTheme>> entry : map.entrySet()) {
                PreparedStatement stat1 = null, stat2 = null;
                ResultSet rs = null;
                try {
                    stat1 = conn.prepareStatement("select f.PUID, f.SETTING_VALUE,s.PUID  "
                            + "from EDG_CONF as f, EDG_SPACES as s where f.SETTING_TYPE='com.edgenius.wiki.SpaceSetting' "
                            + "and s.CONFIGURATION_PUID=f.PUID and s.PUID=?");
                    stat2 = conn.prepareStatement("update EDG_CONF set SETTING_VALUE=? where PUID=?");
                    stat1.setInt(1, entry.getKey());
                    rs = stat1.executeQuery();
                    if (rs.next()) {
                        int ID = rs.getInt(1);
                        SpaceSetting setting = (SpaceSetting) xs
                                .fromXML(StringUtils.trimToEmpty(rs.getString(2)));
                        setting.setPageThemes(entry.getValue());
                        String content = xs.toXML(setting);
                        //update
                        stat2.setString(1, content);
                        stat2.setInt(2, ID);
                        stat2.executeUpdate();
                        log.info("Update space setting  {} for page theme ", ID);
                    }
                } catch (Exception e) {
                    log.error("Update space setting failed " + entry.getKey(), e);
                } finally {
                    if (rs != null)
                        rs.close();
                    if (stat1 != null)
                        stat1.close();
                    if (stat2 != null)
                        stat2.close();
                }
            }
        } catch (Exception e) {
            log.error("update space setting failed with PageTheme", e);
        } finally {
            if (conn != null)
                conn.close();
        }

        //delete unnecessary files
        File f1 = new File(rootFile, "data/themes/defaultwiki.xml");
        f1.delete();
        File f2 = new File(rootFile, "data/themes/defaultblog.xml");
        f2.delete();
        File f3 = new File(rootFile, "data/themes/customized");
        if (f3.isDirectory() && f3.list().length == 0) {
            f3.delete();
        }

    } else {
        log.error("Unable to parse out theme directory {}", (root + "data/themes/customized"));
    }
}

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to parse the InkML string markup data identified by the inkmlStr given
 * // w w w . ja v  a 2 s.  co  m
 * @param inkmlStr String markup data
 * @throws InkMLException
 */
public void parseInkMLString(final String inkmlStrParam) throws InkMLException {
    final String inkmlStr;
    if (inkmlStrParam.indexOf("ink") == -1) {
        // the given welformed inkmlStr does not contain complete <ink> document as string.
        // wrap it with a false root element, <inkMLFramgment>. It is called as fragment.
        inkmlStr = "<inkMLFramgment>" + inkmlStrParam + " </inkMLFramgment>";
    } else {
        inkmlStr = inkmlStrParam;
    }
    InkMLDOMParser.LOG.fine(inkmlStr);

    try {
        final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setIgnoringComments(true);
        dbFactory.setIgnoringElementContentWhitespace(true);
        dbFactory.setValidating(false);
        InkMLDOMParser.LOG.info("Validation using schema is disabled.");
        final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        this.inkmlDOMDocument = dBuilder.parse(inkmlStr);
        this.bindData(this.inkMLProcessor.getInk());
    } catch (final ParserConfigurationException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final SAXException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final IOException e) {
        throw new InkMLException("I/O error while parsing Input InkML XML file.\n Message: " + e.getMessage(),
                e);
    }
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java

/**
 * Gets the data from a specific set of URL's and converts the information
 * to the format usefull to the REQUEST_TYPE. Once the information is
 * collected and converted the method calls for a write in the DataWrapper,
 * which will sent the data to the client requested for this information.
 *
 * @param dw DataWrapper object containing the clients request information
 * @param urls StringBuffer with the urls where kaartenbalie should connect
 * to to recieve the requested data.//  w w w  .  j a  v a2 s. c  o m
 * @param overlay A boolean setting the overlay to true or false. If false
 * is chosen the images are placed under eachother.
 *
 * @return byte[]
 *
 * @throws Exception
 */
protected void getOnlineData(DataWrapper dw, ArrayList urlWrapper, boolean overlay, String REQUEST_TYPE)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedImage[] bi = null;

    //The list is given in the opposit ranking. Therefore we first need to swap the list.
    int size = urlWrapper.size();
    ArrayList swaplist = new ArrayList(size);
    for (int i = size - 1; i >= 0; i--) {
        swaplist.add(urlWrapper.get(i));
        log.debug("Outgoing url: " + ((ServiceProviderRequest) urlWrapper.get(i)).getProviderRequestURI());
    }
    urlWrapper = swaplist;

    /* To save time, this method checks first if the ArrayList contains more then one url
     * If it contains only one url then the method doesn't have to load the image into the G2D
     * environment, which saves a lot of time and capacity because it doesn't have to decode
     * and recode the image.
     */
    long startprocestime = System.currentTimeMillis();

    DataMonitoring rr = dw.getRequestReporting();
    if (urlWrapper.size() > 1) {
        if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetMap)) {
            /*
             * Log the time in ms from the start of the clientrequest.. (Reporting)
             */
            Operation o = new Operation();
            o.setType(Operation.SERVER_TRANSFER);
            o.setMsSinceRequestStart(new Long(rr.getMSSinceStart()));

            ImageManager imagemanager = new ImageManager(urlWrapper, dw);
            imagemanager.process();
            long endprocestime = System.currentTimeMillis();
            Long time = new Long(endprocestime - startprocestime);
            dw.setHeader("X-Kaartenbalie-ImageServerResponseTime", time.toString());

            o.setDuration(time);
            rr.addRequestOperation(o);

            imagemanager.sendCombinedImages(dw);
        } else if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetFeatureInfo)) {

            /*
             * Create a DOM document and copy all the information of the several GetFeatureInfo
             * responses into one document. This document has the same layout as the received
             * documents and will hold all the information of the specified objects.
             * After combining these documents, the new document will be sent onto the request.
             */
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setValidating(false);
            dbf.setNamespaceAware(true);
            dbf.setIgnoringElementContentWhitespace(true);

            DocumentBuilder builder = dbf.newDocumentBuilder();
            Document destination = builder.newDocument();
            Element rootElement = destination.createElement("msGMLOutput");
            destination.appendChild(rootElement);
            rootElement.setAttribute("xmlns:gml", "http://www.opengis.net/gml");
            rootElement.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
            rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            Document source = null;
            for (int i = 0; i < urlWrapper.size(); i++) {
                ServiceProviderRequest wmsRequest = (ServiceProviderRequest) urlWrapper.get(i);
                String url = wmsRequest.getProviderRequestURI();
                // code below could be used to get bytes received
                //InputStream is = new URL(url).openStream();
                //CountingInputStream cis = new CountingInputStream(is);
                //source = builder.parse(cis);
                source = builder.parse(url); //what if url points to non MapServer service?
                copyElements(source, destination);

                wmsRequest.setBytesSent(new Long(url.getBytes().length));
                wmsRequest.setProviderRequestURI(url);
                wmsRequest.setMsSinceRequestStart(new Long(rr.getMSSinceStart()));
                wmsRequest.setBytesReceived(new Long(-1));
                //wmsRequest.setBytesReceived(new Long(cis.getByteCount()));
                wmsRequest.setResponseStatus(new Integer(-1));
                rr.addServiceProviderRequest(wmsRequest);
            }

            OutputFormat format = new OutputFormat(destination);
            format.setIndenting(true);
            XMLSerializer serializer = new XMLSerializer(baos, format);
            serializer.serialize(destination);
            dw.write(baos);
        } else if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_DescribeLayer)) {

            //TODO: implement and refactor so there is less code duplication with getFeatureInfo
            /*
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              dbf.setValidating(false);
              dbf.setNamespaceAware(true);
              dbf.setIgnoringElementContentWhitespace(true);
                    
              DocumentBuilder builder = dbf.newDocumentBuilder();
              Document destination = builder.newDocument();
                     
              //root element is different
              Element rootElement = destination.createElement("WMS_DescribeLayerResponse");
              destination.appendChild(rootElement);
              //set version attribute
              Document source = null;
              for (int i = 0; i < urlWrapper.size(); i++) {
              ServiceProviderRequest dlRequest = (ServiceProviderRequest) urlWrapper.get(i);
              String url = dlRequest.getProviderRequestURI();
              source = builder.parse(url);
              copyElements(source,destination);
              }*/

            throw new Exception(REQUEST_TYPE + " request with more then one service url is not supported yet!");
        }

    } else {
        //urlWrapper not > 1, so only 1 url or zero urls
        if (!urlWrapper.isEmpty()) {
            getOnlineData(dw, (ServiceProviderRequest) urlWrapper.get(0), REQUEST_TYPE);
        } else {
            if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetFeatureInfo)) {
                log.error(KBConfiguration.FEATUREINFO_EXCEPTION);
                throw new Exception(KBConfiguration.FEATUREINFO_EXCEPTION);
            } else if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetLegendGraphic)) {
                log.error(KBConfiguration.LEGENDGRAPHIC_EXCEPTION);
                throw new Exception(KBConfiguration.LEGENDGRAPHIC_EXCEPTION);
            }
        }
    }
}

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to parse the InkML file identified by the inkmlFilename given in the parameter and creates data objects. It performs validation with schema. It
 * must have "ink" as root element with InkML name space specified with xmlns="http://www.w3.org/2003/InkML". The schema location may be specified. If it is
 * not specified or if relative path of the InkML.xsd file is specified, then the InkML.xsd file path must be added to * CLASSPATH for the parser to locate
 * it. An example of a typical header is, <ink xmlns="http://www.w3.org/2003/InkML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 * xsi:schemaLocation="http://www.w3.org/2003/InkML C:\project\schema\inkml.xsd">
 * //from  w w  w  . j  a v a 2  s.c  om
 * @param inkmlFileName
 * @throws InkMLException
 */
public void parseInkMLFile(final InputStream inputStream) throws InkMLException {

    // Get the DOM document object by parsing the InkML input file
    try {
        final InputSource input = new InputSource(inputStream);

        // get the DOM document object of the input InkML XML file.
        final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setIgnoringComments(true);
        dbFactory.setNamespaceAware(true);
        dbFactory.setIgnoringElementContentWhitespace(true);
        dbFactory.setValidating(false);
        if (this.isSchemaValidationEnabled()) {
            InkMLDOMParser.LOG.info("Validation using schema is enabled.");
            dbFactory.setSchema(this.schemaFactory
                    .newSchema(new StreamSource(this.getClass().getResourceAsStream("/schema/inkml.xsd"))));
        } else {
            InkMLDOMParser.LOG.info("Validation using schema is disabled.");
        }
        final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        dBuilder.setErrorHandler(this);
        this.inkmlDOMDocument = dBuilder.parse(input);
        InkMLDOMParser.LOG.info("\nInput InkML XML file parsing is completed.\n");
        this.inkMLProcessor.beginInkSession();
        this.bindData(this.inkMLProcessor.getInk());
    } catch (final ParserConfigurationException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final SAXException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final IOException e) {
        throw new InkMLException("I/O error while parsing Input InkML XML file.\n Message: " + e.getMessage(),
                e);
    }
}

From source file:com.zacwolf.commons.wbxcon.WBXCONorg.java

final private Document executeNonQueued(final List<NameValuePair> params, final int retry)
        throws WBXCONexception {
    Document dom = null;/* w  w w  .  j  av a  2 s . com*/
    try {
        cleanCred(params);
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setCoalescing(true);
        final DocumentBuilder db = factory.newDocumentBuilder();
        final HttpPost httpPost = new HttpPost(this.wapiURL);
        httpPost.setEntity(new UrlEncodedFormEntity(params, org.apache.http.Consts.UTF_8));
        final CloseableHttpResponse httpRes = HTTPSCLIENT.execute(httpPost, new BasicHttpContext());
        try {
            dom = db.parse(httpRes.getEntity().getContent());
        } finally {
            httpRes.close();
        }
    } catch (final SocketException se) {
        if (retry < 3) {//Catches issues with WebEx Connect server connection
            System.err.println("SocketException making wapi call. Retry:" + (retry + 1));
            return executeNonQueued(params, retry + 1);
        } else
            throw new WBXCONexception(se);
    } catch (final Exception e) {
        throw new WBXCONexception(e);
    }
    if (dom != null) {
        final NodeList result = dom.getElementsByTagName("result");
        if (result == null || result.item(0) == null
                || !result.item(0).getTextContent().equalsIgnoreCase("success"))
            throw new WBXCONexception(getMethodName(2) + ": [RESULT]:" + result.item(0).getTextContent()
                    + " [ERROR}:" + documentGetErrorString(dom));
    }
    return dom;
}

From source file:com.zacwolf.commons.wbxcon.WBXCONorg.java

final private Document executeQueued(final List<NameValuePair> params, final int retry) throws WBXCONexception {
    try {//from   ww w  .ja  v  a2  s. c  o  m
        return THREADPOOL.submit(new Callable<Document>() {
            @Override
            public Document call() throws WBXCONexception {
                return getDoc(0);
            }

            private Document getDoc(final int retry) throws WBXCONexception {
                Document dom = null;
                try {
                    cleanCred(params);
                    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    factory.setValidating(false);
                    factory.setCoalescing(true);
                    final DocumentBuilder db = factory.newDocumentBuilder();
                    final HttpPost httpPost = new HttpPost(WBXCONorg.this.wapiURL);
                    httpPost.setEntity(new UrlEncodedFormEntity(params, org.apache.http.Consts.UTF_8));
                    final CloseableHttpResponse httpRes = HTTPSCLIENT.execute(httpPost, new BasicHttpContext());
                    try {
                        dom = db.parse(httpRes.getEntity().getContent());
                    } finally {
                        httpRes.close();
                    }
                } catch (final SocketException se) {
                    if (retry < 3) {//Catches issues with WebEx Connect server connection
                        System.err.println("SocketException making wapi call. Retry:" + (retry + 1));
                        return getDoc(retry + 1);
                    } else
                        throw new WBXCONexception(se);
                } catch (final Exception e) {
                    throw new WBXCONexception(e);
                }
                if (dom != null) {
                    final NodeList result = dom.getElementsByTagName("result");
                    if (result == null || result.item(0) == null
                            || !result.item(0).getTextContent().equalsIgnoreCase("success"))
                        throw new WBXCONexception("executeQueued(" + getParamsAsString(params)
                                + ").getDoc(): [RESULT]:" + result.item(0).getTextContent() + " [ERROR}:"
                                + documentGetErrorString(dom));
                }
                return dom;
            }
        }).get();

    } catch (final Exception e) {
        throw new WBXCONexception(e);
    }
}