Example usage for org.w3c.dom Element getFirstChild

List of usage examples for org.w3c.dom Element getFirstChild

Introduction

In this page you can find the example usage for org.w3c.dom Element getFirstChild.

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:com.buaa.cfs.conf.Configuration.java

private Resource loadResource(Properties properties, Resource wrapper, boolean quiet) {
    String name = UNKNOWN_RESOURCE;
    try {/*  www  . ja v  a2  s  . c o  m*/
        Object resource = wrapper.getResource();
        name = wrapper.getName();

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        //ignore all comments inside the xml file
        docBuilderFactory.setIgnoringComments(true);

        //allow includes in the xml file
        docBuilderFactory.setNamespaceAware(true);
        try {
            docBuilderFactory.setXIncludeAware(true);
        } catch (UnsupportedOperationException e) {
            LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e);
        }
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;
        boolean returnCachedProperties = false;

        if (resource instanceof URL) { // an URL resource
            doc = parse(builder, (URL) resource);
        } else if (resource instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) resource);
            doc = parse(builder, url);
        } else if (resource instanceof Path) { // a file resource
            // Can't use FileSystem API or we get an infinite loop
            // since FileSystem uses Configuration API.  Use java.io.File instead.
            File file = new File(((Path) resource).toUri().getPath()).getAbsoluteFile();
            if (file.exists()) {
                if (!quiet) {
                    LOG.debug("parsing File " + file);
                }
                doc = parse(builder, new BufferedInputStream(new FileInputStream(file)),
                        ((Path) resource).toString());
            }
        } else if (resource instanceof InputStream) {
            doc = parse(builder, (InputStream) resource, null);
            returnCachedProperties = true;
        } else if (resource instanceof Properties) {
            overlay(properties, (Properties) resource);
        } else if (resource instanceof Element) {
            root = (Element) resource;
        }

        if (root == null) {
            if (doc == null) {
                if (quiet) {
                    return null;
                }
                throw new RuntimeException(resource + " not found");
            }
            root = doc.getDocumentElement();
        }
        Properties toAddTo = properties;
        if (returnCachedProperties) {
            toAddTo = new Properties();
        }
        if (!"configuration".equals(root.getTagName()))
            LOG.fatal("bad conf file: top-level element not <configuration>");
        NodeList props = root.getChildNodes();
        DeprecationContext deprecations = deprecationContext.get();
        for (int i = 0; i < props.getLength(); i++) {
            Node propNode = props.item(i);
            if (!(propNode instanceof Element))
                continue;
            Element prop = (Element) propNode;
            if ("configuration".equals(prop.getTagName())) {
                loadResource(toAddTo, new Resource(prop, name), quiet);
                continue;
            }
            if (!"property".equals(prop.getTagName()))
                LOG.warn("bad conf file: element not <property>");
            NodeList fields = prop.getChildNodes();
            String attr = null;
            String value = null;
            boolean finalParameter = false;
            LinkedList<String> source = new LinkedList<String>();
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element))
                    continue;
                Element field = (Element) fieldNode;
                if ("name".equals(field.getTagName()) && field.hasChildNodes())
                    attr = StringInterner.weakIntern(((Text) field.getFirstChild()).getData().trim());
                if ("value".equals(field.getTagName()) && field.hasChildNodes())
                    value = StringInterner.weakIntern(((Text) field.getFirstChild()).getData());
                if ("final".equals(field.getTagName()) && field.hasChildNodes())
                    finalParameter = "true".equals(((Text) field.getFirstChild()).getData());
                if ("source".equals(field.getTagName()) && field.hasChildNodes())
                    source.add(StringInterner.weakIntern(((Text) field.getFirstChild()).getData()));
            }
            source.add(name);

            // Ignore this parameter if it has already been marked as 'final'
            if (attr != null) {
                if (deprecations.getDeprecatedKeyMap().containsKey(attr)) {
                    DeprecatedKeyInfo keyInfo = deprecations.getDeprecatedKeyMap().get(attr);
                    keyInfo.clearAccessed();
                    for (String key : keyInfo.newKeys) {
                        // update new keys with deprecated key's value
                        loadProperty(toAddTo, name, key, value, finalParameter,
                                source.toArray(new String[source.size()]));
                    }
                } else {
                    loadProperty(toAddTo, name, attr, value, finalParameter,
                            source.toArray(new String[source.size()]));
                }
            }
        }

        if (returnCachedProperties) {
            overlay(properties, toAddTo);
            return new Resource(toAddTo, name);
        }
        return null;
    } catch (IOException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (DOMException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (SAXException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    }
}

From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java

/**
 * {@inheritDoc}/*  ww  w . ja v a 2 s.  c  om*/
 */
public void addToJava2wsPlugin(JavaType serviceClass, String serviceName, String addressName,
        String fullyQualifiedTypeName) {

    // Get pom
    String pomPath = getPomFilePath();
    Validate.isTrue(pomPath != null, "Cxf configuration file not found, export again the service.");
    MutableFile pomMutableFile = getFileManager().updateFile(pomPath);
    Document pom = getInputDocument(pomMutableFile.getInputStream());
    Element root = pom.getDocumentElement();

    // Gets java2ws plugin element
    Element jaxWsPlugin = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin[groupId='org.apache.cxf' and artifactId='cxf-java2ws-plugin']",
            root);

    // Install it if it's missing
    if (jaxWsPlugin == null) {

        logger.log(Level.INFO, "Jax-Ws plugin is not defined in the pom.xml. Installing in project.");
        // Installs jax2ws plugin.
        addPlugin();
    }

    // Checks if already exists the execution.
    Element serviceExecution = XmlUtils
            .findFirstElement("/project/build/plugins/plugin/executions/execution/configuration[className='"
                    .concat(serviceClass.getFullyQualifiedTypeName()).concat("']"), root);

    if (serviceExecution != null) {
        logger.log(Level.FINE, "A previous Wsdl generation with CXF plugin for '".concat(serviceName)
                .concat("' service has been found."));
        return;
    }

    // Checks if name of java class has been changed comparing current
    // service class and name declared in annotation
    boolean classNameChanged = false;
    if (!serviceClass.getFullyQualifiedTypeName().contentEquals(fullyQualifiedTypeName)) {
        classNameChanged = true;
    }

    // if class has been changed (package or name) update execution
    if (classNameChanged) {
        serviceExecution = XmlUtils
                .findFirstElement("/project/build/plugins/plugin/executions/execution/configuration[className='"
                        .concat(fullyQualifiedTypeName).concat("']"), root);

        // Update with serviceClass.getFullyQualifiedTypeName().
        if (serviceExecution != null && serviceExecution.hasChildNodes()) {

            Node updateServiceExecution;
            updateServiceExecution = (serviceExecution.getFirstChild() != null)
                    ? serviceExecution.getFirstChild().getNextSibling()
                    : null;

            // Find node which contains old class name
            while (updateServiceExecution != null) {

                if (updateServiceExecution.getNodeName().contentEquals("className")) {
                    // Update node content with new value
                    updateServiceExecution.setTextContent(serviceClass.getFullyQualifiedTypeName());

                    // write pom
                    XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
                    logger.log(Level.INFO,
                            "Wsdl generation with CXF plugin for '" + serviceName
                                    + " service, updated className attribute for '"
                                    + serviceClass.getFullyQualifiedTypeName() + "'.");
                    // That's all
                    return;
                }

                // Check next node.
                updateServiceExecution = updateServiceExecution.getNextSibling();

            }
        }
    }

    // Prepare Execution configuration
    String executionID = "${project.basedir}/src/test/resources/generated/wsdl/".concat(addressName)
            .concat(".wsdl");
    serviceExecution = createJava2wsExecutionElement(pom, serviceClass, addressName, executionID);

    // Checks if already exists the execution.

    // XXX ??? this is hard difficult because previously it's already
    // checked
    // using class name
    Element oldExecution = XmlUtils.findFirstElement(
            "/project/build/plugins/plugin/executions/execution[id='" + executionID + "']", root);

    if (oldExecution != null) {
        logger.log(Level.FINE, "Wsdl generation with CXF plugin for '" + serviceName
                + " service, has been configured before.");
        return;
    }

    // Checks if already exists the executions to update or create.
    Element oldExecutions = DomUtils.findFirstElementByName(EXECUTIONS, jaxWsPlugin);

    Element newExecutions;

    // To Update execution definitions It must be replaced in pom.xml to
    // maintain the format.
    if (oldExecutions != null) {
        newExecutions = oldExecutions;
        newExecutions.appendChild(serviceExecution);
        oldExecutions.getParentNode().replaceChild(oldExecutions, newExecutions);
    } else {
        newExecutions = pom.createElement(EXECUTIONS);
        newExecutions.appendChild(serviceExecution);

        jaxWsPlugin.appendChild(newExecutions);
    }

    XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SPSProxyHelper.java

/**
*
* @return true if connection OK// ww w  . j  a  v  a  2s. c  o  m
* @throws java.net.MalformedURLException
* @throws javax.xml.rpc.ServiceException
* @throws java.rmi.RemoteException
*/
public boolean checkConnection(String site, boolean sps30) throws ManifoldCFException, ServiceInterruption {
    long currentTime;
    try {
        if (site.equals("/"))
            site = "";

        // Attempt a listservice call
        ListsWS listService = new ListsWS(baseUrl + site, userName, password, configuration, httpClient);
        ListsSoap listCall = listService.getListsSoapHandler();
        listCall.getListCollection();

        // If this is 3.0, we should also attempt to reach our custom webservice
        if (sps30) {
            // The web service allows us to get acls for a site, so that's what we will attempt

            MCPermissionsWS aclService = new MCPermissionsWS(baseUrl + site, userName, password, configuration,
                    httpClient);
            com.microsoft.sharepoint.webpartpages.PermissionsSoap aclCall = aclService
                    .getPermissionsSoapHandler();

            aclCall.getPermissionCollection("/", "Web");
        }

        return true;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a service exception checking connection - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Service exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 12 * 60 * 60000L, -1, true);
    } catch (org.apache.axis.AxisFault e) {
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(
                    new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
            if (elem != null) {
                elem.normalize();
                String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (httpErrorCode.equals("404")) {
                    // Page did not exist
                    throw new ManifoldCFException("The site at " + baseUrl + site + " did not exist");
                } else if (httpErrorCode.equals("401"))
                    throw new ManifoldCFException(
                            "Crawl user did not authenticate properly, or has insufficient permissions to access "
                                    + baseUrl + site + ": " + e.getMessage(),
                            e);
                else if (httpErrorCode.equals("403"))
                    throw new ManifoldCFException(
                            "Http error " + httpErrorCode + " while reading from " + baseUrl + site
                                    + " - check IIS and SharePoint security settings! " + e.getMessage(),
                            e);
                else if (httpErrorCode.equals("302"))
                    throw new ManifoldCFException(
                            "The correct version of ManifoldCF's MCPermissions web service may not be installed on the target SharePoint server.  MCPermissions service is needed for SharePoint repositories version 3.0 or higher, to allow access to security information for files and folders.  Consult your system administrator.");
                else
                    throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                            + " accessing SharePoint at " + baseUrl + site + ": " + e.getMessage(), e);
            }
            throw new ManifoldCFException("Unknown http error occurred: " + e.getMessage(), e);
        } else if (e.getFaultCode()
                .equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/", "Server"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(new javax.xml.namespace.QName(
                    "http://schemas.microsoft.com/sharepoint/soap/", "errorcode"));
            if (elem != null) {
                elem.normalize();
                String sharepointErrorCode = elem.getFirstChild().getNodeValue().trim();
                org.w3c.dom.Element elem2 = e.lookupFaultDetail(new javax.xml.namespace.QName(
                        "http://schemas.microsoft.com/sharepoint/soap/", "errorstring"));
                String errorString = "";
                if (elem != null)
                    errorString = elem2.getFirstChild().getNodeValue().trim();

                throw new ManifoldCFException(
                        "Accessing site " + site + " failed with unexpected SharePoint error code "
                                + sharepointErrorCode + ": " + errorString,
                        e);
            }
            throw new ManifoldCFException("Unknown SharePoint server error accessing site " + site
                    + " - axis fault = " + e.getFaultCode().getLocalPart() + ", detail = " + e.getFaultString(),
                    e);
        }

        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/",
                "Server.userException"))) {
            String exceptionName = e.getFaultString();
            if (exceptionName.equals("java.lang.InterruptedException"))
                throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
        }

        throw new ManifoldCFException("Got an unknown remote exception accessing site " + site
                + " - axis fault = " + e.getFaultCode().getLocalPart() + ", detail = " + e.getFaultString(), e);
    } catch (java.rmi.RemoteException e) {
        // We expect the axis exception to be thrown, not this generic one!
        // So, fail hard if we see it.
        throw new ManifoldCFException(
                "Got an unexpected remote exception accessing site " + site + ": " + e.getMessage(), e);
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SPSProxyHelper.java

/**
* Gets a list of sites given a parent site
* @param parentSite the site to search for subsites, empty string for root
* @return lists of sites as an arraylist of NameValue objects
*///from   www .  ja v  a  2  s. co  m
public List<NameValue> getSites(String parentSite) throws ManifoldCFException, ServiceInterruption {
    long currentTime;
    try {
        ArrayList<NameValue> result = new ArrayList<NameValue>();

        // Call the webs service
        if (parentSite.equals("/"))
            parentSite = "";
        WebsWS webService = new WebsWS(baseUrl + parentSite, userName, password, configuration, httpClient);
        WebsSoap webCall = webService.getWebsSoapHandler();

        GetWebCollectionResponseGetWebCollectionResult webResp = webCall.getWebCollection();
        org.apache.axis.message.MessageElement[] webList = webResp.get_any();

        XMLDoc doc = new XMLDoc(webList[0].toString());
        ArrayList nodeList = new ArrayList();

        doc.processPath(nodeList, "*", null);
        if (nodeList.size() != 1) {
            throw new ManifoldCFException("Bad xml - missing outer 'ns1:Webs' node - there are "
                    + Integer.toString(nodeList.size()) + " nodes");
        }
        Object parent = nodeList.get(0);
        if (!doc.getNodeName(parent).equals("ns1:Webs"))
            throw new ManifoldCFException("Bad xml - outer node is not 'ns1:Webs'");

        nodeList.clear();
        doc.processPath(nodeList, "*", parent); // <ns1:Webs>

        int i = 0;
        while (i < nodeList.size()) {
            Object o = nodeList.get(i++);
            //Logging.connectors.debug( i + ": " + o );
            //System.out.println( i + ": " + o );
            String url = doc.getValue(o, "Url");
            String title = doc.getValue(o, "Title");

            // Leave here for now
            if (Logging.connectors.isDebugEnabled())
                Logging.connectors.debug("SharePoint: Subsite list: '" + url + "', '" + title + "'");

            // A full path to the site is tacked on the front of each one of these.  However, due to nslookup differences, we cannot guarantee that
            // the server name part of the path will actually match what got passed in.  Therefore, we want to look only at the last path segment, whatever that is.
            if (url != null && url.length() > 0) {
                int lastSlash = url.lastIndexOf("/");
                if (lastSlash != -1) {
                    String pathValue = url.substring(lastSlash + 1);
                    if (pathValue.length() > 0) {
                        if (title == null || title.length() == 0)
                            title = pathValue;
                        result.add(new NameValue(pathValue, title));
                    }
                }
            }
        }

        return result;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a service exception getting subsites for site "
                    + parentSite + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Service exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 12 * 60 * 60000L, -1, true);
    } catch (org.apache.axis.AxisFault e) {
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(
                    new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
            if (elem != null) {
                elem.normalize();
                String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (httpErrorCode.equals("404"))
                    return null;
                else if (httpErrorCode.equals("403"))
                    throw new ManifoldCFException("Remote procedure exception: " + e.getMessage(), e);
                else if (httpErrorCode.equals("401")) {
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug(
                                "SharePoint: Crawl user does not have sufficient privileges to get subsites of site "
                                        + parentSite + " - skipping",
                                e);
                    return null;
                }
                throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                        + " accessing SharePoint at " + baseUrl + parentSite + ": " + e.getMessage(), e);
            }
            throw new ManifoldCFException("Unknown http error occurred: " + e.getMessage(), e);
        }

        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/",
                "Server.userException"))) {
            String exceptionName = e.getFaultString();
            if (exceptionName.equals("java.lang.InterruptedException"))
                throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
        }

        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a remote exception getting subsites for site "
                    + parentSite + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 3 * 60 * 60000L, -1, false);
    } catch (java.rmi.RemoteException e) {
        throw new ManifoldCFException("Unexpected remote exception occurred: " + e.getMessage(), e);
    }

}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

private DOMXMLSignature createEnveloped(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, JAXBException, MarshalException, XMLSignatureException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    signContext.setURIDereferencer(new URIDereferencer() {

        @Override/*from w w  w  .  ja v a 2 s .c o m*/
        public Data dereference(URIReference uriReference, XMLCryptoContext context)
                throws URIReferenceException {
            final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
            Data data = fac.getURIDereferencer().dereference(uriReference, context);
            return data;
        }
    });

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", XMLSignature.XMLNS);

    List<Reference> references = new ArrayList<Reference>();

    /* The first reference concern the whole document */
    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(fac.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    org.w3c.dom.Document empty;
    try {
        empty = dbf.newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new RuntimeException(e1);
    }
    Element xpathEl = empty.createElementNS(XMLSignature.XMLNS, "XPath");
    xpathEl.setTextContent("");
    empty.adoptNode(xpathEl);
    XPathFilterParameterSpec specs = new XPathFilterParameterSpec("not(ancestor-or-self::ds:Signature)");
    DOMTransform t = (DOMTransform) fac.newTransform("http://www.w3.org/TR/1999/REC-xpath-19991116", specs);

    transforms.add(t);
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);
    Reference reference = fac.newReference("", digestMethod, transforms, null, "xml_ref_id");
    references.add(reference);

    List<XMLObject> objects = new ArrayList<XMLObject>();

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.XML);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);
    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod,
            Collections.singletonList(
                    fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)),
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    signature.marshal(doc.getDocumentElement(), "ds", signContext);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");

    digestReferences(signContext, references);

    return signature;

}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SPSProxyHelper.java

/** Gets a list of attachment URLs, given a site, list name, and list item ID.  These will be returned
* as name/value pairs; the "name" is the name of the attachment, and the "value" is the full URL.
*//*from  w  w  w.j av  a2s  . com*/
public List<NameValue> getAttachmentNames(String site, String listName, String itemID)
        throws ManifoldCFException, ServiceInterruption {
    long currentTime;
    try {
        ArrayList<NameValue> result = new ArrayList<NameValue>();

        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: In getAttachmentNames; site='" + site + "', listName='"
                    + listName + "', itemID='" + itemID + "'");

        // The docLibrary must be a GUID, because we don't have  title.

        if (site.compareTo("/") == 0)
            site = "";
        ListsWS listService = new ListsWS(baseUrl + site, userName, password, configuration, httpClient);
        ListsSoap listCall = listService.getListsSoapHandler();

        GetAttachmentCollectionResponseGetAttachmentCollectionResult listResponse = listCall
                .getAttachmentCollection(listName, itemID);
        org.apache.axis.message.MessageElement[] List = listResponse.get_any();

        XMLDoc doc = new XMLDoc(List[0].toString());
        ArrayList nodeList = new ArrayList();

        doc.processPath(nodeList, "*", null);
        if (nodeList.size() != 1) {
            throw new ManifoldCFException(
                    "Bad xml - missing outer node - there are " + Integer.toString(nodeList.size()) + " nodes");
        }

        Object attachments = nodeList.get(0);
        if (!doc.getNodeName(attachments).equals("ns1:Attachments"))
            throw new ManifoldCFException(
                    "Bad xml - outer node '" + doc.getNodeName(attachments) + "' is not 'ns1:Attachments'");

        nodeList.clear();
        doc.processPath(nodeList, "*", attachments);

        int i = 0;
        while (i < nodeList.size()) {
            Object o = nodeList.get(i++);
            if (!doc.getNodeName(o).equals("ns1:Attachment"))
                throw new ManifoldCFException(
                        "Bad xml - inner node '" + doc.getNodeName(o) + "' is not 'ns1:Attachment'");
            String attachmentURL = doc.getData(o);
            if (attachmentURL != null) {
                int index = attachmentURL.lastIndexOf("/");
                if (index == -1)
                    throw new ManifoldCFException("Unexpected attachment URL form: '" + attachmentURL + "'");
                result.add(new NameValue(attachmentURL.substring(index + 1),
                        new java.net.URL(attachmentURL).getPath()));
            }
        }

        return result;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a service exception getting attachments for site " + site
                    + " listName " + listName + " itemID " + itemID + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Service exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 12 * 60 * 60000L, -1, true);
    } catch (org.apache.axis.AxisFault e) {
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(
                    new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
            if (elem != null) {
                elem.normalize();
                String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (httpErrorCode.equals("404"))
                    return null;
                else if (httpErrorCode.equals("403"))
                    throw new ManifoldCFException("Remote procedure exception: " + e.getMessage(), e);
                else if (httpErrorCode.equals("401")) {
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug(
                                "SharePoint: Crawl user does not have sufficient privileges to get attachment list for site "
                                        + site + " listName " + listName + " itemID " + itemID + " - skipping",
                                e);
                    return null;
                }
                throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                        + " accessing SharePoint at " + baseUrl + site + ": " + e.getMessage(), e);
            }
            throw new ManifoldCFException("Unknown http error occurred: " + e.getMessage(), e);
        }

        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/",
                "Server.userException"))) {
            String exceptionName = e.getFaultString();
            if (exceptionName.equals("java.lang.InterruptedException"))
                throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
        }

        // I don't know if this is what you get when the library is missing, but here's hoping.
        if (e.getMessage().indexOf("List does not exist") != -1)
            return null;

        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a remote exception getting attachments for site " + site
                    + " listName " + listName + " itemID " + itemID + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 3 * 60 * 60000L, -1, false);
    } catch (java.rmi.RemoteException e) {
        throw new ManifoldCFException("Unexpected remote exception occurred: " + e.getMessage(), e);
    }

}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SPSProxyHelper.java

/**
* Gets a list of field names of the given document library
* @param site/*from  w w  w  .j a  va 2 s  .co  m*/
* @param list/library name
* @return list of the fields
*/
public Map<String, String> getFieldList(String site, String listName)
        throws ManifoldCFException, ServiceInterruption {
    long currentTime;
    try {
        Map<String, String> result = new HashMap<String, String>();

        if (Logging.connectors.isDebugEnabled())
            Logging.connectors
                    .debug("SharePoint: In getFieldList; site='" + site + "', listName='" + listName + "'");

        // The docLibrary must be a GUID, because we don't have  title.

        if (site.compareTo("/") == 0)
            site = "";
        ListsWS listService = new ListsWS(baseUrl + site, userName, password, configuration, httpClient);
        ListsSoap listCall = listService.getListsSoapHandler();

        GetListResponseGetListResult listResponse = listCall.getList(listName);
        org.apache.axis.message.MessageElement[] List = listResponse.get_any();

        XMLDoc doc = new XMLDoc(List[0].toString());
        ArrayList nodeList = new ArrayList();

        doc.processPath(nodeList, "*", null);
        if (nodeList.size() != 1) {
            throw new ManifoldCFException(
                    "Bad xml - missing outer node - there are " + Integer.toString(nodeList.size()) + " nodes");
        }

        Object parent = nodeList.get(0);
        if (!doc.getNodeName(parent).equals("ns1:List"))
            throw new ManifoldCFException(
                    "Bad xml - outer node is '" + doc.getNodeName(parent) + "' not 'ns1:List'");

        nodeList.clear();
        doc.processPath(nodeList, "*", parent); // <ns1:Fields>

        for (Object metaField : nodeList) {
            if (doc.getNodeName(metaField).equals("ns1:Fields")) {
                ArrayList fieldsList = new ArrayList();
                doc.processPath(fieldsList, "*", metaField);

                for (Object o : fieldsList) {
                    String name = doc.getValue(o, "DisplayName");
                    String fieldName = doc.getValue(o, "Name");
                    String hidden = doc.getValue(o, "Hidden");
                    // System.out.println( "Hidden :" + hidden );
                    if (name.length() != 0 && fieldName.length() != 0 && (!hidden.equalsIgnoreCase("true"))) {
                        // make sure we don't include the same field more than once.
                        // This may happen if the Library has more than one view.
                        if (result.containsKey(fieldName) == false)
                            result.put(fieldName, name);
                    }
                }
            }
        }
        // System.out.println(result.size());
        return result;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a service exception getting field list for site " + site
                    + " listName " + listName + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Service exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 12 * 60 * 60000L, -1, true);
    } catch (org.apache.axis.AxisFault e) {
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(
                    new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
            if (elem != null) {
                elem.normalize();
                String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (httpErrorCode.equals("404"))
                    return null;
                else if (httpErrorCode.equals("403"))
                    throw new ManifoldCFException("Remote procedure exception: " + e.getMessage(), e);
                else if (httpErrorCode.equals("401")) {
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug(
                                "SharePoint: Crawl user does not have sufficient privileges to get field list for site "
                                        + site + " listName " + listName + " - skipping",
                                e);
                    return null;
                }
                throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                        + " accessing SharePoint at " + baseUrl + site + ": " + e.getMessage(), e);
            }
            throw new ManifoldCFException("Unknown http error occurred: " + e.getMessage(), e);
        }

        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/",
                "Server.userException"))) {
            String exceptionName = e.getFaultString();
            if (exceptionName.equals("java.lang.InterruptedException"))
                throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
        }

        // I don't know if this is what you get when the library is missing, but here's hoping.
        if (e.getMessage().indexOf("List does not exist") != -1)
            return null;

        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a remote exception getting field list for site " + site
                    + " listName " + listName + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 3 * 60 * 60000L, -1, false);
    } catch (java.rmi.RemoteException e) {
        throw new ManifoldCFException("Unexpected remote exception occurred: " + e.getMessage(), e);
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SPSProxyHelper.java

/**
*
* @param site/*from ww  w  .  ja  va  2s  . c o  m*/
* @param docPath
* @return an XML document
* @throws ManifoldCFException
* @throws ServiceInterruption
*/
public XMLDoc getVersions(String site, String docPath) throws ServiceInterruption, ManifoldCFException {
    long currentTime;
    try {
        if (site.compareTo("/") == 0)
            site = ""; // root case
        VersionsWS versionsService = new VersionsWS(baseUrl + site, userName, password, configuration,
                httpClient);
        VersionsSoap versionsCall = versionsService.getVersionsSoapHandler();

        GetVersionsResponseGetVersionsResult versionsResp = versionsCall.getVersions(docPath);
        org.apache.axis.message.MessageElement[] lists = versionsResp.get_any();

        //System.out.println( lists[0].toString() );
        XMLDoc doc = new XMLDoc(lists[0].toString());
        ArrayList nodeList = new ArrayList();

        doc.processPath(nodeList, "*", null);

        if (nodeList.size() != 1) {
            throw new ManifoldCFException("Bad xml - missing outer 'results' node - there are "
                    + Integer.toString(nodeList.size()) + " nodes");
        }

        Object parent = nodeList.get(0);
        if (!doc.getNodeName(parent).equals("results"))
            throw new ManifoldCFException("Bad xml - outer node is not 'results'");

        return doc;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a service exception getting versions for site " + site
                    + " docpath " + docPath + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Service exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 12 * 60 * 60000L, -1, true);
    } catch (org.apache.axis.AxisFault e) {
        currentTime = System.currentTimeMillis();
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(
                    new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
            if (elem != null) {
                elem.normalize();
                String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (httpErrorCode.equals("404")) {
                    // Page did not exist
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug("SharePoint: The page at " + baseUrl + site
                                + " did not exist; assuming library deleted");
                    return null;
                } else if (httpErrorCode.equals("401")) {
                    // User did not have permissions for this library to get the acls
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors
                                .debug("SharePoint: The crawl user did not have access to get versions for "
                                        + baseUrl + site + "; skipping");
                    return null;
                } else if (httpErrorCode.equals("403"))
                    throw new ManifoldCFException(
                            "Http error " + httpErrorCode + " while reading from " + baseUrl + site
                                    + " - check IIS and SharePoint security settings! " + e.getMessage(),
                            e);
                else
                    throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                            + " accessing SharePoint at " + baseUrl + site + ": " + e.getMessage(), e);
            }
            throw new ManifoldCFException("Unknown http error occurred: " + e.getMessage(), e);
        } else if (e.getFaultCode()
                .equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/", "Server"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(new javax.xml.namespace.QName(
                    "http://schemas.microsoft.com/sharepoint/soap/", "errorcode"));
            if (elem != null) {
                elem.normalize();
                String sharepointErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (sharepointErrorCode.equals("0x82000006")) {
                    // List did not exist
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug("SharePoint: The docpath " + docPath + " in site " + site
                                + " did not exist; assuming library deleted");
                    return null;
                } else {
                    if (Logging.connectors.isDebugEnabled()) {
                        org.w3c.dom.Element elem2 = e.lookupFaultDetail(new javax.xml.namespace.QName(
                                "http://schemas.microsoft.com/sharepoint/soap/", "errorstring"));
                        String errorString = "";
                        if (elem != null)
                            errorString = elem2.getFirstChild().getNodeValue().trim();

                        Logging.connectors.debug("SharePoint: Getting versions for the docpath " + docPath
                                + " in site " + site + " failed with unexpected SharePoint error code "
                                + sharepointErrorCode + ": " + errorString + " - Skipping", e);
                    }
                    return null;
                }
            }
            if (Logging.connectors.isDebugEnabled())
                Logging.connectors
                        .debug("SharePoint: Unknown SharePoint server error getting versions for site " + site
                                + " docpath " + docPath + " - axis fault = " + e.getFaultCode().getLocalPart()
                                + ", detail = " + e.getFaultString() + " - retrying", e);

            throw new ServiceInterruption("Unknown SharePoint server error: " + e.getMessage() + " - retrying",
                    e, currentTime + 300000L, currentTime + 3 * 60 * 60000L, -1, false);
        }

        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/",
                "Server.userException"))) {
            String exceptionName = e.getFaultString();
            if (exceptionName.equals("java.lang.InterruptedException"))
                throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
        }

        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got an unknown remote exception getting versions for site "
                    + site + " docpath " + docPath + " - axis fault = " + e.getFaultCode().getLocalPart()
                    + ", detail = " + e.getFaultString() + " - retrying", e);
        throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 3 * 60 * 60000L, -1, false);
    } catch (java.rmi.RemoteException e) {
        // We expect the axis exception to be thrown, not this generic one!
        // So, fail hard if we see it.
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got an unexpected remote exception getting versions for site "
                    + site + " docpath " + docPath, e);
        throw new ManifoldCFException("Unexpected remote procedure exception: " + e.getMessage(), e);
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SPSProxyHelper.java

/**
* Gets a list of document libraries given a parent site
* @param parentSite the site to search for document libraries, empty string for root
* @return lists of NameValue objects, representing document libraries
*/// www . j  a va2s.  c  om
public List<NameValue> getDocumentLibraries(String parentSite, String parentSiteDecoded)
        throws ManifoldCFException, ServiceInterruption {
    long currentTime;
    try {
        ArrayList<NameValue> result = new ArrayList<NameValue>();

        String parentSiteRequest = parentSite;

        if (parentSiteRequest.equals("/")) {
            parentSiteRequest = ""; // root case
            parentSiteDecoded = "";
        }

        ListsWS listsService = new ListsWS(baseUrl + parentSiteRequest, userName, password, configuration,
                httpClient);
        ListsSoap listsCall = listsService.getListsSoapHandler();

        GetListCollectionResponseGetListCollectionResult listResp = listsCall.getListCollection();
        org.apache.axis.message.MessageElement[] lists = listResp.get_any();

        //if ( parentSite.compareTo("/Sample2") == 0) System.out.println( lists[0].toString() );

        XMLDoc doc = new XMLDoc(lists[0].toString());
        ArrayList nodeList = new ArrayList();

        doc.processPath(nodeList, "*", null);
        if (nodeList.size() != 1) {
            throw new ManifoldCFException("Bad xml - missing outer 'ns1:Lists' node - there are "
                    + Integer.toString(nodeList.size()) + " nodes");
        }
        Object parent = nodeList.get(0);
        if (!doc.getNodeName(parent).equals("ns1:Lists"))
            throw new ManifoldCFException("Bad xml - outer node is not 'ns1:Lists'");

        nodeList.clear();
        doc.processPath(nodeList, "*", parent); // <ns1:Lists>

        String prefixPath = decodedServerLocation + parentSiteDecoded + "/";

        int i = 0;
        while (i < nodeList.size()) {
            Object o = nodeList.get(i++);

            String baseType = doc.getValue(o, "BaseType");
            if (baseType.equals("1")) {
                // We think it's a library

                // This is how we display it, so this has the right path extension
                String urlPath = doc.getValue(o, "DefaultViewUrl");
                // This is the pretty name
                String title = doc.getValue(o, "Title");

                // Leave this in for the moment
                if (Logging.connectors.isDebugEnabled())
                    Logging.connectors.debug("SharePoint: Library list: '" + urlPath + "', '" + title + "'");

                // It's a library.  If it has no view url, we don't have any idea what to do with it
                if (urlPath != null && urlPath.length() > 0) {
                    // Normalize conditionally
                    if (!urlPath.startsWith("/"))
                        urlPath = prefixPath + urlPath;
                    // Get rid of what we don't want, unconditionally
                    if (urlPath.startsWith(prefixPath)) {
                        urlPath = urlPath.substring(prefixPath.length());
                        // We're at the library name.  Figure out where the end of it is.
                        int index = urlPath.indexOf("/");
                        if (index == -1)
                            throw new ManifoldCFException(
                                    "Bad library view url without site: '" + urlPath + "'");
                        String pathpart = urlPath.substring(0, index);

                        if (pathpart.length() != 0 && !pathpart.equals("_catalogs")) {
                            if (title == null || title.length() == 0)
                                title = pathpart;
                            result.add(new NameValue(pathpart, title));
                        }
                    } else {
                        Logging.connectors.warn("SharePoint: Library view url is not in the expected form: '"
                                + urlPath + "'; expected something beginning with '" + prefixPath
                                + "'; skipping");
                    }
                }
            }
        }

        return result;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a service exception getting document libraries for site "
                    + parentSite + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Service exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 12 * 60 * 60000L, -1, true);
    } catch (org.apache.axis.AxisFault e) {
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(
                    new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
            if (elem != null) {
                elem.normalize();
                String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (httpErrorCode.equals("404"))
                    return null;
                else if (httpErrorCode.equals("403"))
                    throw new ManifoldCFException("Remote procedure exception: " + e.getMessage(), e);
                else if (httpErrorCode.equals("401")) {
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug(
                                "SharePoint: Crawl user does not have sufficient privileges to read document libraries for site "
                                        + parentSite + " - skipping",
                                e);
                    return null;
                }
                throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                        + " accessing SharePoint at " + baseUrl + parentSite + ": " + e.getMessage(), e);
            }
            throw new ManifoldCFException("Unknown http error occurred: " + e.getMessage(), e);
        }
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/",
                "Server.userException"))) {
            String exceptionName = e.getFaultString();
            if (exceptionName.equals("java.lang.InterruptedException"))
                throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
        }
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("SharePoint: Got a remote exception reading document libraries for site "
                    + parentSite + " - retrying", e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 3 * 60 * 60000L, -1, false);
    } catch (java.rmi.RemoteException e) {
        throw new ManifoldCFException("Unexpected remote exception occurred: " + e.getMessage(), e);
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SPSProxyHelper.java

/**
* Gets a list of lists given a parent site
* @param parentSite the site to search for lists, empty string for root
* @return lists of NameValue objects, representing lists
*///from w  ww.j a va 2 s. c om
public List<NameValue> getLists(String parentSite, String parentSiteDecoded)
        throws ManifoldCFException, ServiceInterruption {
    long currentTime;
    try {
        ArrayList<NameValue> result = new ArrayList<NameValue>();

        String parentSiteRequest = parentSite;

        if (parentSiteRequest.equals("/")) {
            parentSiteRequest = ""; // root case
            parentSiteDecoded = "";
        }

        ListsWS listsService = new ListsWS(baseUrl + parentSiteRequest, userName, password, configuration,
                httpClient);
        ListsSoap listsCall = listsService.getListsSoapHandler();

        GetListCollectionResponseGetListCollectionResult listResp = listsCall.getListCollection();
        org.apache.axis.message.MessageElement[] lists = listResp.get_any();

        //if ( parentSite.compareTo("/Sample2") == 0) System.out.println( lists[0].toString() );

        XMLDoc doc = new XMLDoc(lists[0].toString());
        ArrayList nodeList = new ArrayList();

        doc.processPath(nodeList, "*", null);
        if (nodeList.size() != 1) {
            throw new ManifoldCFException("Bad xml - missing outer 'ns1:Lists' node - there are "
                    + Integer.toString(nodeList.size()) + " nodes");
        }
        Object parent = nodeList.get(0);
        if (!doc.getNodeName(parent).equals("ns1:Lists"))
            throw new ManifoldCFException("Bad xml - outer node is not 'ns1:Lists'");

        nodeList.clear();
        doc.processPath(nodeList, "*", parent); // <ns1:Lists>

        String prefixPath = decodedServerLocation + parentSiteDecoded + "/";

        int i = 0;
        while (i < nodeList.size()) {
            Object o = nodeList.get(i++);

            String baseType = doc.getValue(o, "BaseType");
            if (baseType.equals("0")) {
                // We think it's a list

                // This is how we display it, so this has the right path extension
                String urlPath = doc.getValue(o, "DefaultViewUrl");
                // This is the pretty name
                String title = doc.getValue(o, "Title");

                // Leave this in for the moment
                if (Logging.connectors.isDebugEnabled())
                    Logging.connectors.debug("SharePoint: List: '" + urlPath + "', '" + title + "'");

                // If it has no view url, we don't have any idea what to do with it
                if (urlPath != null && urlPath.length() > 0) {
                    // Normalize conditionally
                    if (!urlPath.startsWith("/"))
                        urlPath = prefixPath + urlPath;
                    // Get rid of what we don't want, unconditionally
                    if (urlPath.startsWith(prefixPath)) {
                        urlPath = urlPath.substring(prefixPath.length());
                        // We're at the /Lists/listname part of the name.  Figure out where the end of it is.
                        int index = urlPath.indexOf("/");
                        if (index == -1)
                            throw new ManifoldCFException("Bad list view url without site: '" + urlPath + "'");
                        String pathpart = urlPath.substring(0, index);

                        if ("Lists".equals(pathpart)) {
                            int k = urlPath.indexOf("/", index + 1);
                            if (k == -1)
                                throw new ManifoldCFException(
                                        "Bad list view url without 'Lists': '" + urlPath + "'");
                            pathpart = urlPath.substring(index + 1, k);
                        }

                        if (pathpart.length() != 0 && !pathpart.equals("_catalogs")) {
                            if (title == null || title.length() == 0)
                                title = pathpart;
                            result.add(new NameValue(pathpart, title));
                        }
                    } else {
                        Logging.connectors.warn("SharePoint: List view url is not in the expected form: '"
                                + urlPath + "'; expected something beginning with '" + prefixPath
                                + "'; skipping");
                    }
                }
            }

        }

        return result;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug(
                    "SharePoint: Got a service exception getting lists for site " + parentSite + " - retrying",
                    e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Service exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 12 * 60 * 60000L, -1, true);
    } catch (org.apache.axis.AxisFault e) {
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
            org.w3c.dom.Element elem = e.lookupFaultDetail(
                    new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
            if (elem != null) {
                elem.normalize();
                String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                if (httpErrorCode.equals("404"))
                    return null;
                else if (httpErrorCode.equals("403"))
                    throw new ManifoldCFException("Remote procedure exception: " + e.getMessage(), e);
                else if (httpErrorCode.equals("401")) {
                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug(
                                "SharePoint: Crawl user does not have sufficient privileges to read lists for site "
                                        + parentSite + " - skipping",
                                e);
                    return null;
                }
                throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                        + " accessing SharePoint at " + baseUrl + parentSite + ": " + e.getMessage(), e);
            }
            throw new ManifoldCFException("Unknown http error occurred: " + e.getMessage(), e);
        }
        if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/envelope/",
                "Server.userException"))) {
            String exceptionName = e.getFaultString();
            if (exceptionName.equals("java.lang.InterruptedException"))
                throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
        }
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug(
                    "SharePoint: Got a remote exception reading lists for site " + parentSite + " - retrying",
                    e);
        currentTime = System.currentTimeMillis();
        throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e, currentTime + 300000L,
                currentTime + 3 * 60 * 60000L, -1, false);
    } catch (java.rmi.RemoteException e) {
        throw new ManifoldCFException("Unexpected remote exception occurred: " + e.getMessage(), e);
    }
}