Example usage for org.w3c.dom Element normalize

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

Introduction

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

Prototype

public void normalize();

Source Link

Document

Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

Usage

From source file:com.liferay.portal.editor.fckeditor.receiver.impl.BaseCommandReceiver.java

private void _writeDocument(Document document, HttpServletResponse response) {

    try {/*from  w  ww.j av  a2  s.c  om*/
        Element documentElement = document.getDocumentElement();

        documentElement.normalize();

        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        Transformer transformer = transformerFactory.newTransformer();

        DOMSource domSource = new DOMSource(document);

        if (_log.isDebugEnabled()) {
            StreamResult streamResult = new StreamResult(System.out);

            transformer.transform(domSource, streamResult);
        }

        response.setContentType("text/xml; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");

        PrintWriter printWriter = response.getWriter();

        StreamResult streamResult = new StreamResult(printWriter);

        transformer.transform(domSource, streamResult);

        printWriter.flush();
        printWriter.close();
    } catch (Exception e) {
        throw new FCKException(e);
    }
}

From source file:com.esri.gpt.server.csw.client.CswClient.java

/**
 * submit HTTP Request (Both GET and POST). Parse the response into an xml document element.
 * @param method//from w  w w. j ava2s  . c  o m
 * @param urlString
 * @param postdata
 * @param usr
 * @param pwd
 * @return response
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public Element submitHttpRequestAndGetDom(String method, String urlString, String postdata, String usr,
        String pwd) throws IOException, ParserConfigurationException, SAXException {

    InputStream inStream = null;
    Element response;
    try {
        inStream = submitHttpRequest(method, urlString, postdata, "", "");
        // Get a response
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(inStream);

        response = doc.getDocumentElement();
        response.normalize();
    } finally {
        Utils.close(inStream);
    }

    return response;
}

From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SPSProxyHelper.java

/**
*
* @return true if connection OK/*from  w w  w.  ja v  a2  s .  c  o  m*/
* @throws java.net.MalformedURLException
* @throws javax.xml.rpc.ServiceException
* @throws java.rmi.RemoteException
*/
public boolean checkConnection(String site) throws ManifoldCFException {
    try {
        if (site.equals("/"))
            site = "";

        UserGroupWS userService = new UserGroupWS(baseUrl + site, userName, password, configuration,
                httpClient);
        com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap userCall = userService
                .getUserGroupSoapHandler();

        // Get the info for the admin user
        com.microsoft.schemas.sharepoint.soap.directory.GetUserInfoResponseGetUserInfoResult userResp = userCall
                .getUserInfo(mapToClaimSpace(userName));
        org.apache.axis.message.MessageElement[] userList = userResp.get_any();

        return true;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.authorityConnectors.isDebugEnabled())
            Logging.authorityConnectors.debug("SharePoint: Got a service exception checking connection", e);
        throw new ManifoldCFException("Service exception: " + e.getMessage(), e);
    } 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(
                            "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
                    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:com.flipzu.flipzu.FlipInterface.java

public Element getRootElement(String resp) throws ParserConfigurationException, SAXException, IOException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    resp = this.replaceAll(resp, "\0", "");

    byte[] bytes = resp.getBytes(); // IMPORTANT FOR NULL CHARACTERS

    Document document = null;//from w ww.  j av  a 2s .  co m
    try {
        document = builder.parse(new ByteArrayInputStream(bytes));
    } catch (SAXParseException e) {
        debug.logW(TAG, "getRootElement: " + e.getMessage());
    }

    // Normalize the root element of the XML document. This ensures that all
    // Text
    // nodes under the root node are put into a "normal" form, which means
    // that
    // there are neither adjacent Text nodes nor empty Text nodes in the
    // document.
    // See Node.normalize().

    Element rootElement = null;
    if (document != null) {
        rootElement = document.getDocumentElement();
        rootElement.normalize();
    }

    return rootElement;

}

From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SPSProxyHelper.java

/**
* Get the access tokens for a user principal.
*//*from   w  w w .j  a v  a2s . c  om*/
public List<String> getAccessTokens(String site, String userLoginName) throws ManifoldCFException {
    try {
        if (site.compareTo("/") == 0)
            site = ""; // root case

        userLoginName = mapToClaimSpace(userLoginName);

        UserGroupWS userService = new UserGroupWS(baseUrl + site, userName, password, configuration,
                httpClient);
        com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap userCall = userService
                .getUserGroupSoapHandler();

        com.microsoft.schemas.sharepoint.soap.directory.GetUserInfoResponseGetUserInfoResult userResp = userCall
                .getUserInfo(userLoginName);
        org.apache.axis.message.MessageElement[] usersList = userResp.get_any();

        /* Response looks like this:
            <GetUserInfo xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/">
               <User ID="4" Sid="S-1-5-21-2127521184-1604012920-1887927527-34577" Name="User1_Display_Name" 
        LoginName="DOMAIN\User1_Alias" Email="User1_E-mail" 
        Notes="Notes" IsSiteAdmin="False" IsDomainGroup="False" />
            </GetUserInfo>
          */

        if (usersList.length != 1)
            throw new ManifoldCFException("Bad response - expecting one outer 'GetUserInfo' node, saw "
                    + Integer.toString(usersList.length));

        if (Logging.authorityConnectors.isDebugEnabled()) {
            Logging.authorityConnectors
                    .debug("SharePoint authority: getUserInfo xml response: '" + usersList[0].toString() + "'");
        }

        MessageElement users = usersList[0];
        if (!users.getElementName().getLocalName().equals("GetUserInfo"))
            throw new ManifoldCFException("Bad response - outer node should have been 'GetUserInfo' node");

        String userID = null;
        String userName = null;

        Iterator userIter = users.getChildElements();
        while (userIter.hasNext()) {
            MessageElement child = (MessageElement) userIter.next();
            if (child.getElementName().getLocalName().equals("User")) {
                userID = child.getAttribute("ID");
                userName = child.getAttribute("LoginName");
            }
        }

        // If userID is null, no such user
        if (userID == null)
            return null;

        List<String> accessTokens = new ArrayList<String>();
        accessTokens.add("U" + userName);

        com.microsoft.schemas.sharepoint.soap.directory.GetGroupCollectionFromUserResponseGetGroupCollectionFromUserResult userGroupResp = userCall
                .getGroupCollectionFromUser(userLoginName);
        org.apache.axis.message.MessageElement[] groupsList = userGroupResp.get_any();

        /* Response looks like this:
            <GetGroupCollectionFromUser xmlns=
               "http://schemas.microsoft.com/sharepoint/soap/directory/">
               <Groups>
        <Group ID="3" Name="Group1" Description="Description" OwnerID="1" 
           OwnerIsUser="False" />
        <Group ID="15" Name="Group2" Description="Description" 
           OwnerID="12" OwnerIsUser="True" />
        <Group ID="16" Name="Group3" Description="Description" 
           OwnerID="7" OwnerIsUser="False" />
               </Groups>
            </GetGroupCollectionFromUser>
          */

        if (groupsList.length != 1)
            throw new ManifoldCFException(
                    "Bad response - expecting one outer 'GetGroupCollectionFromUser' node, saw "
                            + Integer.toString(groupsList.length));

        if (Logging.authorityConnectors.isDebugEnabled()) {
            Logging.authorityConnectors.debug("SharePoint authority: getGroupCollectionFromUser xml response: '"
                    + groupsList[0].toString() + "'");
        }

        MessageElement groups = groupsList[0];
        if (!groups.getElementName().getLocalName().equals("GetGroupCollectionFromUser"))
            throw new ManifoldCFException(
                    "Bad response - outer node should have been 'GetGroupCollectionFromUser' node");

        Iterator groupsIter = groups.getChildElements();
        while (groupsIter.hasNext()) {
            MessageElement child = (MessageElement) groupsIter.next();
            if (child.getElementName().getLocalName().equals("Groups")) {
                Iterator groupIter = child.getChildElements();
                while (groupIter.hasNext()) {
                    MessageElement group = (MessageElement) groupIter.next();
                    if (group.getElementName().getLocalName().equals("Group")) {
                        String groupID = group.getAttribute("ID");
                        String groupName = group.getAttribute("Name");
                        // Add to the access token list
                        accessTokens.add("G" + groupName);
                    }
                }
            }
        }

        // AxisFault is expected for case where user has no assigned roles
        try {
            com.microsoft.schemas.sharepoint.soap.directory.GetRoleCollectionFromUserResponseGetRoleCollectionFromUserResult userRoleResp = userCall
                    .getRoleCollectionFromUser(userLoginName);
            org.apache.axis.message.MessageElement[] rolesList = userRoleResp.get_any();

            if (rolesList.length != 1)
                throw new ManifoldCFException(
                        "Bad response - expecting one outer 'GetRoleCollectionFromUser' node, saw "
                                + Integer.toString(rolesList.length));

            if (Logging.authorityConnectors.isDebugEnabled()) {
                Logging.authorityConnectors
                        .debug("SharePoint authority: getRoleCollectionFromUser xml response: '"
                                + rolesList[0].toString() + "'");
            }

            // Not specified in doc and must be determined experimentally
            /*
            <ns1:GetRoleCollectionFromUser xmlns:ns1="http://schemas.microsoft.com/sharepoint/soap/directory/">
            <ns1:Roles>
            <ns1:Role ID="1073741825" Name="Limited Access" Description="Can view specific lists, document libraries, list items, folders, or documents when given permissions."
            Order="160" Hidden="True" Type="Guest" BasePermissions="ViewFormPages, Open, BrowseUserInfo, UseClientIntegration, UseRemoteAPIs"/>
            </ns1:Roles>
            </ns1:GetRoleCollectionFromUser>'
            */

            MessageElement roles = rolesList[0];
            if (!roles.getElementName().getLocalName().equals("GetRoleCollectionFromUser"))
                throw new ManifoldCFException(
                        "Bad response - outer node should have been 'GetRoleCollectionFromUser' node");

            Iterator rolesIter = roles.getChildElements();
            while (rolesIter.hasNext()) {
                MessageElement child = (MessageElement) rolesIter.next();
                if (child.getElementName().getLocalName().equals("Roles")) {
                    Iterator roleIter = child.getChildElements();
                    while (roleIter.hasNext()) {
                        MessageElement role = (MessageElement) roleIter.next();
                        if (role.getElementName().getLocalName().equals("Role")) {
                            String roleID = role.getAttribute("ID");
                            String roleName = role.getAttribute("Name");
                            // Add to the access token list
                            accessTokens.add("R" + roleName);
                        }
                    }
                }
            }
        } catch (org.apache.axis.AxisFault e) {
            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("0x80131600"))
                        throw e;
                }
            } else
                throw e;
        }

        return accessTokens;
    } catch (java.net.MalformedURLException e) {
        throw new ManifoldCFException("Bad SharePoint url: " + e.getMessage(), e);
    } catch (javax.xml.rpc.ServiceException e) {
        if (Logging.authorityConnectors.isDebugEnabled())
            Logging.authorityConnectors
                    .debug("SharePoint: Got a service exception getting the acls for site " + site, e);
        throw new ManifoldCFException("Service exception: " + e.getMessage(), e);
    } 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
                    if (Logging.authorityConnectors.isDebugEnabled())
                        Logging.authorityConnectors
                                .debug("SharePoint: The page at " + baseUrl + site + " did not exist");
                    throw new ManifoldCFException("The page at " + baseUrl + site + " did not exist");
                } else if (httpErrorCode.equals("401")) {
                    // User did not have permissions for this library to get the acls
                    if (Logging.authorityConnectors.isDebugEnabled())
                        Logging.authorityConnectors
                                .debug("SharePoint: The user did not have access to the usergroups service for "
                                        + baseUrl + site);
                    throw new ManifoldCFException(
                            "The user did not have access to the usergroups service at " + baseUrl + site);
                } 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("0x80131600")) {
                    // No such user
                    return null;
                }
                if (Logging.authorityConnectors.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.authorityConnectors.debug("SharePoint: Getting usergroups in site " + site
                            + " failed with unexpected SharePoint error code " + sharepointErrorCode + ": "
                            + errorString, e);
                }
                throw new ManifoldCFException("SharePoint server error code: " + sharepointErrorCode);
            }
            if (Logging.authorityConnectors.isDebugEnabled())
                Logging.authorityConnectors
                        .debug("SharePoint: Unknown SharePoint server error getting usergroups for site " + site
                                + " - axis fault = " + e.getFaultCode().getLocalPart() + ", detail = "
                                + e.getFaultString(), e);

            throw new ManifoldCFException("Unknown SharePoint server error: " + e.getMessage());
        }

        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.authorityConnectors.isDebugEnabled())
            Logging.authorityConnectors
                    .debug("SharePoint: Got an unknown remote exception getting usergroups for " + site
                            + " - axis fault = " + e.getFaultCode().getLocalPart() + ", detail = "
                            + e.getFaultString(), e);
        throw new ManifoldCFException("Remote procedure exception: " + e.getMessage(), 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.
        if (Logging.authorityConnectors.isDebugEnabled())
            Logging.authorityConnectors
                    .debug("SharePoint: Got an unexpected remote exception usergroups for site " + site, e);
        throw new ManifoldCFException("Unexpected remote procedure exception: " + e.getMessage(), e);
    }
}

From source file:autohit.creator.compiler.SimCompiler.java

/**
 * Compile the xml tree into an VMExecutable object.
 * //from   ww w .ja v  a2s. c o m
 * We will create a new log for each run, so that we can uniquely
 * identify them.
 *
 * @param xd   A parsed XML document.
 * @return a reference to the target object, in this case it will be a VMExecutableWrapper, or null if it failed.
 * @see autohit.vm.VMExecutableWrapper
 */
public Object build(Document xd) {

    int idx;
    NodeList rootChildren;
    Element itemTree = null;
    Element codeTree = null;
    int numNodes;
    Node scratchNode;
    String scratchString;

    // Any exception or verification check aborts the compile
    try {

        // Ok, build our working Sim object
        ob = new VMExecutableWrapper();
        ob.create();

        // Create our symbol table and fixup stack
        symboltable = new HashMap();
        fixupstack = new Stack();

        // set defaults attributes
        ob.exec.major = 0;

        // set any default attributes
        ob.exec.type = MY_TYPE_OF_EXEC;
        ob.exec.minor = 0;
        ob.exec.output = null; // assume there is nothign to return

        // Get the root element and normalize
        Element root = (Element) xd.getDocumentElement();
        root.normalize();

        // Peal out the <info> and <code> sub-trees
        rootChildren = (NodeList) root.getChildNodes();
        numNodes = rootChildren.getLength();
        while (numNodes > 0) {
            scratchNode = rootChildren.item(numNodes - 1);
            if (scratchNode instanceof Element) {
                scratchString = scratchNode.getNodeName();
                if (scratchString.charAt(0) == 'i') {
                    itemTree = (Element) scratchNode;
                } else if (scratchString.charAt(0) == 'c') {
                    codeTree = (Element) scratchNode;
                }
            }
            numNodes--;
        }

        if (itemTree == null) {
            runtimeError("Missing infomation <info> block.");
        }

        if (codeTree == null) {
            runtimeError("Missing infomation <code> block.");
            throw new Exception();
        }

        // Deal with the <info> tree
        NodeList itemTreeChildren = itemTree.getChildNodes();
        for (idx = 0; idx < itemTreeChildren.getLength(); idx++) {
            scratchNode = itemTreeChildren.item(idx);

            // pull only Elements
            if (scratchNode instanceof Element) {
                processItem((Element) scratchNode);
            }

        }

        // Deal with the <code> tree
        // Basicall, I'm gonna go wtih recursion.  I don't think it should
        // get very deep.   
        try {
            processCode(codeTree);

            // Put a NOP on the end of the executable
            ob.emit(new VMINop());
            ob.clean();

            // fixup goto symbols
            ListIterator li = fixupstack.listIterator();
            VMIGoto jcandidate;
            NOPair nocandidate;
            Integer currentgoto;
            while (li.hasNext()) {
                nocandidate = (NOPair) li.next();
                if (symboltable.containsKey(nocandidate.n)) {
                    jcandidate = (VMIGoto) nocandidate.o;
                    currentgoto = (Integer) symboltable.get(nocandidate.n);
                    jcandidate.t = currentgoto.intValue();
                    runtimeDebug("Fixup GOTO for label=" + nocandidate.n + " target=" + jcandidate.t);
                } else {
                    runtimeError("Broken GOTO.  No label for " + nocandidate.n + ".");
                }
            }

        } catch (Exception e) {
            // an otherwise uncaught exception.  A runaway compiler...
            runtimeError("FATAL ERROR.  Runaway compilation errors.  Stopping compile.");
            ob = null;
        }

    } catch (Exception e) {
        myLog.error("CRITICAL ERROR encountered.  Stopping compile of " + localname + ".  " + e.toString(),
                AutohitErrorCodes.CODE_COMPILE_ERROR);
        myLog.error(e.toString());
        ob = null; // leave the objectCode as null;
    }

    // ditch data as it falls out of scope
    symboltable = null;
    fixupstack = null;

    // clean up logs
    int err = numberErrors();
    runtimeLog.error("Total errors for " + localname + " : " + err);
    runtimeLog.warning("Total errors for " + localname + " : " + numberWarnings());
    if (err > 0) {
        runtimeLog.info("COMPILE FAILED  " + localname + " DUE TO ERRORS.");
        ob = null;
    }
    return ob;
}

From source file:de.betterform.xml.xforms.model.submission.Submission.java

/**
 * Implements <code>xforms-submit</code> default action.
 *///from  ww w.j  a  va2 s  .  c  om
protected void submit() throws XFormsException {
    if (getLogger().isDebugEnabled()) {
        getLogger().debug(this + " submit");
    }

    try {
        updateXPathContext();
    } catch (Exception xe) {
        LOGGER.warn("Exception occured while updating nodeset bound by submission "
                + DOMUtil.getCanonicalPath(this.element) + " " + xe.getMessage());
        LOGGER.warn(
                "Exception occured while updating nodeset bound by submission - exception will be ignored. Submission cancelled");
        return;
    }

    // get instance object and location path to submit
    Instance instanceObject = this.model.getInstance(getInstanceId());
    /*
            if(instanceObject == null) {
    instanceObject = targetModel.getInstance(getInstanceId());
            }
    */
    String pathExpression = getLocationPath();
    if (!XPathUtil.existsNode(instanceObject.getInstanceNodeset(), 1, locationPath, getPrefixMapping(),
            this.xpathFunctionContext)) {
        throw new XFormsSubmitError("nodeset is empty at: " + DOMUtil.getCanonicalPath(this.getElement()),
                this.getTarget(), XFormsSubmitError.constructInfoObject(this.element, this.container,
                        locationPath, XFormsConstants.NO_DATA, getResourceURI()));
    }

    //todo: when serialization is 'none' validation and relevance selection should be skipped if not explicitly set as attributes
    // validate instance items
    submitValidate(instanceObject, pathExpression, getPrefixMapping(), this.xpathFunctionContext);

    // select relevant items
    //todo: this should happen before submitValidate above according to spec - see the xforms-submit event
    Node instanceNode = submitSelectRelevant(instanceObject, pathExpression);

    Map response;
    try {
        // todo: should be supported by serializers
        /*
                    if (this.includenamespaceprefixes != null) {
        getLogger().warn(this + " submit: the 'includenamespaceprefixes' attribute is not supported yet");
                    }
        */

        processSubmissionOptions();

        // todo: refactor submission options to become a typed object, e.g. SubmissionOptions
        // todo: refactor submission response to become a typed object, e.g. SubmissionResponse
        // todo: refactor serializers to be set excplicitly

        // Look for resource submission option and possibly replace action
        // Implementation of the resource attribute version 1.1 feature
        // http://www.w3.org/TR/2007/CR-xforms11-20071129/#submit
        // chapter 11.1
        if (this.resource != null && this.resource.isAvailable()) {
            // obtain relative URI
            //                String relativeURI = null;
            //                relativeURI = instanceObject.getNodeValue(this.resource);
            //
            //                if (relativeURI != null) {
            //                    // resolve uri and assign to action
            //                    this.action = this.container.getConnectorFactory().getAbsoluteURI(relativeURI, this.element).toString();
            //                }
            this.action = getResourceURI();
        }

        //do xforms-submit-serialize handling
        final Element submissionBodyEl = this.element.getOwnerDocument().createElement("submission-body");
        final Map<String, Object> info = new HashMap<String, Object>();
        info.put(XFormsConstants.SUBMISSION_BODY,
                this.container.getDocumentWrapper(this.element).wrap(submissionBodyEl));

        this.container.dispatch(this.id, XFormsEventNames.SUBMIT_SERIALIZE, info);
        submissionBodyEl.normalize();

        // serialize and transmit instance items
        SubmissionHandler sh = this.container.getConnectorFactory().createSubmissionHandler(this.action,
                this.element);
        if (submissionBodyEl.getFirstChild() == null) {
            response = sh.submit(this, instanceNode);
        } else {
            response = sh.submit(this, submissionBodyEl.getFirstChild());
        }
    } catch (XFormsInternalSubmitException e) {
        Map<String, Object> info = XFormsSubmitError.constructInfoObject(this.element, this.container,
                locationPath, e.getErrorType(), getResourceURI(), e.getStatusCode(), null, e.getStatusText(),
                e.getResponseBodyAsString());
        throw new XFormsSubmitError(
                "instance submission failed at: " + DOMUtil.getCanonicalPath(this.getElement()), e,
                this.getTarget(), info);
    } catch (Exception e) {
        String errorType;
        if (e instanceof XFormsInternalSubmitException) {
            errorType = ((XFormsInternalSubmitException) e).getErrorType();
        } else {
            errorType = XFormsConstants.RESOURCE_ERROR;
        }
        Map<String, Object> info = XFormsSubmitError.constructInfoObject(this.element, this.container,
                locationPath, errorType, getResourceURI());

        //todo: hacky - event context info construction must be reviewed - using exception cause as response-reason-phrase for now
        if (e.getCause() != null && e.getCause().getMessage() != null) {
            info.put(RESPONSE_REASON_PHRASE, e.getCause().getMessage());
            if (e.getCause() instanceof XFormsInternalSubmitException) {
                info.put(RESPONSE_STATUS_CODE,
                        new Integer(((XFormsInternalSubmitException) e.getCause()).getStatusCode())
                                .doubleValue());
            }
        }
        throw new XFormsSubmitError(
                "instance submission failed at: " + DOMUtil.getCanonicalPath(this.getElement()), e,
                this.getTarget(), info);
        //throw new XFormsSubmitError("instance submission failed", e, this.getTarget(), this.action);
    }

    //todo: for async submits processing should stop here!!!
    // handle replace mode
    if (this.replace.equals("all")) {
        submitReplaceAll(response);
        return;
    }
    if (this.replace.equals("instance")) {
        submitReplaceInstance(response);
        return;
    }
    if (this.replace.equals("text")) {
        submitReplaceText(response);
        return;
    }
    if (this.replace.equals("none")) {
        submitReplaceNone(response);
        return;
    }
    if (this.replace.equals("embedHTML")) {
        submitReplaceEmbedHTML(response);
        return;
    }
    if (this.replace.equals("embedXFormsUI")) {
        submitReplaceEmbedXForms(response);
        return;
    }

    if (this.replace.equals("new")) {
        submitReplaceNew(response);
        return;
    }

    throw new XFormsSubmitError("unknown replace mode " + this.replace, this.getTarget(),
            XFormsSubmitError.constructInfoObject(this.element, this.container, locationPath,
                    XFormsConstants.VALIDATION_ERROR, getResourceURI()));
}

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

/**
*
* @return true if connection OK//from ww w. j  a  v a  2 s.co 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 ww  w. ja v  a  2  s.  c o  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: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  ww .  j ava 2 s  . c om
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);
    }

}