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:org.apache.manifoldcf.authorities.authorities.sharepoint.SPSProxyHelper.java

/**
*
* @return true if connection OK/*from   w w w. j a  va  2  s. c om*/
* @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.sterlingcommerce.xpedx.webchannel.services.XPEDXProcessPromptsAction.java

public String execute() {
    String username;/*from  w w w.  j  ava 2  s .c om*/
    String password;
    String authentication;
    String CMS;
    Map<String, String> promptData = new HashMap<String, String>();
    ReportUtils ru = new ReportUtils();
    List<String> promptsString = null;
    HttpHost _target = null;
    ArrayList<String> logonTokens = null;

    LOG.debug("++++ In XPEDXProcessPromptsAction.java ++++");
    Map<String, String[]> map = request.getParameterMap();

    // Ony when "All Locations" is selected
    String userId = wcContext.getLoggedInUserId();
    String[] strLocType = map.get("selectedLocationType");
    if (strLocType[0].equalsIgnoreCase("All")) {
        try {
            Document outputDoc = getAllLocationsDoc(userId);
            NodeList customerListElem = outputDoc.getElementsByTagName("Customer");
            if (customerListElem != null && customerListElem.getLength() > 0) {
                for (int m = 0; m < customerListElem.getLength(); m++) {
                    Element customerElem = (Element) customerListElem.item(m);
                    if (customerElem != null) {
                        String strCustId = SCXmlUtil.getAttribute(customerElem, "CustomerID");
                        Element extElement = (Element) customerElem.getFirstChild();
                        String extSuffixType = SCXmlUtil.getAttribute(extElement, "ExtnSuffixType");
                        // Checking For Account,Bill To, Ship to
                        // Modified For Jira 3216
                        if (extSuffixType.equalsIgnoreCase("C")) {
                            // if(strCustId.startsWith("CD") &&
                            // strCustId.endsWith("CC")) {
                            String account = getCustomerNo(strCustId);
                            accountList.add(account);
                        } else if (extSuffixType.equalsIgnoreCase("B") == true) {
                            // Fix to match Bill to cust id with the
                            // customer batch job. No need to send suffix,
                            // since we truncate it to 000 while migrating
                            // data
                            String billto = geteditedCustomerNo(strCustId);// +
                            // " - "
                            // +
                            // getShipToSuffix(strCustId);
                            billToList.add(billto);
                        } else if (extSuffixType.equalsIgnoreCase("S") == true) {
                            String shipto = geteditedCustomerNo(strCustId) + " - " + getShipToSuffix(strCustId);
                            shipToList.add(shipto);
                        }

                    }
                }
            }
        } catch (CannotBuildInputException e) {
            LOG.debug("Error Occured :->" + e.getMessage());

        }

    }

    //Logon to the CMS and retrieve a Token
    try {
        //ML - changed logic to read CMS Info from property file only once. 
        Map<String, String> CMSLogonDetails = ReportUtils.getCMSLogonDetails();
        username = CMSLogonDetails.get("username").toString();
        password = CMSLogonDetails.get("password").toString();
        authentication = CMSLogonDetails.get("authentication").toString();
        CMS = CMSLogonDetails.get("CMS").toString();
        //postpone setting _target until CMS is read to avoid calling getCMSLogonDetails() more than once. 
        _target = ru.getHttpHost(CMS);

        //ML:Find out if logonTokens is in session. If not, then go get a new one and store it in the session. 
        //this logic should be reused across this "Report List" page, the "Report Details" page, and the ReportDisplay page to avoid
        //creating too many sessions and violate the SAP license agreement. 
        logonTokens = (ArrayList) request.getSession().getAttribute("logonTokens");
        if ((logonTokens == null) || (logonTokens.size() != 2)) {
            logonTokens = ru.logonCMS(username, password, authentication, _target);
            //store the logonTokens in session for future use
            request.getSession().setAttribute("logonTokens", logonTokens);
        }

    } catch (Exception e) {
        System.out.println("Could not logon to BI/CMS using the supplied credentials.");
        e.printStackTrace();
    }
    Boolean isOK = true;
    if (logonTokens.size() < 2) {
        System.out.println("No Tokens Found");
        isOK = false;
    }
    if (isOK) {
        try {
            promptsString = ru.getPromptsAsString(getId(), _target, logonTokens.get(0));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    for (int i = 0; i < promptsString.size(); i++) {
        String promptName = promptsString.get(i);

        String[] paramStringArray = (String[]) map.get(promptName);

        String promptNameArray[] = promptName.split("_");
        String suffix = null;
        String prefix = null;
        if (promptNameArray.length >= 2)
            suffix = promptNameArray[1];
        prefix = promptNameArray[0];

        if (prefix.equalsIgnoreCase("ddls") && suffix != null && suffix.equalsIgnoreCase("account:")) {
            strLocType = map.get("selectedLocationType");
            // Only when account has been selected on webiprompt screen
            if (strLocType[0].equalsIgnoreCase("account")) {
                String[] strSapId = request.getParameterValues("selectedCustId");
                String temp[] = new String[1];
                temp[0] = getCustomerNo(strSapId[0]);
                LOG.debug("****For Prompt " + promptName + ", Value Passed Is= " + temp[0]);
                promptData.put(promptName, temp[0]);

            } else if (strLocType[0].equalsIgnoreCase("All")) {
                String array[] = (String[]) accountList.toArray(new String[accountList.size()]);
                String arrayCSF = "";
                for (int m = 0; m < array.length; m++) {
                    if (m == array.length - 1)
                        arrayCSF = arrayCSF + array[m];
                    else
                        arrayCSF = arrayCSF + array[m] + ";";
                    LOG.debug("**** When All Authorized, For Prompt " + promptName + " Value Passed Is= "
                            + array[m]);
                }

                promptData.put(promptName, arrayCSF);

            } else {
                LOG.debug("Entering null values for " + promptName);
            }
        }

        if (prefix.equalsIgnoreCase("ddls") && suffix != null && suffix.equalsIgnoreCase("Ship To:")) {
            strLocType = map.get("selectedLocationType");
            // Only when ship to has been selected on webiprompt screen
            if (strLocType[0].equalsIgnoreCase("Ship To")) {
                String[] strSapId = request.getParameterValues("selectedCustId");
                String temp[] = new String[1];
                temp[0] = geteditedCustomerNo(strSapId[0]) + " - " + getShipToSuffix(strSapId[0]);
                LOG.debug("****For Prompt " + promptName + ", Value Passed Is= " + temp[0]);
                promptData.put(promptName, temp[0]);

            } else if (strLocType[0].equalsIgnoreCase("All")) {
                String array[] = (String[]) shipToList.toArray(new String[shipToList.size()]);
                String arrayCSF = "";
                for (int m = 0; m < array.length; m++) {
                    if (m == array.length - 1)
                        arrayCSF = arrayCSF + array[m];
                    else
                        arrayCSF = arrayCSF + array[m] + ";";
                    LOG.debug("**** When All Authorized, For Prompt " + promptName + " Value Passed Is= "
                            + array[m]);
                }
                promptData.put(promptName, arrayCSF);

            } else {
                LOG.debug("Entering null values for " + promptName);
            }
        }

        if (prefix.equalsIgnoreCase("ddls") && suffix != null && suffix.equalsIgnoreCase("Bill To:")) {
            strLocType = map.get("selectedLocationType");
            // Only when Bill To has been selected on webiprompt screen
            if (strLocType[0].equalsIgnoreCase("Bill To")) {
                String[] strSapId = request.getParameterValues("selectedCustId");
                String temp[] = new String[1];
                // Fix to match Bill to cust id with the customer batch job.
                // No need to send suffix, since we truncate it to 000 while
                // migrating data
                temp[0] = geteditedCustomerNo(strSapId[0]); // + " - " +
                // getShipToSuffix(strSapId[0]);
                LOG.debug("****For Prompt " + promptName + ", Value Passed Is= " + temp[0]);
                promptData.put(promptName, temp[0]);

            } else if (strLocType[0].equalsIgnoreCase("All")) {
                String array[] = (String[]) billToList.toArray(new String[billToList.size()]);
                String arrayCSF = "";
                for (int m = 0; m < array.length; m++) {
                    if (m == array.length - 1)
                        arrayCSF = arrayCSF + array[m];
                    else
                        arrayCSF = arrayCSF + array[m] + ";";
                    LOG.debug("**** When All Authorized, For Prompt " + promptName + " Value Passed Is= "
                            + array[m]);
                }

                promptData.put(promptName, arrayCSF);

            } else {
                LOG.debug("Entering null values for " + promptName);
            }
        }

        if (errorList.size() == 0) {
            if (paramStringArray != null && paramStringArray.length > 0 && paramStringArray[0] != null
                    && !paramStringArray[0].equals("")) {
                for (int m = 0; m < paramStringArray.length; m++) {
                    LOG.debug("****For Prompt " + promptName + ", Value Passed Is= " + paramStringArray[m]);
                }

                if ("caln".equals(prefix)) {
                    String dateValue = paramStringArray[0];
                    String dateSplitValue[] = dateValue.split("/");
                    dateValue = "DateTime(" + dateSplitValue[2] + "," + dateSplitValue[0] + ","
                            + dateSplitValue[1] + ",0,0,0)";
                    paramStringArray[0] = dateValue;
                }

                promptData.put(promptName, paramStringArray[0]);
            } else {
                if (!prefix.equalsIgnoreCase("ddls") && suffix != null) {
                    LOG.debug("Entering null values for " + promptName);
                }
            }
        }
    } //end of FOR LOOP

    if (errorList.size() > 0) {
        if (log.isDebugEnabled()) {
            log.debug(".............error list greater than 0............................");
        }
        setRndrReport("false");
        Iterator<String> iterator = errorList.iterator();
        while (iterator.hasNext()) {
            log.error("errorList+++++++++++" + iterator.next());
        }

    } else {

        String params = "";
        String openDocURL = "";
        try {
            openDocURL = ru.getOpenDoc(getId(), _target, logonTokens.get(0));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        if (!("").equals(openDocURL)) {
            try {
                params = ru.getParamString(getId(), _target, logonTokens.get(0), promptData);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            setRndrReport("true");

            String encodedToken = logonTokens.get(1);

            finalURL = openDocURL + params + "&token=" + encodedToken + "&sRefresh=Y";
        }

    }

    return SUCCESS;
}

From source file:com.portfolio.data.attachment.XSLService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**//from w w w  .  j av  a  2s  .  co  m
     * Format demand:
     * <convert>
     *   <portfolioid>{uuid}</portfolioid>
     *   <portfolioid>{uuid}</portfolioid>
     *   <nodeid>{uuid}</nodeid>
     *   <nodeid>{uuid}</nodeid>
     *   <documentid>{uuid}</documentid>
     *   <xsl>{rpertoire}{fichier}</xsl>
     *   <format>[pdf rtf xml ...]</format>
     *   <parameters>
     *     <maVar1>lala</maVar1>
     *     ...
     *   </parameters>
     * </convert>
     */
    try {
        //On initialise le dataProvider
        Connection c = null;
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String origin = request.getRequestURL().toString();

    /// Variable stuff
    int userId = 0;
    int groupId = 0;
    String user = "";
    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    /// TODO: A voire si un form get ne ferait pas l'affaire aussi

    /// On lis le xml
    /*
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while( (line = rd.readLine()) != null )
       sb.append(line);
            
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    Document doc=null;
    try
    {
       documentBuilder = documentBuilderFactory.newDocumentBuilder();
       doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
            
    /// On lit les paramtres
    NodeList portfolioNode = doc.getElementsByTagName("portfolioid");
    NodeList nodeNode = doc.getElementsByTagName("nodeid");
    NodeList documentNode = doc.getElementsByTagName("documentid");
    NodeList xslNode = doc.getElementsByTagName("xsl");
    NodeList formatNode = doc.getElementsByTagName("format");
    NodeList parametersNode = doc.getElementsByTagName("parameters");
    //*/
    //      String xslfile = xslNode.item(0).getTextContent();
    String xslfile = request.getParameter("xsl");
    String format = request.getParameter("format");
    //      String format = formatNode.item(0).getTextContent();
    String parameters = request.getParameter("parameters");
    String documentid = request.getParameter("documentid");
    String portfolios = request.getParameter("portfolioids");
    String[] portfolioid = null;
    if (portfolios != null)
        portfolioid = portfolios.split(";");
    String nodes = request.getParameter("nodeids");
    String[] nodeid = null;
    if (nodes != null)
        nodeid = nodes.split(";");

    System.out.println("PARAMETERS: ");
    System.out.println("xsl: " + xslfile);
    System.out.println("format: " + format);
    System.out.println("user: " + userId);
    System.out.println("portfolioids: " + portfolios);
    System.out.println("nodeids: " + nodes);
    System.out.println("parameters: " + parameters);

    boolean redirectDoc = false;
    if (documentid != null) {
        redirectDoc = true;
        System.out.println("documentid @ " + documentid);
    }

    boolean usefop = false;
    String ext = "";
    if (MimeConstants.MIME_PDF.equals(format)) {
        usefop = true;
        ext = ".pdf";
    } else if (MimeConstants.MIME_RTF.equals(format)) {
        usefop = true;
        ext = ".rtf";
    }
    //// Paramtre portfolio-uuid et file-xsl
    //      String uuid = request.getParameter("uuid");
    //      String xslfile = request.getParameter("xsl");

    StringBuilder aggregate = new StringBuilder();
    try {
        int portcount = 0;
        int nodecount = 0;
        // On aggrge les donnes
        if (portfolioid != null) {
            portcount = portfolioid.length;
            for (int i = 0; i < portfolioid.length; ++i) {
                String p = portfolioid[i];
                String portfolioxml = dataProvider
                        .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0)
                        .toString();
                aggregate.append(portfolioxml);
            }
        }

        if (nodeid != null) {
            nodecount = nodeid.length;
            for (int i = 0; i < nodeid.length; ++i) {
                String n = nodeid[i];
                String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "")
                        .toString();
                aggregate.append(nodexml);
            }
        }

        // Est-ce qu'on a eu besoin d'aggrger les donnes?
        String input = aggregate.toString();
        String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration

        input = input.replaceAll(pattern, "");

        input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet ["
                + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir
                + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \""
                + servletDir + "xhtml-symbol.ent\">"
                + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir
                + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters
                "<root>" + input + "</root>";

        //         System.out.println("INPUT WITH PROXY:"+ input);

        /// Rsolution des proxys
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(input));
        Document doc = documentBuilder.parse(is);

        /// Proxy stuff
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//asmResource[@xsi_type='Proxy']";
        String filterCode = "./code/text()";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        XPathExpression codeFilter = xPath.compile(filterCode);

        for (int i = 0; i < nodelist.getLength(); ++i) {
            Node res = nodelist.item(i);
            Node gp = res.getParentNode(); // resource -> context -> container
            Node ggp = gp.getParentNode();
            Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE);

            /// Fetch node we want to replace
            String returnValue = dataProvider
                    .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "")
                    .toString();

            Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue)));
            Element repNode = rep.getDocumentElement();
            Node proxyNode = repNode.getFirstChild();
            proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned
            //            doc.replaceChild(proxyNode, gp);
            ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work.
            ggp.removeChild(gp);
        }

        try // Convert XML document to string
        {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            writer.flush();
            input = writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }

        //         System.out.println("INPUT DATA:"+ input);

        // Setup a buffer to obtain the content length
        ByteArrayOutputStream stageout = new ByteArrayOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //// Setup Transformer (1st stage)
        /// Base path
        String basepath = xslfile.substring(0, xslfile.indexOf(File.separator));
        String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator
                + "xsl" + File.separator + "html2xml.xsl";
        System.out.println("FIRST: " + firstStage);
        Source xsltSrc1 = new StreamSource(new File(firstStage));
        Transformer transformer1 = transFactory.newTransformer(xsltSrc1);
        StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes()));
        Result stageRes = new StreamResult(stageout);
        transformer1.transform(stageSource, stageRes);

        // Setup Transformer (2nd stage)
        String secondStage = baseDir + File.separator + xslfile;
        Source xsltSrc2 = new StreamSource(new File(secondStage));
        Transformer transformer2 = transFactory.newTransformer(xsltSrc2);

        // Configure parameter from xml
        String[] table = parameters.split(";");
        for (int i = 0; i < table.length; ++i) {
            String line = table[i];
            int var = line.indexOf(":");
            String par = line.substring(0, var);
            String val = line.substring(var + 1);
            transformer2.setParameter(par, val);
        }

        // Setup input
        StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes()));
        //         StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") );

        Result res = null;
        if (usefop) {
            /// FIXME: Might need to include the entity for html stuff?
            //Setup FOP
            //Make sure the XSL transformation's result is piped through to FOP
            Fop fop = fopFactory.newFop(format, out);

            res = new SAXResult(fop.getDefaultHandler());

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        } else {
            res = new StreamResult(out);

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        }

        if (redirectDoc) {

            // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]
            String urlTarget = "http://" + server + "/resources/resource/file/" + documentid;
            System.out.println("Redirect @ " + urlTarget);

            HttpClientBuilder clientbuilder = HttpClientBuilder.create();
            CloseableHttpClient client = clientbuilder.build();

            HttpPost post = new HttpPost(urlTarget);
            post.addHeader("referer", origin);
            String sessionid = request.getSession().getId();
            System.out.println("Session: " + sessionid);
            post.addHeader("Cookie", "JSESSIONID=" + sessionid);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext);

            builder.addPart("uploadfile", body);

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse ret = client.execute(post);
            String stringret = new BasicResponseHandler().handleResponse(ret);

            int code = ret.getStatusLine().getStatusCode();
            response.setStatus(code);
            ServletOutputStream output = response.getOutputStream();
            output.write(stringret.getBytes(), 0, stringret.length());
            output.close();
            client.close();

            /*
            HttpURLConnection connection = CreateConnection( urlTarget, request );
                    
            /// Helping construct Json
            connection.setRequestProperty("referer", origin);
                    
            /// Send post data
            ServletInputStream inputData = request.getInputStream();
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
                    
            byte[] buffer = new byte[1024];
            int dataSize;
            while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
            {
               writer.write(buffer, 0, dataSize);
            }
            inputData.close();
            writer.close();
                    
            RetrieveAnswer(connection, response, origin);
            //*/
        } else {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=generated" + ext);
            response.setContentType(format);
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        String message = e.getMessage();
        response.setStatus(500);
        response.getOutputStream().write(message.getBytes());
        response.getOutputStream().close();

        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }
}

From source file:com.amalto.workbench.actions.XSDAddComplexTypeElementAction.java

public Map<String, List<String>> cloneXSDAnnotation(XSDAnnotation oldAnn) {
    Map<String, List<String>> infor = new HashMap<String, List<String>>();
    try {/*ww w . j  av  a2  s.  co  m*/
        if (oldAnn != null) {
            for (int i = 0; i < oldAnn.getApplicationInformation().size(); i++) {
                Element oldElem = oldAnn.getApplicationInformation().get(i);
                String type = oldElem.getAttributes().getNamedItem("source").getNodeValue(); //$NON-NLS-1$
                // X_Write,X_Hide,X_Workflow
                if (type.equals("X_Write") || type.equals("X_Hide") || type.equals("X_Workflow")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    if (!infor.containsKey(type)) {
                        List<String> typeList = new ArrayList<String>();
                        typeList.add(oldElem.getFirstChild().getNodeValue());
                        infor.put(type, typeList);
                    } else {
                        (infor.get(type)).add(oldElem.getFirstChild().getNodeValue());
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(this.page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages._PasteError, e.getLocalizedMessage()));
    }
    return infor;
}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

/**
 * Saves the configuration.//w w  w  .  j  a va2 s  .com
 * @see IConfigurationManager#saveConfiguration()
 */
public synchronized void saveConfiguration() throws ConfigurationException {
    boolean bFound = false;
    Date dNow = null;
    StringBuffer sbComment = null;
    Element elRoot = null;
    Node nCurrent = null;
    Node nComment = null;
    String sValue = null;
    try {
        // add date to configuration
        dNow = new Date(System.currentTimeMillis());

        sbComment = new StringBuffer(" Configuration changes saved on ");
        sbComment.append(DateFormat.getDateInstance().format(dNow));
        sbComment.append(". ");

        elRoot = _oDomDocument.getDocumentElement();
        nCurrent = elRoot.getFirstChild();
        while (!bFound && nCurrent != null) // all elements
        {
            if (nCurrent.getNodeType() == Node.COMMENT_NODE) {
                // check if it's a "save changes" comment
                sValue = nCurrent.getNodeValue();
                if (sValue.trim().startsWith("Configuration changes saved on")) {
                    // overwrite message
                    nCurrent.setNodeValue(sbComment.toString());
                    bFound = true;
                }
            }
            nCurrent = nCurrent.getNextSibling();
        }
        if (!bFound) // no comment found: adding new
        {
            // create new comment node
            nComment = _oDomDocument.createComment(sbComment.toString());
            // insert comment before first node
            elRoot.insertBefore(nComment, elRoot.getFirstChild());
        }
        _oConfigHandler.saveConfiguration(_oDomDocument);
    } catch (ConfigurationException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error", e);
        throw new ConfigurationException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:com.amalto.workbench.utils.XSDParser.java

/**
 * Load the XML Schema file and print the documentation based on it.
 * //from  w  w  w  .  j a va2 s.  c o m
 * @param xsdFile the name of an XML Schema file.
 */
public void loadAndPrint(String xsd) throws Exception {
    // XSDFactory xsdFactory = XSDFactory.eINSTANCE;

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setValidating(false);
    InputSource source = new InputSource(new StringReader(xsd));
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(source);
    XSDSchema xsdSchema = XSDSchemaImpl.createSchema(document.getDocumentElement());

    // Create a resource set and load the main schema file into it.
    //
    /*
     * ResourceSet resourceSet = new ResourceSetImpl(); XSDResourceImpl xsdResource = (XSDResourceImpl) resourceSet
     * .getResource(URI.createFileURI(xsdFile), true);
     * 
     * XSDResourceImpl res = new XSDResourceImpl();
     * 
     * XSDSchema xsdSchema = xsdResource.getSchema();
     */

    String elementContentHeaderDocumentation = getContentDocumentation("element-header"); //$NON-NLS-1$
    if (elementContentHeaderDocumentation != null) {
        System.out.println(elementContentHeaderDocumentation);
    }

    List all = new ArrayList(xsdSchema.getElementDeclarations());

    for (Iterator iter = all.iterator(); iter.hasNext();) {
        XSDElementDeclaration concept = (XSDElementDeclaration) iter.next();
        System.out
                .println("CONCEPT: " + concept.getName() + "-- " + concept.getContainer().getClass().getName()); //$NON-NLS-1$ //$NON-NLS-2$

        // name of the concept in English
        XSDAnnotation annotation = concept.getAnnotation();
        if (annotation != null) {
            EList list = annotation.getApplicationInformation();
            for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                Element appinfo = (Element) iterator.next();
                String language = appinfo.getAttribute("source"); //$NON-NLS-1$
                if ("EN".equals(language.toUpperCase())) { //$NON-NLS-1$
                    if (appinfo.getFirstChild() != null)
                        System.out.println("     " + appinfo.getFirstChild().getNodeValue()); //$NON-NLS-1$
                }
            }
        }

        // children
        XSDTypeDefinition typedef = concept.getTypeDefinition();
        if (typedef instanceof XSDComplexTypeDefinition) {
            XSDComplexTypeContent xsdContent = ((XSDComplexTypeDefinition) typedef).getContent();
            XSDParticle xsdParticle = (XSDParticle) xsdContent;
            String ident = "    "; //$NON-NLS-1$
            processParticle(xsdParticle, ident);
        }

    } // for elements
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

private void mergeArguments(Document templateDocument, TemplateContext templateContext) throws Exception {
    Document document = templateContext.getSourceDocument();
    Map<String, Element> argumentMap = getArgumentElements(document, templateContext.getSourceContext());
    Map<String, Element> templateArgumentMap = getArgumentElements(templateDocument, templateContext);

    if (!argumentMap.isEmpty()) {
        Element templateDocumentElement = templateDocument.getDocumentElement();
        Element argumentsElement = ViewConfigParserUtils.findArgumentsElement(templateDocumentElement,
                templateContext.getResource());
        if (argumentsElement == null) {
            argumentsElement = templateDocument.createElement(ViewXmlConstants.ARGUMENTS);
            templateDocumentElement.insertBefore(argumentsElement, templateDocumentElement.getFirstChild());
        }//  ww  w. j a  va  2s  .  co  m

        for (Map.Entry<String, Element> entry : argumentMap.entrySet()) {
            String name = entry.getKey();
            if (templateArgumentMap == null || !templateArgumentMap.containsKey(name)) {
                Element element = entry.getValue();
                Element clonedElement = (Element) templateDocument.importNode(element, true);
                argumentsElement.appendChild(clonedElement);
            }
        }
    }
}

From source file:com.enonic.vertical.engine.handlers.ContentObjectHandler.java

public void copyContentObjectsPostOp(int oldMenuKey, CopyContext copyContext) throws VerticalCopyException {

    boolean includeContents = copyContext.isIncludeContents();
    int newMenuKey = copyContext.getMenuKey(oldMenuKey);

    try {/*from   w ww.jav  a2  s . c  o  m*/
        Document doc = getContentObjectsByMenu(newMenuKey);
        Element[] contentobjectElems = XMLTool.getElements(doc.getDocumentElement());

        for (Element contentobjectElem : contentobjectElems) {
            Element codElem = XMLTool.getElement(contentobjectElem, "contentobjectdata");

            // datasource
            NodeList parameterList = XMLTool.selectNodes(codElem,
                    "datasources/datasource/parameters/parameter");
            for (int k = 0; k < parameterList.getLength(); k++) {
                Element parameterElem = (Element) parameterList.item(k);
                String name = parameterElem.getAttribute("name");
                if ("cat".equalsIgnoreCase(name)) {
                    Text text = (Text) parameterElem.getFirstChild();
                    if (text != null) {
                        String oldCategoryKeys = text.getData();

                        Matcher m = CATEGORY_KEYLIST_PATTERN.matcher(oldCategoryKeys);
                        if (m.matches()) {
                            StringBuffer data = translateCategoryKeys(copyContext, oldCategoryKeys);
                            text.setData(data.toString());
                        }
                    }
                } else if ("menu".equalsIgnoreCase(name)) {
                    Text text = (Text) parameterElem.getFirstChild();
                    if (text != null) {
                        int oldKey = Integer.parseInt(text.getData());
                        int newKey = copyContext.getMenuKey(oldKey);
                        if (newKey >= 0) {
                            text.setData(String.valueOf(newKey));
                        } else {
                            text.setData(String.valueOf(oldKey));
                        }
                    }
                }
            }

            // stylesheet parameters
            NodeList stylesheetparamList = XMLTool.selectNodes(codElem, "stylesheetparams/stylesheetparam");
            for (int k = 0; k < stylesheetparamList.getLength(); k++) {
                Element stylesheetparamElem = (Element) stylesheetparamList.item(k);
                String type = stylesheetparamElem.getAttribute("type");
                if ("page".equals(type)) {
                    Text text = (Text) stylesheetparamElem.getFirstChild();
                    if (text != null) {
                        String oldMenuItemKey = text.getData();
                        if (oldMenuItemKey != null && oldMenuItemKey.length() > 0) {
                            int newMenuItemKey = copyContext.getMenuItemKey(Integer.parseInt(oldMenuItemKey));
                            if (newMenuItemKey >= 0) {
                                text.setData(String.valueOf(newMenuItemKey));
                            } else {
                                XMLTool.removeChildNodes(stylesheetparamElem, true);
                            }
                        } else {
                            XMLTool.removeChildNodes(stylesheetparamElem, true);
                        }
                    }
                }
            }

            // border parameters
            NodeList borderparamList = XMLTool.selectNodes(codElem, "borderparams/borderparam");
            for (int k = 0; k < borderparamList.getLength(); k++) {
                Element borderparamElem = (Element) borderparamList.item(k);
                String type = borderparamElem.getAttribute("type");
                if ("page".equals(type)) {
                    Text text = (Text) borderparamElem.getFirstChild();
                    if (text != null) {
                        String oldMenuItemKey = text.getData();
                        if (oldMenuItemKey != null && oldMenuItemKey.length() > 0) {
                            int newMenuItemKey = copyContext.getMenuItemKey(Integer.parseInt(oldMenuItemKey));
                            if (newMenuItemKey >= 0) {
                                text.setData(String.valueOf(newMenuItemKey));
                            } else {
                                XMLTool.removeChildNodes(borderparamElem, true);
                            }
                        } else {
                            XMLTool.removeChildNodes(borderparamElem, true);
                        }
                    }
                }
            }
        }

        updateContentObject(doc);
    } catch (VerticalUpdateException vue) {
        String message = "Failed to copy content objects (post operation): %t";
        VerticalEngineLogger.errorCopy(this.getClass(), 0, message, vue);
    }
}

From source file:de.huberlin.wbi.hiway.am.galaxy.GalaxyApplicationMaster.java

/**
 * A helper function for processing the Galaxy config file that specifies metadata for data tables along with the location of their loc files
 * /*from w ww. j av  a 2 s . c o m*/
 * @param file
 *            the Galaxy data table config file
 */
private void processDataTables(File file) {
    try {
        System.out.println("Processing Galaxy data table config file " + file.getCanonicalPath());
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(file);
        NodeList tables = doc.getElementsByTagName("table");
        for (int i = 0; i < tables.getLength(); i++) {
            Element tableEl = (Element) tables.item(i);
            Element columnsEl = (Element) tableEl.getElementsByTagName("columns").item(0);
            Element fileEl = (Element) tableEl.getElementsByTagName("file").item(0);
            String name = tableEl.getAttribute("name");
            String comment_char = tableEl.getAttribute("comment_char");
            String[] columns = columnsEl.getFirstChild().getNodeValue().split(", ");
            if (!fileEl.hasAttribute("path"))
                continue;
            String path = fileEl.getAttribute("path");
            if (!path.startsWith("/"))
                path = galaxyPath + "/" + path;
            GalaxyDataTable galaxyDataTable = new GalaxyDataTable(name, comment_char, columns, path);
            processLocFile(new File(path), galaxyDataTable);
            galaxyDataTables.put(name, galaxyDataTable);
        }

    } catch (SAXException | IOException | ParserConfigurationException e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

private MetadataAVUList parseMetadata(NodeList avuNodes) {
    MetadataAVUList avuList = new MetadataAVUList();
    if (avuNodes != null) {
        for (int a = 0; a < avuNodes.getLength(); a++) {
            Element avuNode = (Element) avuNodes.item(a);
            avuList.add(new MetadataAVU(avuNode.getAttribute("id").toUpperCase(),
                    avuNode.getFirstChild().getNodeValue()));
        }/*from  w  w  w  . j a  v  a  2s .  co  m*/
    }
    return avuList;
}