Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:it.imtech.metadata.MetaUtility.java

private void removeClassificationToMetadata(String panelname) {
    try {//w  ww  .jav a2s . com
        System.out.println("Search for lest classification..");

        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc;

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();

        //File backupmetadata = new File(Globals.SESSION_METADATA);
        File backupmetadata = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);
        doc = dBuilder.parse(backupmetadata);

        String expression = "//*[@ID='22']";
        NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
        int maxseq = 0;
        int tmpseq;

        for (int i = 0; i < nodeList.getLength(); i++) {
            NamedNodeMap attr = nodeList.item(i).getAttributes();
            Node nodeAttr = attr.getNamedItem("sequence");
            tmpseq = Integer.parseInt(nodeAttr.getNodeValue());

            if (tmpseq > maxseq) {
                maxseq = tmpseq;
            }
        }

        int nLast, idLast, counter = 0;

        for (int i = 0; i < nodeList.getLength(); i++) {
            NamedNodeMap attr = nodeList.item(i).getAttributes();
            Node nodeAttr = attr.getNamedItem("sequence");
            if (maxseq == Integer.parseInt(nodeAttr.getNodeValue())) {
                nLast = counter;
                nodeAttr = attr.getNamedItem("ID");
                idLast = Integer.parseInt(nodeAttr.getNodeValue());
                nodeList.item(i).getParentNode().removeChild(nodeList.item(i));
            }
            counter++;
        }

        Element root = doc.getDocumentElement(); // ripristino sequenze esatte
        NodeList firstlevelnodes = root.getChildNodes();

        for (int i = 0; i < firstlevelnodes.getLength(); i++) {
            if (firstlevelnodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element node = (Element) firstlevelnodes.item(i);
                Integer sequence = Integer.parseInt(node.getAttribute("sequence"));
                if (!node.getAttribute("ID").equals("22") && sequence >= maxseq) {
                    node.setAttribute("sequence", Integer.toString(sequence - 1));
                }
            }
        }

        XMLUtil.xmlWriter(doc, Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);
    } catch (ParserConfigurationException ex) {
        logger.error(ex.getMessage());
    } catch (SAXException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } catch (XPathExpressionException ex) {
        logger.error(ex.getMessage());
    }
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

private static Reservation readPrice(SqlSession sqlSession, Reservation reservation, String productAltId) {
    StringBuilder sb = new StringBuilder();
    Date now = new Date();
    long time = now.getTime();
    String SenderSessionID = time + "bookingnetS";
    String ReceiverSessionID = time + "bookingnetR";
    String rq;/*from ww  w. j  ava 2 s  .c  o  m*/
    String rs = null;

    try {
        sb.append("<?xml version='1.0' ?>");
        sb.append("<TravelMessage VersionID='1.8N'>");
        sb.append(" <Control Language='NL' Test='nee'>");
        sb.append("    <SenderSessionID>" + SenderSessionID + "</SenderSessionID>");
        sb.append("    <ReceiverSessionID>" + ReceiverSessionID + "</ReceiverSessionID>");
        sb.append("    <Date>" + DF.format(new Date()) + "</Date>");
        sb.append("    <Time Reliability='zeker'>" + TF.format(new Date()) + "</Time>");
        sb.append("   <MessageSequence>1</MessageSequence>");
        sb.append("   <SenderID>" + SENDERID + "</SenderID>");
        sb.append("  <ReceiverID>NPS001</ReceiverID>");
        sb.append("   <RequestID>AvailabilitybookingnetRequest</RequestID>");
        sb.append("   <ResponseID>AvailabilitybookingnetResponse</ResponseID>");
        sb.append(" </Control>");
        sb.append("  <TRequest>");
        sb.append("    <AvailabilitybookingnetRequest>");
        sb.append("      <PackageDetails WaitListCheck='ja'>");
        sb.append("          <AccommodationID>" + "A" + productAltId + "</AccommodationID>");
        sb.append("          <ArrivalDate>" + DF.format(reservation.getFromdate()) + "</ArrivalDate>");
        sb.append("        <Duration DurationType='dagen'>" + reservation.getDuration(Time.DAY).intValue()
                + "</Duration>");
        sb.append("     </PackageDetails>");
        sb.append("   </AvailabilitybookingnetRequest>");
        sb.append("  </TRequest>");
        sb.append("</TravelMessage>");

        rq = sb.toString();
        rs = getConnection(rq); // fix code have better support. gettting errors when deploying with tomcat.

        LOG.debug("computePrice rq: \n" + rq + "\n");
        LOG.debug("computePrice rs: \n" + rs + "\n");

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        InputSource inputSource = new InputSource(new StringReader(rs.toString()));
        Double price = (Double) xpath.evaluate("//Price", inputSource, XPathConstants.NUMBER);
        if (Double.isNaN(price)) {
            throw new ServiceException(Error.product_not_available);
        }

        price = price / 100.00; //price is a whole number

        factory = XPathFactory.newInstance();
        xpath = factory.newXPath();
        inputSource = new InputSource(new StringReader(rs.toString()));
        String fromCurrency = (String) xpath.evaluate("//Price/@Currency", inputSource, XPathConstants.STRING);
        if ("".equals(fromCurrency)) {
            throw new ServiceException(Error.price_missing, reservation.getId() + " State = "
                    + reservation.getState() + " currency = " + reservation.getCurrency());
        }
        String tocurrency = reservation.getCurrency();
        if (!fromCurrency.equalsIgnoreCase(tocurrency)) {
            // Double rate = OpenExchangeRates.getExchangeRate(currency,rescurrency);
            Double rate = WebService.getRate(sqlSession, fromCurrency, tocurrency, new Date());
            price = rate * price;
        }

        LOG.debug("price = " + price);
        reservation.setPrice(price);
        reservation.setQuote(price);
    } catch (Throwable e) {
        LOG.error(e.getMessage());
        reservation.setPrice(0.00);
    }
    return reservation;
}

From source file:com.rapid.server.Designer.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    RapidRequest rapidRequest = new RapidRequest(this, request);

    try {/*  ww w  .j av  a 2 s  . c o m*/

        String output = "";

        // read bytes from request body into our own byte array (this means we can deal with images) 
        InputStream input = request.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        for (int length = 0; (length = input.read(_byteBuffer)) > -1;)
            outputStream.write(_byteBuffer, 0, length);
        byte[] bodyBytes = outputStream.toByteArray();

        // get the rapid application
        Application rapidApplication = getApplications().get("rapid");

        // check we got one
        if (rapidApplication != null) {

            // get rapid security
            SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter();

            // check we got some
            if (rapidSecurity != null) {

                // get user name
                String userName = rapidRequest.getUserName();
                if (userName == null)
                    userName = "";

                // check permission
                if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) {

                    Application application = rapidRequest.getApplication();

                    if (application != null) {

                        if ("savePage".equals(rapidRequest.getActionName())) {

                            String bodyString = new String(bodyBytes, "UTF-8");

                            getLogger().debug("Designer POST request : " + request.getQueryString() + " body : "
                                    + bodyString);

                            JSONObject jsonPage = new JSONObject(bodyString);

                            // instantiate a new blank page
                            Page newPage = new Page();

                            // set page properties
                            newPage.setId(jsonPage.optString("id"));
                            newPage.setName(jsonPage.optString("name"));
                            newPage.setTitle(jsonPage.optString("title"));
                            newPage.setFormPageType(jsonPage.optInt("formPageType"));
                            newPage.setLabel(jsonPage.optString("label"));
                            newPage.setDescription(jsonPage.optString("description"));
                            newPage.setSimple(jsonPage.optBoolean("simple"));

                            // look in the JSON for an event array
                            JSONArray jsonEvents = jsonPage.optJSONArray("events");
                            // add the events if we found one
                            if (jsonEvents != null)
                                newPage.setEvents(Control.getEvents(this, jsonEvents));

                            // look in the JSON for a styles array
                            JSONArray jsonStyles = jsonPage.optJSONArray("styles");
                            // if there were styles
                            if (jsonStyles != null)
                                newPage.setStyles(Control.getStyles(this, jsonStyles));

                            // if there are child controls from the page loop them and add to the pages control collection
                            JSONArray jsonControls = jsonPage.optJSONArray("childControls");
                            if (jsonControls != null) {
                                for (int i = 0; i < jsonControls.length(); i++) {
                                    // get the JSON control
                                    JSONObject jsonControl = jsonControls.getJSONObject(i);
                                    // call our function so it can go iterative
                                    newPage.addControl(createControl(jsonControl));
                                }
                            }

                            // if there are roles specified for this page
                            JSONArray jsonUserRoles = jsonPage.optJSONArray("roles");
                            if (jsonUserRoles != null) {
                                List<String> userRoles = new ArrayList<String>();
                                for (int i = 0; i < jsonUserRoles.length(); i++) {
                                    // get the JSON role
                                    String jsonUserRole = jsonUserRoles.getString(i);
                                    // add to collection
                                    userRoles.add(jsonUserRole);
                                }
                                // assign to page
                                newPage.setRoles(userRoles);
                            }

                            // look in the JSON for a sessionVariables array
                            JSONArray jsonSessionVariables = jsonPage.optJSONArray("sessionVariables");
                            // if we found one
                            if (jsonSessionVariables != null) {
                                List<String> sessionVariables = new ArrayList<String>();
                                for (int i = 0; i < jsonSessionVariables.length(); i++) {
                                    sessionVariables.add(jsonSessionVariables.getString(i));
                                }
                                newPage.setSessionVariables(sessionVariables);
                            }

                            // look in the JSON for a pageVisibilityRules array
                            JSONArray jsonVisibilityConditions = jsonPage.optJSONArray("visibilityConditions");
                            // if we found one
                            if (jsonVisibilityConditions != null) {
                                List<Condition> visibilityConditions = new ArrayList<Condition>();
                                for (int i = 0; i < jsonVisibilityConditions.length(); i++) {
                                    visibilityConditions
                                            .add(new Condition(jsonVisibilityConditions.getJSONObject(i)));
                                }
                                newPage.setVisibilityConditions(visibilityConditions);
                            }

                            // look in the JSON for a pageVisibilityRules array is an and or or (default to and)
                            String jsonConditionsType = jsonPage.optString("conditionsType", "and");
                            // set what we got
                            newPage.setConditionsType(jsonConditionsType);

                            // retrieve the html body
                            String htmlBody = jsonPage.optString("htmlBody");
                            // if we got one trim it and retain in page
                            if (htmlBody != null)
                                newPage.setHtmlBody(htmlBody.trim());

                            // look in the JSON for rolehtml
                            JSONArray jsonRolesHtml = jsonPage.optJSONArray("rolesHtml");
                            // if we found some
                            if (jsonRolesHtml != null) {
                                // instantiate the roles html collection
                                ArrayList<Page.RoleHtml> rolesHtml = new ArrayList<Page.RoleHtml>();
                                // loop the entries
                                for (int i = 0; i < jsonRolesHtml.length(); i++) {
                                    // get the entry
                                    JSONObject jsonRoleHtml = jsonRolesHtml.getJSONObject(i);
                                    // retain the html
                                    String html = jsonRoleHtml.optString("html");
                                    // trim it if there is one
                                    if (html != null)
                                        html = html.trim();
                                    // create an array to hold the roles
                                    ArrayList<String> roles = new ArrayList<String>();
                                    // get the roles
                                    JSONArray jsonRoles = jsonRoleHtml.optJSONArray("roles");
                                    // if we got some
                                    if (jsonRoles != null) {
                                        // loop them
                                        for (int j = 0; j < jsonRoles.length(); j++) {
                                            // get the role
                                            String role = jsonRoles.getString(j);
                                            // add it to the roles collections
                                            roles.add(role);
                                        }
                                    }
                                    // create and add a new roleHtml  object
                                    rolesHtml.add(new Page.RoleHtml(roles, html));
                                }
                                // add it to the page
                                newPage.setRolesHtml(rolesHtml);
                            }

                            // fetch a copy of the old page (if there is one)
                            Page oldPage = application.getPages().getPage(getServletContext(), newPage.getId());
                            // if the page's name changed we need to remove it
                            if (oldPage != null) {
                                if (!oldPage.getName().equals(newPage.getName())) {
                                    oldPage.delete(this, rapidRequest, application);
                                }
                            }

                            // save the new page to file
                            newPage.save(this, rapidRequest, application, true);

                            // get any pages collection (we're only sent it if it's been changed)
                            JSONArray jsonPages = jsonPage.optJSONArray("pages");
                            // if we got some
                            if (jsonPages != null) {
                                // make a new map for the page orders
                                Map<String, Integer> pageOrders = new HashMap<String, Integer>();
                                // loop the page orders
                                for (int i = 0; i < jsonPages.length(); i++) {
                                    // add the order to the map
                                    pageOrders.put(jsonPages.getJSONObject(i).getString("id"), i);
                                }
                                // replace the application pageOrders map
                                application.setPageOrders(pageOrders);
                                // save the application and the new orders
                                application.save(this, rapidRequest, true);
                            }
                            boolean jsonPageOrderReset = jsonPage.optBoolean("pageOrderReset");
                            if (jsonPageOrderReset) {
                                // empty the application pageOrders map so everything goes alphabetical
                                application.setPageOrders(null);
                            }

                            // send a positive message
                            output = "{\"message\":\"Saved!\"}";

                            // set the response type to json
                            response.setContentType("application/json");

                        } else if ("testSQL".equals(rapidRequest.getActionName())) {

                            // turn the body bytes into a string
                            String bodyString = new String(bodyBytes, "UTF-8");

                            JSONObject jsonQuery = new JSONObject(bodyString);

                            JSONArray jsonInputs = jsonQuery.optJSONArray("inputs");

                            JSONArray jsonOutputs = jsonQuery.optJSONArray("outputs");

                            Parameters parameters = new Parameters();

                            if (jsonInputs != null) {

                                for (int i = 0; i < jsonInputs.length(); i++)
                                    parameters.addNull();

                            }

                            DatabaseConnection databaseConnection = application.getDatabaseConnections()
                                    .get(jsonQuery.optInt("databaseConnectionIndex", 0));

                            ConnectionAdapter ca = databaseConnection.getConnectionAdapter(getServletContext(),
                                    application);

                            DataFactory df = new DataFactory(ca);

                            int outputs = 0;

                            if (jsonOutputs != null)
                                outputs = jsonOutputs.length();

                            String sql = jsonQuery.getString("SQL");
                            // some jdbc drivers need the line breaks removing before they'll work properly - here's looking at you MS SQL Server!
                            sql = sql.replace("\n", " ");

                            if (outputs == 0) {

                                df.getPreparedStatement(rapidRequest, sql, parameters);

                            } else {

                                ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);

                                ResultSetMetaData rsmd = rs.getMetaData();

                                int cols = rsmd.getColumnCount();

                                if (outputs > cols)
                                    throw new Exception(outputs + " outputs, but only " + cols + " column"
                                            + (cols > 1 ? "s" : "") + " selected");

                                for (int i = 0; i < outputs; i++) {

                                    JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                                    String field = jsonOutput.optString("field", "");

                                    if (!"".equals(field)) {

                                        field = field.toLowerCase();

                                        boolean gotOutput = false;

                                        for (int j = 0; j < cols; j++) {

                                            String sqlField = rsmd.getColumnLabel(j + 1).toLowerCase();

                                            if (field.equals(sqlField)) {
                                                gotOutput = true;
                                                break;
                                            }

                                        }

                                        if (!gotOutput) {
                                            rs.close();
                                            df.close();
                                            throw new Exception("Field \"" + field + "\" from output " + (i + 1)
                                                    + " is not present in selected columns");
                                        }

                                    }

                                }

                                // close the recordset
                                rs.close();
                                // close the data factory
                                df.close();

                            }

                            // send a positive message
                            output = "{\"message\":\"OK\"}";

                            // set the response type to json
                            response.setContentType("application/json");

                        } else if ("uploadImage".equals(rapidRequest.getActionName())
                                || "import".equals(rapidRequest.getActionName())) {

                            // get the content type from the request
                            String contentType = request.getContentType();
                            // get the position of the boundary from the content type
                            int boundaryPosition = contentType.indexOf("boundary=");
                            // derive the start of the meaning data by finding the boundary
                            String boundary = contentType.substring(boundaryPosition + 10);
                            // this is the double line break after which the data occurs
                            byte[] pattern = { 0x0D, 0x0A, 0x0D, 0x0A };
                            // find the position of the double line break
                            int dataPosition = Bytes.findPattern(bodyBytes, pattern);
                            // the body header is everything up to the data
                            String header = new String(bodyBytes, 0, dataPosition, "UTF-8");
                            // find the position of the filename in the data header
                            int filenamePosition = header.indexOf("filename=\"");
                            // extract the file name
                            String filename = header.substring(filenamePosition + 10,
                                    header.indexOf("\"", filenamePosition + 10));
                            // find the position of the file type in the data header
                            int fileTypePosition = header.toLowerCase().indexOf("type:");
                            // extract the file type
                            String fileType = header.substring(fileTypePosition + 6);

                            if ("uploadImage".equals(rapidRequest.getActionName())) {

                                // check the file type
                                if (!fileType.equals("image/jpeg") && !fileType.equals("image/gif")
                                        && !fileType.equals("image/png"))
                                    throw new Exception("Unsupported file type");

                                // get the web folder from the application
                                String path = rapidRequest.getApplication().getWebFolder(getServletContext());
                                // create a file output stream to save the data to
                                FileOutputStream fos = new FileOutputStream(path + "/" + filename);
                                // write the file data to the stream
                                fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length
                                        - dataPosition - pattern.length - boundary.length() - 9);
                                // close the stream
                                fos.close();

                                // log the file creation
                                getLogger().debug("Saved image file " + path + filename);

                                // create the response with the file name and upload type
                                output = "{\"file\":\"" + filename + "\",\"type\":\""
                                        + rapidRequest.getActionName() + "\"}";

                            } else if ("import".equals(rapidRequest.getActionName())) {

                                // check the file type
                                if (!"application/x-zip-compressed".equals(fileType)
                                        && !"application/zip".equals(fileType))
                                    throw new Exception("Unsupported file type");

                                // get the name
                                String appName = request.getParameter("name");

                                // check we were given one
                                if (appName == null)
                                    throw new Exception("Name must be provided");

                                // get the version
                                String appVersion = request.getParameter("version");

                                // check we were given one
                                if (appVersion == null)
                                    throw new Exception("Version must be provided");

                                // make the id from the safe and lower case name
                                String appId = Files.safeName(appName).toLowerCase();

                                // make the version from the safe and lower case name
                                appVersion = Files.safeName(appVersion);

                                // get application destination folder
                                File appFolderDest = new File(
                                        Application.getConfigFolder(getServletContext(), appId, appVersion));
                                // get web contents destination folder
                                File webFolderDest = new File(
                                        Application.getWebFolder(getServletContext(), appId, appVersion));

                                // look for an existing application of this name and version
                                Application existingApplication = getApplications().get(appId, appVersion);
                                // if we have an existing application 
                                if (existingApplication != null) {
                                    // back it up first
                                    existingApplication.backup(this, rapidRequest, false);
                                }

                                // get a file for the temp directory
                                File tempDir = new File(getServletContext().getRealPath("/WEB-INF/temp"));
                                // create it if not there
                                if (!tempDir.exists())
                                    tempDir.mkdir();

                                // the path we're saving to is the temp folder
                                String path = getServletContext()
                                        .getRealPath("/WEB-INF/temp/" + appId + ".zip");
                                // create a file output stream to save the data to
                                FileOutputStream fos = new FileOutputStream(path);
                                // write the file data to the stream
                                fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length
                                        - dataPosition - pattern.length - boundary.length() - 9);
                                // close the stream
                                fos.close();

                                // log the file creation
                                getLogger().debug("Saved import file " + path);

                                // get a file object for the zip file
                                File zipFile = new File(path);
                                // load it into a zip file object
                                ZipFile zip = new ZipFile(zipFile);
                                // unzip the file
                                zip.unZip();
                                // delete the zip file
                                zipFile.delete();

                                // unzip folder (for deletion)
                                File unZipFolder = new File(
                                        getServletContext().getRealPath("/WEB-INF/temp/" + appId));
                                // get application folders
                                File appFolderSource = new File(
                                        getServletContext().getRealPath("/WEB-INF/temp/" + appId + "/WEB-INF"));
                                // get web content folders
                                File webFolderSource = new File(getServletContext()
                                        .getRealPath("/WEB-INF/temp/" + appId + "/WebContent"));

                                // check we have the right source folders
                                if (webFolderSource.exists() && appFolderSource.exists()) {

                                    // get application.xml file
                                    File appFileSource = new File(appFolderSource + "/application.xml");

                                    if (appFileSource.exists()) {

                                        // delete the appFolder if it exists
                                        if (appFolderDest.exists())
                                            Files.deleteRecurring(appFolderDest);
                                        // delete the webFolder if it exists
                                        if (webFolderDest.exists())
                                            Files.deleteRecurring(webFolderDest);

                                        // copy application content
                                        Files.copyFolder(appFolderSource, appFolderDest);

                                        // copy web content
                                        Files.copyFolder(webFolderSource, webFolderDest);

                                        try {

                                            // load the new application (but don't initialise, nor load pages)
                                            Application appNew = Application.load(getServletContext(),
                                                    new File(appFolderDest + "/application.xml"), false);

                                            // update application name
                                            appNew.setName(appName);

                                            // get the old id
                                            String appOldId = appNew.getId();

                                            // make the new id
                                            appId = Files.safeName(appName).toLowerCase();

                                            // update the id
                                            appNew.setId(appId);

                                            // get the old version
                                            String appOldVersion = appNew.getVersion();

                                            // make the new version
                                            appVersion = Files.safeName(appVersion);

                                            // update the version
                                            appNew.setVersion(appVersion);

                                            // update the created date
                                            appNew.setCreatedDate(new Date());

                                            // set the status to In development
                                            appNew.setStatus(Application.STATUS_DEVELOPMENT);

                                            // a map of actions that might be removed from any of the pages
                                            Map<String, Integer> removedActions = new HashMap<String, Integer>();

                                            // look for page files
                                            File pagesFolder = new File(
                                                    appFolderDest.getAbsolutePath() + "/pages");
                                            // if the folder is there
                                            if (pagesFolder.exists()) {

                                                // create a filter for finding .page.xml files
                                                FilenameFilter xmlFilenameFilter = new FilenameFilter() {
                                                    public boolean accept(File dir, String name) {
                                                        return name.toLowerCase().endsWith(".page.xml");
                                                    }
                                                };

                                                // loop the .page.xml files 
                                                for (File pageFile : pagesFolder.listFiles(xmlFilenameFilter)) {

                                                    BufferedReader reader = new BufferedReader(
                                                            new InputStreamReader(new FileInputStream(pageFile),
                                                                    "UTF-8"));
                                                    String line = null;
                                                    StringBuilder stringBuilder = new StringBuilder();

                                                    while ((line = reader.readLine()) != null) {
                                                        stringBuilder.append(line);
                                                        stringBuilder.append("\n");
                                                    }
                                                    reader.close();

                                                    // retrieve the xml into a string
                                                    String fileString = stringBuilder.toString();

                                                    // prepare a new file string which will update into
                                                    String newFileString = null;

                                                    // if the old app did not have a version (for backwards compatibility)
                                                    if (appOldVersion == null) {

                                                        // replace all properties that appear to have a url, and all created links - note the fix for cleaning up the double encoding
                                                        newFileString = fileString
                                                                .replace("applications/" + appOldId + "/",
                                                                        "applications/" + appId + "/"
                                                                                + appVersion + "/")
                                                                .replace("~?a=" + appOldId + "&amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;")
                                                                .replace("~?a=" + appOldId + "&amp;amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;");

                                                    } else {

                                                        // replace all properties that appear to have a url, and all created links - note the fix for double encoding 
                                                        newFileString = fileString
                                                                .replace(
                                                                        "applications/" + appOldId + "/"
                                                                                + appOldVersion + "/",
                                                                        "applications/" + appId + "/"
                                                                                + appVersion + "/")
                                                                .replace(
                                                                        "~?a=" + appOldId + "&amp;v="
                                                                                + appOldVersion + "&amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;")
                                                                .replace(
                                                                        "~?a=" + appOldId + "&amp;amp;v="
                                                                                + appOldVersion + "&amp;amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;");
                                                    }

                                                    // now open the string into a document
                                                    Document pageDocument = XML.openDocument(newFileString);
                                                    // get an xpath factory
                                                    XPathFactory xPathfactory = XPathFactory.newInstance();
                                                    XPath xpath = xPathfactory.newXPath();
                                                    // an expression for any attributes with a local name of "type"
                                                    XPathExpression expr = xpath
                                                            .compile("//@*[local-name()='type']");
                                                    // get them
                                                    NodeList nl = (NodeList) expr.evaluate(pageDocument,
                                                            XPathConstants.NODESET);
                                                    // get out system actions
                                                    JSONArray jsonActions = getJsonActions();
                                                    // if we found any elements with a type attribute and we have system actions
                                                    if (nl.getLength() > 0 && jsonActions.length() > 0) {
                                                        // a list of action types
                                                        List<String> types = new ArrayList<String>();
                                                        // loop the json actions
                                                        for (int i = 0; i < jsonActions.length(); i++)
                                                            types.add(jsonActions.getJSONObject(i)
                                                                    .optString("type").toLowerCase());
                                                        // loop the action attributes we found
                                                        for (int i = 0; i < nl.getLength(); i++) {
                                                            // get this attribute
                                                            Attr a = (Attr) nl.item(i);
                                                            // get the value of the type 
                                                            String type = a.getTextContent().toLowerCase();
                                                            // get the element the attribute is in
                                                            Node n = a.getOwnerElement();
                                                            // if we don't know about this action type
                                                            if (!types.contains(type)) {
                                                                // get the parent node
                                                                Node p = n.getParentNode();
                                                                // remove this node
                                                                p.removeChild(n);
                                                                // if we have removed this type already
                                                                if (removedActions.containsKey(type)) {
                                                                    // increment the entry for this type
                                                                    removedActions.put(type,
                                                                            removedActions.get(type) + 1);
                                                                } else {
                                                                    // add an entry for this type
                                                                    removedActions.put(type, 1);
                                                                }
                                                            } // got type check                                                                                                                                             
                                                        } // attribute loop

                                                    } // attribute and system action check

                                                    // use the transformer to write to disk
                                                    TransformerFactory transformerFactory = TransformerFactory
                                                            .newInstance();
                                                    Transformer transformer = transformerFactory
                                                            .newTransformer();
                                                    DOMSource source = new DOMSource(pageDocument);
                                                    StreamResult result = new StreamResult(pageFile);
                                                    transformer.transform(source, result);

                                                } // page xml file loop

                                            } // pages folder check

                                            // now initialise with the new id but don't make the resource files (this reloads the pages and sets up the security adapter)
                                            appNew.initialise(getServletContext(), false);

                                            // get the security for this application
                                            SecurityAdapter security = appNew.getSecurityAdapter();

                                            // if we have one
                                            if (security != null) {

                                                // assume we don't have the user
                                                boolean gotUser = false;
                                                // get the current users record from the adapter
                                                User user = security.getUser(rapidRequest);
                                                // check the current user is present in the app's security adapter
                                                if (user != null) {
                                                    // now check the current user password is correct too
                                                    if (security.checkUserPassword(rapidRequest, userName,
                                                            rapidRequest.getUserPassword())) {
                                                        // we have the right user with the right password
                                                        gotUser = true;
                                                    } else {
                                                        // remove this user as the password does not match
                                                        security.deleteUser(rapidRequest);
                                                    }
                                                }

                                                // if we don't have the user
                                                if (!gotUser) {
                                                    // get the current user from the Rapid application
                                                    User rapidUser = rapidSecurity.getUser(rapidRequest);
                                                    // create a new user based on the Rapid user
                                                    user = new User(userName, rapidUser.getDescription(),
                                                            rapidUser.getPassword());
                                                    // add the new user 
                                                    security.addUser(rapidRequest, user);
                                                }

                                                // add Admin and Design roles for the new user if required
                                                if (!security.checkUserRole(rapidRequest,
                                                        com.rapid.server.Rapid.ADMIN_ROLE))
                                                    security.addUserRole(rapidRequest,
                                                            com.rapid.server.Rapid.ADMIN_ROLE);

                                                if (!security.checkUserRole(rapidRequest,
                                                        com.rapid.server.Rapid.DESIGN_ROLE))
                                                    security.addUserRole(rapidRequest,
                                                            com.rapid.server.Rapid.DESIGN_ROLE);
                                            }

                                            // if any items were removed
                                            if (removedActions.keySet().size() > 0) {
                                                // a description of what was removed
                                                String removed = "";
                                                // loop the entries
                                                for (String type : removedActions.keySet()) {
                                                    int count = removedActions.get(type);
                                                    removed += "removed " + count + " " + type + " action"
                                                            + (count == 1 ? "" : "s") + " on import\n";
                                                }
                                                // get the current description
                                                String description = appNew.getDescription();
                                                // if null set to empty string
                                                if (description == null)
                                                    description = "";
                                                // add a line break if need be
                                                if (description.length() > 0)
                                                    description += "\n";
                                                // add the removed
                                                description += removed;
                                                // set it back
                                                appNew.setDescription(description);
                                            }

                                            // reload the pages (actually clears down the pages collection and reloads the headers)
                                            appNew.getPages().loadpages(getServletContext());

                                            // save application (this will also initialise and rebuild the resources)
                                            appNew.save(this, rapidRequest, false);

                                            // add application to the collection
                                            getApplications().put(appNew);

                                            // delete unzip folder
                                            Files.deleteRecurring(unZipFolder);

                                            // send a positive message
                                            output = "{\"id\":\"" + appNew.getId() + "\",\"version\":\""
                                                    + appNew.getVersion() + "\"}";

                                        } catch (Exception ex) {

                                            // delete the appFolder if it exists
                                            if (appFolderDest.exists())
                                                Files.deleteRecurring(appFolderDest);
                                            // if the parent is empty delete it too
                                            if (appFolderDest.getParentFile().list().length <= 1)
                                                Files.deleteRecurring(appFolderDest.getParentFile());

                                            // delete the webFolder if it exists
                                            if (webFolderDest.exists())
                                                Files.deleteRecurring(webFolderDest);
                                            // if the parent is empty delete it too
                                            if (webFolderDest.getParentFile().list().length <= 1)
                                                Files.deleteRecurring(webFolderDest.getParentFile());

                                            // rethrow exception
                                            throw ex;

                                        }

                                    } else {

                                        // delete unzip folder
                                        Files.deleteRecurring(unZipFolder);

                                        // throw excpetion
                                        throw new Exception("Must be a valid Rapid " + Rapid.VERSION + " file");

                                    }

                                } else {

                                    // delete unzip folder
                                    Files.deleteRecurring(unZipFolder);

                                    // throw excpetion
                                    throw new Exception("Must be a valid Rapid file");

                                }

                            }

                        }

                        getLogger().debug("Designer POST response : " + output);

                        PrintWriter out = response.getWriter();
                        out.print(output);
                        out.close();

                    } // got an application

                } // got rapid design role

            } // got rapid security

        } // got rapid application

    } catch (Exception ex) {

        getLogger().error("Designer POST error : ", ex);

        sendException(rapidRequest, response, ex);

    }

}

From source file:com.espertech.esper.event.xml.SchemaXMLPropertyParser.java

/**
 * Return the xPath corresponding to the given property.
 * The propertyName String may be simple, nested, indexed or mapped.
 *
 * @param propertyName is the event property name
 * @param namespace is the default namespace
 * @param schemaModel is the schema model
 * @param xPathFactory is the xpath factory instance to use
 * @param rootElementName is the name of the root element
 * @param eventAdapterService for type lookup and creation
 * @param xmlEventType the resolving type
 * @param isAllowFragment whether fragmenting is allowed
 * @param defaultNamespace default namespace
 * @return xpath expression/*from   w w w.  j  a v a2 s.com*/
 * @throws EPException is there are XPath errors
 */
public static EventPropertyGetter getXPathResolution(String propertyName, XPathFactory xPathFactory,
        String rootElementName, String namespace, SchemaModel schemaModel,
        EventAdapterService eventAdapterService, BaseXMLEventType xmlEventType, boolean isAllowFragment,
        String defaultNamespace) throws EPException {
    if (log.isDebugEnabled()) {
        log.debug("Determining XPath expression for property '" + propertyName + "'");
    }

    XPathNamespaceContext ctx = new XPathNamespaceContext();
    List<String> namespaces = schemaModel.getNamespaces();

    String defaultNamespacePrefix = null;
    for (int i = 0; i < namespaces.size(); i++) {
        String prefix = "n" + i;
        ctx.addPrefix(prefix, namespaces.get(i));
        if ((defaultNamespace != null) && (defaultNamespace.equals(namespaces.get(i)))) {
            defaultNamespacePrefix = prefix;
        }
    }

    Tree ast = PropertyParser.parse(propertyName);
    Property property = PropertyParser.parse(propertyName, false);
    boolean isDynamic = property.isDynamic();

    SchemaElementComplex rootComplexElement = SchemaUtil.findRootElement(schemaModel, namespace,
            rootElementName);
    String prefix = ctx.getPrefix(rootComplexElement.getNamespace());
    if (prefix == null) {
        prefix = "";
    } else {
        prefix += ':';
    }

    StringBuilder xPathBuf = new StringBuilder();
    xPathBuf.append('/');
    xPathBuf.append(prefix);
    if (rootElementName.startsWith("//")) {
        xPathBuf.append(rootElementName.substring(2));
    } else {
        xPathBuf.append(rootElementName);
    }

    SchemaElementComplex parentComplexElement = rootComplexElement;
    Pair<String, QName> pair = null;

    if (ast.getChildCount() == 1) {
        pair = makeProperty(rootComplexElement, ast.getChild(0), ctx, true, isDynamic, defaultNamespacePrefix);
        if (pair == null) {
            throw new PropertyAccessException("Failed to locate property '" + propertyName + "' in schema");
        }
        xPathBuf.append(pair.getFirst());
    } else {
        for (int i = 0; i < ast.getChildCount(); i++) {
            boolean isLast = (i == ast.getChildCount() - 1);
            Tree child = ast.getChild(i);
            pair = makeProperty(parentComplexElement, child, ctx, isLast, isDynamic, defaultNamespacePrefix);
            if (pair == null) {
                throw new PropertyAccessException("Failed to locate property '" + propertyName
                        + "' nested property part '" + child.toString() + "' in schema");
            }

            String text = child.getChild(0).getText();
            SchemaItem obj = SchemaUtil.findPropertyMapping(parentComplexElement, text);
            if (obj instanceof SchemaElementComplex) {
                parentComplexElement = (SchemaElementComplex) obj;
            }
            xPathBuf.append(pair.getFirst());
        }
    }

    String xPath = xPathBuf.toString();
    if ((ExecutionPathDebugLog.isDebugEnabled) && (log.isDebugEnabled())) {
        log.debug(".parse XPath for property '" + propertyName + "' is expression=" + xPath);
    }

    // Compile assembled XPath expression
    XPath path = xPathFactory.newXPath();
    path.setNamespaceContext(ctx);

    if (log.isDebugEnabled()) {
        log.debug("Compiling XPath expression '" + xPath + "' for property '" + propertyName
                + "' using namespace context :" + ctx);
    }

    XPathExpression expr;
    try {
        expr = path.compile(xPath);
    } catch (XPathExpressionException e) {
        String detail = "Error constructing XPath expression from property expression '" + propertyName
                + "' expression '" + xPath + "'";
        if (e.getMessage() != null) {
            throw new EPException(detail + " :" + e.getMessage(), e);
        }
        throw new EPException(detail, e);
    }

    // get type
    SchemaItem item = property.getPropertyTypeSchema(rootComplexElement, eventAdapterService);
    if ((item == null) && (!isDynamic)) {
        return null;
    }

    Class resultType;
    if (!isDynamic) {
        resultType = SchemaUtil.toReturnType(item);
    } else {
        resultType = Node.class;
    }

    FragmentFactory fragmentFactory = null;
    if (isAllowFragment) {
        fragmentFactory = new FragmentFactoryDOMGetter(eventAdapterService, xmlEventType, propertyName);
    }
    return new XPathPropertyGetter(propertyName, xPath, expr, pair.getSecond(), resultType, fragmentFactory);
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

private void createBooking(String rq, Reservation reservation, long timestamp, Map<String, String> result)
        throws Throwable {
    String rs = getConnection(rq);
    LOG.debug("\nBookResponse rs: \n" + rs + "\n");
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    InputSource inputSource = new InputSource(new StringReader(rs.toString()));
    String bookID = (String) xpath.evaluate("//BookID", inputSource, XPathConstants.STRING);
    if (bookID.isEmpty()) {
        throw new ServiceException(Error.reservation_api, reservation.getId());
    } else {/*from w w w .ja  v  a2s  .  c o  m*/
        reservation.setAltid(bookID);
        reservation.setAltpartyid(getAltpartyid());
        reservation.setMessage(reservation.getMessage());
        reservation.setVersion(new Date(timestamp));
        reservation.setState(Reservation.State.Confirmed.name());
        result.put(GatewayHandler.STATE, GatewayHandler.ACCEPTED);
    }
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

/**
 * Returns if the property is available for the reservation.
 * /*from ww w .j  av  a 2  s .c o m*/
 * @param sqlSession the current SQL session.
 * @param reservation the reservation for collisions
 * @return list of collisions
 */
@Override
public boolean isAvailable(SqlSession sqlSession, Reservation reservation) {
    StringBuilder sb = new StringBuilder();
    Date now = new Date();
    long time = now.getTime();
    String SenderSessionID = time + "bookingnetS";
    String ReceiverSessionID = time + "bookingnetR";
    String rq;
    String rs = null;
    boolean available = false;
    if (reservation.notActive()) {
        throw new ServiceException(Error.reservation_state,
                reservation.getId() + " state " + reservation.getState());
    }

    Product product = sqlSession.getMapper(ProductMapper.class).read(reservation.getProductid());
    if (product == null) {
        throw new ServiceException(Error.product_id, reservation.getProductid());
    }
    if (reservation.noAgentid()) {
        throw new ServiceException(Error.reservation_agentid);
    }
    Party agent = sqlSession.getMapper(PartyMapper.class).read(reservation.getAgentid());
    if (agent == null) {
        throw new ServiceException(Error.party_id, reservation.getAgentid());
    }
    if (reservation.noCustomerid()) {
        reservation.setCustomerid(Party.NO_ACTOR);
    }
    Party customer = sqlSession.getMapper(PartyMapper.class).read(reservation.getCustomerid());
    if (customer == null) {
        throw new ServiceException(Error.reservation_customerid, reservation.getCustomerid());
    }

    try {
        sb.append("<?xml version='1.0' ?>");
        sb.append("<TravelMessage VersionID='1.8N'>");
        sb.append(" <Control Language='NL' Test='nee'>");
        sb.append("    <SenderSessionID>" + SenderSessionID + "</SenderSessionID>");
        sb.append("    <ReceiverSessionID>" + ReceiverSessionID + "</ReceiverSessionID>");
        sb.append("    <Date>" + DF.format(new Date()) + "</Date>");
        sb.append("    <Time Reliability='zeker'>" + TF.format(new Date()) + "</Time>");
        sb.append("   <MessageSequence>1</MessageSequence>");
        sb.append("   <SenderID>" + SENDERID + "</SenderID>");
        sb.append("  <ReceiverID>NPS001</ReceiverID>");
        sb.append("   <RequestID>AvailabilitybookingnetRequest</RequestID>");
        sb.append("   <ResponseID>AvailabilitybookingnetResponse</ResponseID>");
        sb.append(" </Control>");
        sb.append("  <TRequest>");
        sb.append("    <AvailabilitybookingnetRequest>");
        sb.append("      <PackageDetails WaitListCheck='ja'>");
        sb.append("          <AccommodationID>" + "A" + product.getAltid() + "</AccommodationID>");
        sb.append("          <ArrivalDate>" + DF.format(reservation.getFromdate()) + "</ArrivalDate>");
        sb.append("        <Duration DurationType='dagen'>" + reservation.getDuration(Time.DAY).intValue()
                + "</Duration>");
        sb.append("     </PackageDetails>");
        sb.append("   </AvailabilitybookingnetRequest>");
        sb.append("  </TRequest>");
        sb.append("</TravelMessage>");

        rq = sb.toString();
        LOG.debug("isAvailable rq: \n" + rq + "\n");

        rs = getConnection(rq);
        LOG.debug("isAvailable rs: \n" + rs + "\n");

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        InputSource inputSource = new InputSource(new StringReader(rs.toString()));
        Double bookID = (Double) xpath.evaluate("//PackageID", inputSource, XPathConstants.NUMBER);
        available = !bookID.isNaN();
    } catch (Throwable e) {
        LOG.error(e.getMessage());
    }
    return available;
}

From source file:com.amalto.core.save.DocumentSaveTest.java

@Override
public void setUp() throws Exception {
    LOG.info("Setting up MDM server environment...");
    ServerContext.INSTANCE.get(new MockServerLifecycle());
    MDMConfiguration.getConfiguration().setProperty("xmlserver.class",
            "com.amalto.core.storage.DispatchWrapper");
    SaverSession.setDefaultCommitter(new MockCommitter());
    LOG.info("MDM server environment set.");
    XPathFactory xPathFactory = XPathFactory.newInstance();
    xPath = xPathFactory.newXPath();
    xPath.setNamespaceContext(new TestNamespaceContext());
}

From source file:nl.b3p.ogc.utils.OGCResponse.java

protected NodeList getNodeListFromXPath(Node currentNode, String xPathFrag) throws Exception {
    if (xPathFrag == null || xPathFrag.length() == 0) {
        return null;
    }/*from  w  ww  . j  a  v  a  2s. co m*/
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(getNamespaceContext());

    XPathExpression expr = xpath.compile(xPathFrag);
    Object result = expr.evaluate(currentNode, XPathConstants.NODESET);
    return (NodeList) result;
}

From source file:nl.b3p.viewer.admin.stripes.ServiceUsageMatrixActionBean.java

public static XSSFWorkbook createWorkBook(String theXml) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, XPathFactoryConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(theXml)));

    XSSFWorkbook workbook = new XSSFWorkbook();
    String tempProperty = null;/*from  ww w.  j a  va2 s  . c  o m*/
    try {
        Element root = doc.getDocumentElement();
        /* JSTL XML is setting the system property to use the jstl xpath facotry.
         * Remove the setting temporary:
         * see: https://java.net/jira/browse/JSTL-1
         */
        tempProperty = System
                .getProperty(XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI);
        if (tempProperty != null) {
            System.clearProperty(
                    XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI);
        }

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        XPathExpression exprFeatureSource = xpath.compile("//featureSource");
        XPathExpression exprFeatureType = xpath.compile("featureType");
        XPathExpression exprApplication = xpath.compile("applications/application");
        XPathExpression exprLayer = xpath.compile("layers/layer");
        XPathExpression exprAppLayer = xpath.compile("applayers/applayer");
        XPathExpression exprId = xpath.compile("id/text()");
        XPathExpression exprAlias = xpath.compile("alias/text()");
        XPathExpression exprName = xpath.compile("name/text()");
        XPathExpression exprVersion = xpath.compile("version/text()");
        XPathExpression exprProtocol = xpath.compile("protocol/text()");
        XPathExpression exprUrl = xpath.compile("url/text()");

        XSSFSheet sheet = workbook.createSheet("Sheet 1");
        int rowNum = 0;

        Row head = sheet.createRow(rowNum++);
        String[] headValues = { "Bron", "Featuretype", "Applicatie", "Layernaam van service",
                "Application layer (kaart)" };
        for (int c = 0; c < headValues.length; c++) {
            Cell cell = head.createCell(c);
            cell.setCellValue(headValues[c]);
        }
        List<String> columns = new ArrayList<String>();
        for (int i = 0; i < headValues.length; i++) {
            columns.add("");
        }
        NodeList featureSources = (NodeList) exprFeatureSource.evaluate(root, XPathConstants.NODESET);

        for (int fs = 0; fs < featureSources.getLength(); fs++) {
            Node featureSource = featureSources.item(fs);

            String fsString = (String) exprName.evaluate(featureSource, XPathConstants.STRING);
            fsString += " (" + (String) exprProtocol.evaluate(featureSource, XPathConstants.STRING);
            fsString += ":: " + (String) exprUrl.evaluate(featureSource, XPathConstants.STRING);
            fsString += " id: " + (String) exprId.evaluate(featureSource, XPathConstants.STRING);
            fsString += ")";
            columns.set(0, fsString);
            NodeList featureTypes = (NodeList) exprFeatureType.evaluate(featureSource, XPathConstants.NODESET);
            for (int ft = 0; ft < featureTypes.getLength(); ft++) {
                Node featureType = featureTypes.item(ft);
                //String ftId = (String) exprId.evaluate(featureType,XPathConstants.STRING);
                String ftName = (String) exprName.evaluate(featureType, XPathConstants.STRING);
                //String ftString = ""+ftName;
                columns.set(1, ftName);
                NodeList applications = (NodeList) exprApplication.evaluate(featureType,
                        XPathConstants.NODESET);
                for (int app = 0; app < applications.getLength(); app++) {
                    Node application = applications.item(app);
                    String appVersion = (String) exprVersion.evaluate(application, XPathConstants.STRING);

                    String appString = (String) exprName.evaluate(application, XPathConstants.STRING);
                    if (appVersion != null) {
                        appString += ", version: " + appVersion;
                    }
                    appString += " (" + (String) exprId.evaluate(application, XPathConstants.STRING) + ")";
                    columns.set(2, appString);
                    NodeList layers = (NodeList) exprLayer.evaluate(application, XPathConstants.NODESET);
                    for (int lay = 0; lay < layers.getLength(); lay++) {
                        Node layer = layers.item(lay);
                        String layerString = "";
                        layerString += (String) exprName.evaluate(layer, XPathConstants.STRING);
                        columns.set(3, layerString);
                        NodeList appLayers = (NodeList) exprAppLayer.evaluate(layer, XPathConstants.NODESET);
                        for (int al = 0; al < appLayers.getLength(); al++) {
                            Node appLayer = appLayers.item(al);
                            String alString = (String) exprAlias.evaluate(appLayer, XPathConstants.STRING);
                            alString += " (" + (String) exprId.evaluate(appLayer, XPathConstants.STRING) + ")";
                            columns.set(4, alString);
                            Row row = sheet.createRow(rowNum++);
                            for (int c = 0; c < columns.size(); c++) {
                                Cell cell = row.createCell(c);
                                cell.setCellValue(columns.get(c));
                            }
                        }
                    }
                }
            }
        }
    } finally {
        if (tempProperty != null) {
            System.setProperty(XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI,
                    tempProperty);
        }
    }
    return workbook;
}

From source file:nz.govt.natlib.adapter.arc.ArcAdapter.java

private ArcMetadata parseArcMetadataRecord(ArcVersionBlock arcMetadataRecord) {
    if (arcMetadataRecord == null)
        return null;
    ArcMetadata metadata = new ArcMetadata();
    ByteArrayOutputStream bos = null;
    try {//from w  w  w .  j av  a 2s.  c  om
        Document doc = createXmlDocumentFrom(arcMetadataRecord.getPayloadContent());
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xpath = xPathFactory.newXPath();
        xpath.setNamespaceContext(new ArcMetadataNamespaceContext());
        metadata.software = (String) xpath.evaluate("//arc:arcmetadata/arc:software", doc,
                XPathConstants.STRING);
        metadata.hostname = (String) xpath.evaluate("//arc:arcmetadata/arc:hostname", doc,
                XPathConstants.STRING);
        metadata.ip = (String) xpath.evaluate("//arc:arcmetadata/arc:ip", doc, XPathConstants.STRING);
        metadata.operator = (String) xpath.evaluate("//arc:arcmetadata/arc:operator", doc,
                XPathConstants.STRING);
        metadata.createdDate = (String) xpath.evaluate("//arc:arcmetadata/dc:date", doc, XPathConstants.STRING);
        metadata.robotPolicy = (String) xpath.evaluate("//arc:arcmetadata/arc:robots", doc,
                XPathConstants.STRING);
        metadata.arcFormat = (String) xpath.evaluate("//arc:arcmetadata/dc:format", doc, XPathConstants.STRING);
        metadata.conformsTo = (String) xpath.evaluate("//arc:arcmetadata/dcterms:conformsTo", doc,
                XPathConstants.STRING);
        return metadata;
    } catch (Exception e) {
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}