Example usage for javax.xml.parsers DocumentBuilderFactory setCoalescing

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

Introduction

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

Prototype


public void setCoalescing(boolean coalescing) 

Source Link

Document

Specifies that the parser produced by this code will convert CDATA nodes to Text nodes and append it to the adjacent (if any) text node.

Usage

From source file:com.edgenius.wiki.rss.RSSServiceImpl.java

/**
 * @param spaceUid// w w w  .ja v a  2s . c  o m
 * @param spaceUname
 * @param viewer
 * @param skipSecurityCheck 
 * @return
 * @throws FeedException
 */
private Document getFeedDom(Integer spaceUid, String spaceUname, User viewer, boolean skipSecurityCheck)
        throws FeedException {
    ReentrantReadWriteLock lock = null;
    Document dom;
    try {

        File feedFile = new File(FileUtil.getFullPath(rssRoot.getFile().getAbsolutePath(), spaceUid + ".xml"));
        if (!feedFile.exists()) {
            createFeed(spaceUname);
        }

        //do read lock! must after createFeed possibility, otherwise, deadlock 
        lock = lockMap.get(spaceUid.toString());
        if (lock == null) {
            lock = new ReentrantReadWriteLock();
            lockMap.put(spaceUid.toString(), lock);
        }
        lock.readLock().lock();
        //!!! DON'T USE JDOM - although I test DOM, JDOM, DOM4J: JDOM is fastest. And DOM and DOM4J almost 2 time slow. But
        //!!! JDOM is not thread safe, an infinite looping can happen while this method reading different XML source, 
        //in different thread, and SAXBuild are different instance! The problem is mostly caused by NameSpace.getNamespace(), 
        //which using static HashMap and cause HashMap dead lock!!!
        DocumentBuilder builder = xmlBuilderPool.poll();
        if (builder == null) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setCoalescing(true);
            factory.setIgnoringComments(true);
            builder = factory.newDocumentBuilder();
        }
        dom = builder.parse(feedFile);
        xmlBuilderPool.add(builder);

    } catch (Exception e) {
        log.error("Unable get feed " + spaceUname + " with excpetion ", e);
        throw new FeedException("Unable get feed " + spaceUname + " with excpetion " + e);
    } finally {
        if (lock != null)
            lock.readLock().unlock();
    }
    if (dom == null) {
        log.error("Unable get feed " + spaceUname);
        throw new FeedException("Unable get feed " + spaceUname);
    }

    //~~~~~~~~~~~~ Security filter
    if (!skipSecurityCheck) {
        //need filter out the page that viewer has not permission to read.  
        List<Node> forbidPageUuidList = new ArrayList<Node>();
        String pageUuid;
        Node ele;
        NodeList list = dom.getElementsByTagName(PageRSSModule.NS_PREFIX + ":" + PageRSSModule.PAGE_UUID);
        int len = list.getLength();
        for (int idx = 0; idx < len; idx++) {
            ele = list.item(idx);
            pageUuid = ele.getTextContent();
            if (!securityService.isAllowPageReading(spaceUname, pageUuid, viewer)) {
                log.info("User " + (viewer == null ? "anonymous" : viewer.getUsername())
                        + "  has not reading permission for pageUuid " + pageUuid + " on space " + spaceUname
                        + ". Feed item of this page is removed from RSS output.");
                forbidPageUuidList.add(ele.getParentNode());
            }

        }
        if (forbidPageUuidList.size() > 0) {
            NodeList cl = dom.getElementsByTagName(PageRSSModule.CHANNEL);
            if (cl.getLength() > 0) {
                //only one channel tag!
                Node channel = cl.item(0);
                for (Node element : forbidPageUuidList) {
                    channel.removeChild(element);
                }
            }
        }
    }
    return dom;
}

From source file:com.snaplogic.snaps.checkfree.SoapExecuteTest.java

private DocumentBuilderFactory getDocumentBuilderFactory() {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setExpandEntityReferences(true);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setCoalescing(true);
    return documentBuilderFactory;
}

From source file:org.opendatakit.aggregate.externalservice.REDCapServer.java

private void submitPost(String actionType, HttpEntity postentity, List<NameValuePair> qparam,
        CallingContext cc) {//from   w ww  . j  a  v a  2  s.c o  m

    try {
        HttpResponse response = this.sendHttpRequest(POST, getUrl(), postentity, qparam, cc);
        int statusCode = response.getStatusLine().getStatusCode();
        String responseString = WebUtils.readResponse(response);

        if (responseString.length() != 0) {
            DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
            xmlFactory.setNamespaceAware(true);
            xmlFactory.setIgnoringComments(true);
            xmlFactory.setCoalescing(true);
            DocumentBuilder builder = xmlFactory.newDocumentBuilder();
            InputStream is = new ByteArrayInputStream(responseString.getBytes(UTF_CHARSET));
            Document doc;
            try {
                doc = builder.parse(is);
            } finally {
                is.close();
            }
            Element root = doc.getDocumentElement();

            NodeList errorNodes = root.getElementsByTagName("error");
            StringBuilder b = new StringBuilder();
            if (errorNodes != null) {
                for (int i = 0; i < errorNodes.getLength(); ++i) {
                    if (i != 0) {
                        b.append("\n");
                    }
                    Element e = (Element) errorNodes.item(i);
                    b.append(e.getTextContent());
                }
                String error = b.toString();
                if (error.length() != 0) {
                    throw new IllegalArgumentException(actionType + " to REDCap server failed. statusCode: "
                            + statusCode + " error: " + error);
                }
            }
        } else {
            // this seems to be the common case???
            logger.info(actionType + " to REDCap server returned no body");
        }

        if (statusCode != HttpStatus.SC_OK) {
            throw new IllegalArgumentException(
                    actionType + " to REDCap server failed - but no error content. Reason: "
                            + response.getStatusLine().getReasonPhrase() + " status code: " + statusCode);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalArgumentException(actionType + " to REDCap server failed - " + e.toString());
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        throw new IllegalArgumentException(actionType + " to REDCap server failed - " + e.toString());
    } catch (SAXException e) {
        e.printStackTrace();
        throw new IllegalArgumentException(actionType + " to REDCap server failed - " + e.toString());
    }
}

From source file:dip.world.variant.VariantManager.java

/** 
 *   Initiaize the VariantManager. /* w ww . ja v a2 s  .c om*/
 *   <p>
 *   An exception is thrown if no File paths are specified. A "." may be used
 *   to specify th ecurrent directory.
 *   <p>
 *   Loaded XML may be validated if the isValidating flag is set to true.
 *
 */
public static synchronized void init(final List<File> searchPaths, boolean isValidating)
        throws javax.xml.parsers.ParserConfigurationException, NoVariantsException {
    long ttime = System.currentTimeMillis();
    long vptime = ttime;
    Log.println("VariantManager.init()");

    if (searchPaths == null || searchPaths.isEmpty()) {
        throw new IllegalArgumentException();
    }

    if (vm != null) {
        // perform cleanup
        vm.variantMap.clear();
        vm.variants = new ArrayList<Variant>();
        vm.currentUCL = null;
        vm.currentPackageURL = null;

        vm.symbolPacks = new ArrayList<SymbolPack>();
        vm.symbolMap.clear();
    }

    vm = new VariantManager();

    // find plugins, create plugin loader
    final List<URL> pluginURLs = vm.searchForFiles(searchPaths, VARIANT_EXTENSIONS);

    // setup document builder
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {
        // this may improve performance, and really only apply to Xerces
        dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE);
        dbf.setAttribute("http://apache.org/xml/properties/input-buffer-size", new Integer(4096));
        dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
    } catch (Exception e) {
        Log.println("VM: Could not set XML feature.", e);
    }

    dbf.setValidating(isValidating);
    dbf.setCoalescing(false);
    dbf.setIgnoringComments(true);

    // setup variant parser
    XMLVariantParser variantParser = new XMLVariantParser(dbf);

    // for each plugin, attempt to find the "variants.xml" file inside. 
    // if it does not exist, we will not load the file. If it does, we will parse it,
    // and associate the variant with the URL in a hashtable.
    for (final URL pluginURL : pluginURLs) {
        URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL });
        URL variantXMLURL = urlCL.findResource(VARIANT_FILE_NAME);
        if (variantXMLURL != null) {
            String pluginName = getFile(pluginURL);

            // parse variant description file, and create hash entry of variant object -> URL
            InputStream is = null;
            try {
                is = new BufferedInputStream(variantXMLURL.openStream());
                variantParser.parse(is, pluginURL);
                final List<Variant> variants = variantParser.getVariants();

                // add variants; variants with same name (but older versions) are
                // replaced with same-name newer versioned variants
                for (final Variant variant : variants) {
                    addVariant(variant, pluginName, pluginURL);
                }
            } catch (IOException e) {
                // display error dialog
                ErrorDialog.displayFileIO(null, e, pluginURL.toString());
            } catch (org.xml.sax.SAXException e) {
                // display error dialog
                ErrorDialog.displayGeneral(null, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    // if we are in webstart, search for variants within webstart jars
    Enumeration<URL> enum2 = null;
    ClassLoader cl = null;

    if (vm.isInWebstart) {
        cl = vm.getClass().getClassLoader();

        try {
            enum2 = cl.getResources(VARIANT_FILE_NAME);
        } catch (IOException e) {
            enum2 = null;
        }

        if (enum2 != null) {
            while (enum2.hasMoreElements()) {
                URL variantURL = enum2.nextElement();

                // parse variant description file, and create hash entry of variant object -> URL
                InputStream is = null;
                String pluginName = getWSPluginName(variantURL);

                try {
                    is = new BufferedInputStream(variantURL.openStream());

                    variantParser.parse(is, variantURL);
                    final List<Variant> variants = variantParser.getVariants();

                    // add variants; variants with same name (but older versions) are
                    // replaced with same-name newer versioned variants
                    for (final Variant variant : variants) {
                        addVariant(variant, pluginName, variantURL);
                    }
                } catch (IOException e) {
                    // display error dialog
                    ErrorDialog.displayFileIO(null, e, variantURL.toString());
                } catch (org.xml.sax.SAXException e) {
                    // display error dialog
                    ErrorDialog.displayGeneral(null, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } // if(enum2 != null)
    }

    // check: did we find *any* variants? Throw an exception.
    if (vm.variantMap.isEmpty()) {
        StringBuffer msg = new StringBuffer(256);
        msg.append("No variants found on path: ");
        for (final File searchPath : searchPaths) {
            msg.append(searchPath);
            msg.append("; ");
        }

        throw new NoVariantsException(msg.toString());
    }

    Log.printTimed(vptime, "VariantManager: variant parsing time: ");

    ///////////////// SYMBOLS /////////////////////////

    // now, parse symbol packs
    XMLSymbolParser symbolParser = new XMLSymbolParser(dbf);

    // find plugins, create plugin loader
    final List<URL> pluginURLs2 = vm.searchForFiles(searchPaths, SYMBOL_EXTENSIONS);

    // for each plugin, attempt to find the "variants.xml" file inside. 
    // if it does not exist, we will not load the file. If it does, we will parse it,
    // and associate the variant with the URL in a hashtable.
    for (final URL pluginURL : pluginURLs2) {
        URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL });
        URL symbolXMLURL = urlCL.findResource(SYMBOL_FILE_NAME);
        if (symbolXMLURL != null) {
            String pluginName = getFile(pluginURL);

            // parse variant description file, and create hash entry of variant object -> URL
            InputStream is = null;
            try {
                is = new BufferedInputStream(symbolXMLURL.openStream());
                symbolParser.parse(is, pluginURL);
                addSymbolPack(symbolParser.getSymbolPack(), pluginName, pluginURL);
            } catch (IOException e) {
                // display error dialog
                ErrorDialog.displayFileIO(null, e, pluginURL.toString());
            } catch (org.xml.sax.SAXException e) {
                // display error dialog
                ErrorDialog.displayGeneral(null, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    // if we are in webstart, search for variants within webstart jars      
    enum2 = null;
    cl = null;

    if (vm.isInWebstart) {
        cl = vm.getClass().getClassLoader();

        try {
            enum2 = cl.getResources(SYMBOL_FILE_NAME);
        } catch (IOException e) {
            enum2 = null;
        }

        if (enum2 != null) {
            while (enum2.hasMoreElements()) {
                URL symbolURL = enum2.nextElement();

                // parse variant description file, and create hash entry of variant object -> URL
                InputStream is = null;
                String pluginName = getWSPluginName(symbolURL);

                try {
                    is = new BufferedInputStream(symbolURL.openStream());
                    symbolParser.parse(is, symbolURL);
                    addSymbolPack(symbolParser.getSymbolPack(), pluginName, symbolURL);
                } catch (IOException e) {
                    // display error dialog
                    ErrorDialog.displayFileIO(null, e, symbolURL.toString());
                } catch (org.xml.sax.SAXException e) {
                    // display error dialog
                    ErrorDialog.displayGeneral(null, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } // if(enum2 != null)
    } // if(isInWebStart)      

    // check: did we find *any* symbol packs? Throw an exception.
    if (vm.symbolMap.isEmpty()) {
        StringBuffer msg = new StringBuffer(256);
        msg.append("No SymbolPacks found on path: ");
        for (final File searchPath : searchPaths) {
            msg.append(searchPath);
            msg.append("; ");
        }

        throw new NoVariantsException(msg.toString());
    }
    Log.printTimed(ttime, "VariantManager: total parsing time: ");
}

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

/**
 * Only one instance of this class can/should exist.
 *///w ww .  j a v  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 www  . j a va 2  s.c  o 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.zacwolf.commons.wbxcon.WBXCONorg.java

final private Document executeNonQueued(final List<NameValuePair> params, final int retry)
        throws WBXCONexception {
    Document dom = null;//from w w w.  jav  a 2  s .c  om
    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 {/* w w w.  j  a  v a  2s .co 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);
    }
}

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

/**
 * Authenticates with the wapiAUTHURL, to pull a token and a server name
 * which is then used to populate the wapiURL and generate a cred used
 * by all subsequent REST calls/*from   w  w w  .j  a  v a 2  s .c om*/
 * 
 * These queries are not added to the WAPIworker thread pool queue
 * 
 * @throws WBXCONexception
 */
final private synchronized void restapiDomainGetCredToken(final int retry) {
    Document dom = null;
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("cmd", "getwebextoken"));
    params.add(new BasicNameValuePair("username", this.wapiUSER));
    params.add(new BasicNameValuePair("password", this.wapiPASS));
    params.add(new BasicNameValuePair("isp", "wbx"));
    try {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setCoalescing(true);
        final DocumentBuilder db = factory.newDocumentBuilder();

        System.out.println("this.wapiAUTHURL : " + this.wapiAUTHURL);
        System.out.println("restapiDomainGetCredToken: 1 ");

        HttpPost httpPost = new HttpPost(this.wapiAUTHURL);
        System.out.println("restapiDomainGetCredToken: 2 ");
        httpPost.setEntity(new UrlEncodedFormEntity(params, org.apache.http.Consts.UTF_8));
        System.out.println("restapiDomainGetCredToken: 3 ");
        CloseableHttpResponse httpRes = HTTPSCLIENT.execute(httpPost, new BasicHttpContext());
        System.out.println("restapiDomainGetCredToken: 4 ");
        try {
            dom = db.parse(httpRes.getEntity().getContent());
            System.out.println("restapiDomainGetCredToken: 5 ");
        } finally {
            httpRes.close();
            System.out.println("restapiDomainGetCredToken: 6 ");
        }
        NodeList result = dom.getElementsByTagName("result");
        System.out.println("restapiDomainGetCredToken: 7 ");
        if (result == null || result.item(0) == null
                || !result.item(0).getTextContent().equalsIgnoreCase("success"))
            throw new WBXCONexception("restapiDomainGetCredToken(" + retry + "): [RESULT]:"
                    + result.item(0).getTextContent() + " [ERROR}:" + documentGetErrorString(dom));
        System.out.println("restapiDomainGetCredToken: 8 ");
        this.wapiURL = "https://" + dom.getElementsByTagName("serviceurl").item(0).getTextContent() + "/op.do";
        System.out.println("=======restapiDomainGetCredToken======= wapiURL :" + this.wapiURL);
        this.wapiREPORTURL = "https://" + dom.getElementsByTagName("serviceurl").item(0).getTextContent()
                + "/getfile.do";
        System.out.println("=======restapiDomainGetCredToken======= wapiREPORTURL :" + this.wapiREPORTURL);
        params.clear();
        params.add(new BasicNameValuePair("cmd", "login"));
        params.add(new BasicNameValuePair("username", this.wapiUSER));
        params.add(new BasicNameValuePair("isp", "wbx"));
        params.add(new BasicNameValuePair("autocommit", "true"));
        params.add(new BasicNameValuePair("token", dom.getElementsByTagName("token").item(0).getTextContent()));
        httpPost = new HttpPost(this.wapiURL);
        System.out.println("restapiDomainGetCredToken: 9 ");
        httpPost.setEntity(new UrlEncodedFormEntity(params, org.apache.http.Consts.UTF_8));
        System.out.println("restapiDomainGetCredToken: 10 ");
        httpRes = HTTPSCLIENT.execute(httpPost, new BasicHttpContext());
        System.out.println("restapiDomainGetCredToken: 11 ");
        try {
            dom = db.parse(httpRes.getEntity().getContent());
            System.out.println("restapiDomainGetCredToken: 12 ");
        } finally {
            httpRes.close();
        }
        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));
        System.out.println("restapiDomainGetCredToken: 13 ");
        this.cred = dom.getElementsByTagName("cred").item(0).getTextContent();
        System.out.println("restapiDomainGetCredToken: 14 ");
        this.cred_generated = System.currentTimeMillis();
        System.out.println("restapiDomainGetCredToken: 15 ");
    } catch (final Exception e) {
        if (retry < 3) {
            //Retry generating a new cred three times before giving up
            restapiDomainGetCredToken(retry + 1);
        } else {
            this.wapiURL = null;
            System.err.println(getMethodName() + "(" + retry + ") for " + this.orgName
                    + " unable to generate CRED token.");
            e.printStackTrace();
            //System.exit(3);
        }
    }
}

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

/**
 * Class <code>Contructor</code> initializes WBXCONorg instance for the given managed org (domain) instance.
 * As part of initialization the Constructor makes a call to establish orgID and namespaceID for the domain.
 * /* w w  w .j  a va  2s .  c  om*/
 * The REST API calls are made via https GET and POST.  As such, the <code>HTTPSCLIENT</code> needs to be
 * initialized via a certificate stored in a default keystore.  Since the keystore contains a "static"
 * certificate provided by WebEx Connect, the keystore is generated "in source".  If WebEx Connect modifies
 * their default https certificate, you will need to download the latest version of this package from:<br />
 * <br />
 * <a href="https://github.com/ZacWolf/com.zacwolf.commons">https://github.com/ZacWolf/com.zacwolf.commons</a>
 * 
 * 
 * Whatever user is specified for wapiUSER, the following special privileges need to be granted to the account:
 * 
 * WBX:ManageDomain
 * WBX:ManageUsers
 * WBX:ManageRoles
 * 
 * @param domain_name   Name of the WebEx Connect Managed Org
 * @param wapiAUTHURL   (optional) URL used to override the default URL used to generate the initial login token
 * @param wapiUSER      WebEx UserName to use in making the REST calls
 * @param wapiPASS      WebEx user password to use in making the REST calls
 * @throws WBXCONexception
 */
WBXCONorg(final String domain_name, final String wapiAUTHURL, final String wapiUSER, final String wapiPASS)
        throws WBXCONexception {
    if (HTTPSCLIENT == null)
        try {
            //Quiet the various apache http client loggers
            Logger.getLogger("org.apache.http").setLevel(Level.SEVERE);
            Logger.getLogger("org.apache.http.wire").setLevel(Level.SEVERE);
            Logger.getLogger("org.apache.http.headers").setLevel(Level.SEVERE);
            System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
            System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
            System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "ERROR");
            System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "ERROR");
            System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "ERROR");

            final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(MAX_HTTP_REQUESTS);
            final KeyStore trustStore = KeyStore.getInstance("JCEKS");
            // Use the default keystore that is in the same package directory
            final InputStream instream = WBXCONorg.class.getClassLoader().getResourceAsStream(
                    WBXCONorg.class.getPackage().getName().replaceAll("\\.", "/") + "/" + TRUSTSTOREFILENAME);
            try {
                trustStore.load(instream, TRUSTSTOREPASS.toCharArray());
            } finally {
                instream.close();
            }
            final SSLContext sslcontext = SSLContexts.custom()// Trust own CA and all self-signed certs
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                    new String[] { "TLSv1" }, // Allow TLSv1 protocol only
                    null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            final RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_TIMEOUT * 60000)
                    .setConnectionRequestTimeout(HTTP_TIMEOUT * 60000).setSocketTimeout(HTTP_TIMEOUT * 60000)
                    .build();
            HTTPSCLIENT = HttpClients.custom().setConnectionManager(cm).setSSLSocketFactory(sslsf)
                    .setDefaultRequestConfig(config).build();
        } catch (final Exception e) {
            System.err.println(WBXCONorg.class.getCanonicalName()
                    + " UNABLE TO ESTABLISH HTTPSCLIENT FOR WAPI CALLS. All WAPI CALLS WILL FAIL!!!");
            e.printStackTrace();
            //System.exit(2);
        }
    Runtime.getRuntime().addShutdownHook(new Thread("WBXCONorg shutdownhook") {
        @Override
        public void run() {
            try {
                finalize();
            } catch (final Throwable e) {
                e.printStackTrace();
            }
        }
    });
    this.orgName = domain_name;
    this.wapiAUTHURL = wapiAUTHURL != null ? wapiAUTHURL : this.wapiAUTHURL;
    this.wapiUSER = wapiUSER + (!wapiUSER.endsWith("@" + domain_name) ? "@" + domain_name : "");
    this.wapiPASS = wapiPASS;

    final Document dom;
    try {
        System.out.println("===============  1");
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        System.out.println("===============  2");
        factory.setValidating(false);
        System.out.println("===============  3");
        factory.setCoalescing(true);
        System.out.println("===============  4");
        final DocumentBuilder db = factory.newDocumentBuilder();
        System.out.println("===============  5");
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        System.out.println("===============  6");
        params.add(new BasicNameValuePair("cmd", "get"));
        System.out.println("===============  7");
        params.add(new BasicNameValuePair("type", "org"));
        System.out.println("===============  8");
        params.add(new BasicNameValuePair("select", "org/orgID:/org/namespaceID:ext/WBX/PWSRule"));
        System.out.println("===============  9");
        params.add(new BasicNameValuePair("id", "current"));
        System.out.println("===============  10");
        System.out.println("===============  getDomainCredToken() :" + getDomainCredToken());
        params.add(new BasicNameValuePair("cred", getDomainCredToken()));
        System.out.println("===============  11");
        System.out.println("===============  params" + params.toString());
        System.out.println("===============Before wapiURL :" + this.wapiURL);
        final HttpPost httpPost = new HttpPost(this.wapiURL);
        System.out.println("=============== after wapiURL :" + this.wapiURL);

        httpPost.setEntity(new UrlEncodedFormEntity(params, org.apache.http.Consts.UTF_8));
        System.out.println("===============  12");
        final CloseableHttpResponse httpRes = HTTPSCLIENT.execute(httpPost, new BasicHttpContext());
        System.out.println("===============  13");

        if (httpRes == null) {
            System.out.println("===============  httpRes is NULL");
        }

        try {
            dom = db.parse(httpRes.getEntity().getContent());
            System.out.println("===============  14");
        } finally {
            httpRes.close();
        }
    } catch (final Exception e) {
        throw new WBXCONexception(e);
    }
    final NodeList result = dom.getElementsByTagName("result");
    if (result == null || result.item(0) == null
            || !result.item(0).getTextContent().equalsIgnoreCase("success"))
        throw new WBXCONexception(
                "ERROR::WBXCONorg:constructor(\"" + domain_name + "\")::" + documentGetErrorString(dom));

    this.orgID = dom.getElementsByTagName("orgID").item(0).getTextContent();
    this.namespaceID = dom.getElementsByTagName("namespaceID").item(0).getTextContent();
    this.passwordrule = new PWSRule(Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumLength_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumAlpha_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumNumeric_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumSpecial_9")),
            documentGetTextContentByTagName(dom, "PWRequireMixedCase_B").equalsIgnoreCase("true"));
    this.wapiUser = restapiAccountGet(this.wapiUSER);
}