Example usage for javax.xml.xpath XPath evaluate

List of usage examples for javax.xml.xpath XPath evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPath evaluate.

Prototype

public Object evaluate(String expression, InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate an XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Import flat storages to the hierarchical storage
 *
 * @param con an open and valid connection to store imported data
 * @param zip zip file containing the data
 * @throws Exception on errors//  w  ww  . ja va 2s  .  co m
 */
protected void importFlatStoragesHierarchical(Connection con, ZipFile zip) throws Exception {
    //mapping: storage->level->columnname->assignment id
    final Map<String, Map<Integer, Map<String, Long>>> flatAssignmentMapping = new HashMap<String, Map<Integer, Map<String, Long>>>(
            5);
    //mapping: assignment id->position index
    final Map<Long, Integer> assignmentPositions = new HashMap<Long, Integer>(100);
    //mapping: flatstorage->column sizes [string,bigint,double,select,text]
    final Map<String, Integer[]> flatstoragesColumns = new HashMap<String, Integer[]>(5);
    ZipEntry zeMeta = getZipEntry(zip, FILE_FLATSTORAGE_META);
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(zip.getInputStream(zeMeta));
    XPath xPath = XPathFactory.newInstance().newXPath();

    //calculate column sizes
    NodeList nodes = (NodeList) xPath.evaluate("/flatstorageMeta/storageMeta", document,
            XPathConstants.NODESET);
    Node currNode;
    for (int i = 0; i < nodes.getLength(); i++) {
        currNode = nodes.item(i);
        int cbigInt = Integer.parseInt(currNode.getAttributes().getNamedItem("bigInt").getNodeValue());
        int cdouble = Integer.parseInt(currNode.getAttributes().getNamedItem("double").getNodeValue());
        int cselect = Integer.parseInt(currNode.getAttributes().getNamedItem("select").getNodeValue());
        int cstring = Integer.parseInt(currNode.getAttributes().getNamedItem("string").getNodeValue());
        int ctext = Integer.parseInt(currNode.getAttributes().getNamedItem("text").getNodeValue());
        String tableName = null;
        if (currNode.hasChildNodes()) {
            for (int j = 0; j < currNode.getChildNodes().getLength(); j++)
                if (currNode.getChildNodes().item(j).getNodeName().equals("name")) {
                    tableName = currNode.getChildNodes().item(j).getTextContent();
                }
        }
        if (tableName != null) {
            flatstoragesColumns.put(tableName, new Integer[] { cstring, cbigInt, cdouble, cselect, ctext });
        }
    }

    //parse mappings
    nodes = (NodeList) xPath.evaluate("/flatstorageMeta/mapping", document, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        currNode = nodes.item(i);
        long assignment = Long.valueOf(currNode.getAttributes().getNamedItem("assid").getNodeValue());
        int level = Integer.valueOf(currNode.getAttributes().getNamedItem("lvl").getNodeValue());
        String storage = null;
        String columnname = null;
        final NodeList childNodes = currNode.getChildNodes();
        for (int c = 0; c < childNodes.getLength(); c++) {
            Node child = childNodes.item(c);
            if ("tblname".equals(child.getNodeName()))
                storage = child.getTextContent();
            else if ("colname".equals(child.getNodeName()))
                columnname = child.getTextContent();
        }
        if (storage == null || columnname == null)
            throw new Exception("Invalid flatstorage export: could not read storage or column name!");
        if (!flatAssignmentMapping.containsKey(storage))
            flatAssignmentMapping.put(storage, new HashMap<Integer, Map<String, Long>>(20));
        Map<Integer, Map<String, Long>> levelMap = flatAssignmentMapping.get(storage);
        if (!levelMap.containsKey(level))
            levelMap.put(level, new HashMap<String, Long>(30));
        Map<String, Long> columnMap = levelMap.get(level);
        if (!columnMap.containsKey(columnname))
            columnMap.put(columnname, assignment);
        //calculate position
        assignmentPositions.put(assignment,
                getAssignmentPosition(flatstoragesColumns.get(storage), columnname));
    }
    if (flatAssignmentMapping.size() == 0) {
        LOG.warn("No flatstorage assignments found to process!");
        return;
    }
    ZipEntry zeData = getZipEntry(zip, FILE_DATA_FLAT);

    final String xpathStorage = "flatstorages/storage";
    final String xpathData = "flatstorages/storage/data";

    final PreparedStatement psGetAssInfo = con.prepareStatement(
            "SELECT DISTINCT a.APROPERTY,a.XALIAS,p.DATATYPE FROM " + DatabaseConst.TBL_STRUCT_ASSIGNMENTS
                    + " a, " + DatabaseConst.TBL_STRUCT_PROPERTIES + " p WHERE a.ID=? AND p.ID=a.APROPERTY");
    final Map<Long, Object[]> assignmentPropAlias = new HashMap<Long, Object[]>(assignmentPositions.size());
    final String insert1 = "INSERT INTO " + DatabaseConst.TBL_CONTENT_DATA +
    //1  2   3   4    5     6      =1     =1    =1     =1          7         8          9
            "(ID,VER,POS,LANG,TPROP,ASSIGN,XDEPTH,XMULT,XINDEX,PARENTXMULT,ISMAX_VER,ISLIVE_VER,ISMLDEF,";
    final String insert2 = "(?,?,?,?,1,?,?,1,1,1,?,?,?,";
    final PreparedStatement psString = con
            .prepareStatement(insert1 + "FTEXT1024,UFTEXT1024,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)");
    final PreparedStatement psText = con
            .prepareStatement(insert1 + "FCLOB,UFCLOB,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)");
    final PreparedStatement psDouble = con
            .prepareStatement(insert1 + "FDOUBLE,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psNumber = con
            .prepareStatement(insert1 + "FINT,FSELECT,FBIGINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psLargeNumber = con
            .prepareStatement(insert1 + "FBIGINT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psFloat = con
            .prepareStatement(insert1 + "FFLOAT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psBoolean = con
            .prepareStatement(insert1 + "FBOOL,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psReference = con
            .prepareStatement(insert1 + "FREF,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psSelectOne = con
            .prepareStatement(insert1 + "FSELECT,FINT)VALUES" + insert2 + "?,?)");
    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final DefaultHandler handler = new DefaultHandler() {
            private String currentElement = null;
            private String currentStorage = null;
            private Map<String, String> data = new HashMap<String, String>(10);
            private StringBuilder sbData = new StringBuilder(10000);
            boolean inTag = false;
            boolean inElement = false;
            List<String> path = new ArrayList<String>(10);
            StringBuilder currPath = new StringBuilder(100);
            int insertCount = 0;

            /**
             * {@inheritDoc}
             */
            @Override
            public void startDocument() throws SAXException {
                inTag = false;
                inElement = false;
                path.clear();
                currPath.setLength(0);
                sbData.setLength(0);
                data.clear();
                currentElement = null;
                currentStorage = null;
                insertCount = 0;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endDocument() throws SAXException {
                LOG.info("Imported [" + insertCount + "] flatstorage entries into the hierarchical storage");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                pushPath(qName, attributes);
                if (currPath.toString().equals(xpathData)) {
                    inTag = true;
                    data.clear();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        String name = attributes.getLocalName(i);
                        if (StringUtils.isEmpty(name))
                            name = attributes.getQName(i);
                        data.put(name, attributes.getValue(i));
                    }
                } else if (currPath.toString().equals(xpathStorage)) {
                    currentStorage = attributes.getValue("name");
                    LOG.info("Processing storage: " + currentStorage);
                } else {
                    currentElement = qName;
                }
                inElement = true;
                sbData.setLength(0);
            }

            /**
             * Push a path element from the stack
             *
             * @param qName element name to push
             * @param att attributes
             */
            @SuppressWarnings({ "UnusedDeclaration" })
            private void pushPath(String qName, Attributes att) {
                path.add(qName);
                buildPath();
            }

            /**
             * Pop the top path element from the stack
             */
            private void popPath() {
                path.remove(path.size() - 1);
                buildPath();
            }

            /**
             * Rebuild the current path
             */
            private synchronized void buildPath() {
                currPath.setLength(0);
                for (String s : path)
                    currPath.append(s).append('/');
                if (currPath.length() > 1)
                    currPath.delete(currPath.length() - 1, currPath.length());
                //                    System.out.println("currPath: " + currPath);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (currPath.toString().equals(xpathData)) {
                    //                        LOG.info("Insert [" + xpathData + "]: [" + data + "]");
                    inTag = false;
                    processData();
                    /*try {
                    if (insertMode) {
                        if (executeInsertPhase) {
                            processColumnSet(insertColumns, psInsert);
                            counter += psInsert.executeUpdate();
                        }
                    } else {
                        if (executeUpdatePhase) {
                            if (processColumnSet(updateSetColumns, psUpdate)) {
                                processColumnSet(updateClauseColumns, psUpdate);
                                counter += psUpdate.executeUpdate();
                            }
                        }
                    }
                    } catch (SQLException e) {
                    throw new SAXException(e);
                    } catch (ParseException e) {
                    throw new SAXException(e);
                    }*/
                } else {
                    if (inTag) {
                        data.put(currentElement, sbData.toString());
                    }
                    currentElement = null;
                }
                popPath();
                inElement = false;
                sbData.setLength(0);
            }

            void processData() {
                //                    System.out.println("processing " + currentStorage + " -> " + data);
                final String[] cols = { "string", "bigint", "double", "select", "text" };
                for (String column : data.keySet()) {
                    if (column.endsWith("_mld"))
                        continue;
                    for (String check : cols) {
                        if (column.startsWith(check)) {
                            if ("select".equals(check) && "0".equals(data.get(column)))
                                continue; //dont insert 0-referencing selects
                            try {
                                insertData(column);
                            } catch (SQLException e) {
                                //noinspection ThrowableInstanceNeverThrown
                                throw new FxDbException(e, "ex.db.sqlError", e.getMessage())
                                        .asRuntimeException();
                            }
                        }
                    }
                }
            }

            private void insertData(String column) throws SQLException {
                final int level = Integer.parseInt(data.get("lvl"));
                long assignment = flatAssignmentMapping.get(currentStorage).get(level)
                        .get(column.toUpperCase());
                int pos = FxArrayUtils.getIntElementAt(data.get("positions"), ',',
                        assignmentPositions.get(assignment));
                String _valueData = data.get("valuedata");
                Integer valueData = _valueData == null ? null
                        : FxArrayUtils.getHexIntElementAt(data.get("valuedata"), ',',
                                assignmentPositions.get(assignment));
                Object[] propXP = getPropertyXPathDataType(assignment);
                long prop = (Long) propXP[0];
                String xpath = (String) propXP[1];
                FxDataType dataType;
                try {
                    dataType = FxDataType.getById((Long) propXP[2]);
                } catch (FxNotFoundException e) {
                    throw e.asRuntimeException();
                }
                long id = Long.parseLong(data.get("id"));
                int ver = Integer.parseInt(data.get("ver"));
                long lang = Integer.parseInt(data.get("lang"));
                boolean isMaxVer = "1".equals(data.get("ismax_ver"));
                boolean isLiveVer = "1".equals(data.get("islive_ver"));
                boolean mlDef = "1".equals(data.get(column + "_mld"));
                PreparedStatement ps;
                int vdPos;
                switch (dataType) {
                case String1024:
                    ps = psString;
                    ps.setString(10, data.get(column));
                    ps.setString(11, data.get(column).toUpperCase());
                    vdPos = 12;
                    break;
                case Text:
                case HTML:
                    ps = psText;
                    ps.setString(10, data.get(column));
                    ps.setString(11, data.get(column).toUpperCase());
                    vdPos = 12;
                    break;
                case Number:
                    ps = psNumber;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case LargeNumber:
                    ps = psLargeNumber;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Reference:
                    ps = psReference;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Float:
                    ps = psFloat;
                    ps.setFloat(10, Float.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Double:
                    ps = psDouble;
                    ps.setDouble(10, Double.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Boolean:
                    ps = psBoolean;
                    ps.setBoolean(10, "1".equals(data.get(column)));
                    vdPos = 11;
                    break;
                case SelectOne:
                    ps = psSelectOne;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                default:
                    //noinspection ThrowableInstanceNeverThrown
                    throw new FxInvalidParameterException("assignment",
                            "ex.structure.flatstorage.datatype.unsupported", dataType.name())
                                    .asRuntimeException();
                }
                ps.setLong(1, id);
                ps.setInt(2, ver);
                ps.setInt(3, pos);
                ps.setLong(4, lang);
                ps.setLong(5, prop);
                ps.setLong(6, assignment);
                ps.setBoolean(7, isMaxVer);
                ps.setBoolean(8, isLiveVer);
                ps.setBoolean(9, mlDef);
                if (valueData == null)
                    ps.setNull(vdPos, java.sql.Types.NUMERIC);
                else
                    ps.setInt(vdPos, valueData);
                ps.executeUpdate();
                insertCount++;
            }

            /**
             * Get property id, xpath and data type for an assignment
             *
             * @param assignment assignment id
             * @return Object[] {propertyId, xpath, datatype}
             */
            private Object[] getPropertyXPathDataType(long assignment) {
                if (assignmentPropAlias.get(assignment) != null)
                    return assignmentPropAlias.get(assignment);
                try {
                    psGetAssInfo.setLong(1, assignment);
                    ResultSet rs = psGetAssInfo.executeQuery();
                    if (rs != null && rs.next()) {
                        Object[] data = new Object[] { rs.getLong(1), rs.getString(2), rs.getLong(3) };
                        assignmentPropAlias.put(assignment, data);
                        return data;
                    }
                } catch (SQLException e) {
                    throw new IllegalArgumentException(
                            "Could not load data for assignment " + assignment + ": " + e.getMessage());
                }
                throw new IllegalArgumentException("Could not load data for assignment " + assignment + "!");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (inElement)
                    sbData.append(ch, start, length);
            }

        };
        parser.parse(zip.getInputStream(zeData), handler);
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, psGetAssInfo, psString, psBoolean, psDouble,
                psFloat, psLargeNumber, psNumber, psReference, psSelectOne, psText);
    }
}

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

public void findLastClassification(String panelname) {
    try {/*ww w  .  ja va 2  s.  c o m*/
        int tmpseq;
        last_classification = 0;

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

        File s = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);

        String expression = "//*[@ID='22']";
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();

        doc = dBuilder.parse(s.getAbsolutePath());

        NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);

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

    } catch (SAXException ex) {
        Logger.getLogger(MetaUtility.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MetaUtility.class.getName()).log(Level.SEVERE, null, ex);
    } catch (XPathExpressionException ex) {
        Logger.getLogger(MetaUtility.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(MetaUtility.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

public void findLastContribute(String panelname) {
    try {// w w  w.  j  a  v a 2 s  .  c  o m
        int tmpseq;
        last_contribute = 0;

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

        File s = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);

        String expression = "//*[@ID='11']";
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();

        doc = dBuilder.parse(s.getAbsolutePath());

        NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength() && nodeList.getLength() > 1; i++) {
            NamedNodeMap attr = nodeList.item(i).getAttributes();
            Node nodeAttr = attr.getNamedItem("sequence");
            tmpseq = Integer.parseInt(nodeAttr.getNodeValue());
            System.out.println("contribute sequence: " + tmpseq);
            if (tmpseq > last_contribute) {
                last_contribute = tmpseq;
            }
        }

    } catch (SAXException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } catch (XPathExpressionException ex) {
        logger.error(ex.getMessage());
    } catch (ParserConfigurationException ex) {
        logger.error(ex.getMessage());
    }
}

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

public String addClassificationLinkFromid(String id) {
    boolean found = false;
    String link = "";

    if (this.classificationIDS.containsValue(id)) {
        return Utility.getValueFromKey(this.classificationIDS, id);
    } else {// w w w  .ja v a  2s . c  o  m
        for (String classificationLink : this.availableClassifications.keySet()) {
            try {
                if (found == false && !classificationIDS.containsKey(classificationLink)) {
                    Document doc = Utility.getDocument(classificationLink, true);
                    XPath taxonpath = XPathFactory.newInstance().newXPath();
                    String expression = "//*[local-name()='classification']";

                    NodeList nodeList = (NodeList) taxonpath.evaluate(expression, doc, XPathConstants.NODESET);

                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Element node = (Element) nodeList.item(i);

                        if (node.getAttribute("ID").equals(id)) {
                            classificationIDS.put(classificationLink, id);
                            link = classificationLink;
                            found = true;
                        } else {
                            classificationIDS.put(classificationLink, id);
                        }
                    }
                }
            } 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());
            }
        }

        return link;
    }
}

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

/**
 * Metodo adibito alla lettura ricorsiva dei file delle classificazioni
 *
 * @return TreeMap<Object, Taxon>/*from  w ww .j  a  v  a 2 s .com*/
 * @throws Exception
 */
public void classifications_reader(String sequence, String panelname) throws Exception {
    ResourceBundle bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE, Globals.loader);
    String currentlink = "";

    try {
        boolean defaultclassification = true;
        boolean alreadyread = false;

        if (!sequence.isEmpty()) {
            defaultclassification = false;
            currentlink = selectedClassificationList.get(panelname + "---" + sequence);

            if (!currentlink.isEmpty()) {
                if (oefos.containsKey(currentlink))
                    alreadyread = true;
            }
        }

        for (String classificationLink : this.availableClassifications.keySet()) {
            if (!alreadyread && (defaultclassification
                    || (!currentlink.isEmpty() && classificationLink.equals(currentlink)))) {
                defaultclassification = false;

                TreeMap<Object, Taxon> rval = new TreeMap<Object, Taxon>();
                Document doc = Utility.getDocument(classificationLink, true);
                XPath taxonpath = XPathFactory.newInstance().newXPath();
                String expression = "//*[local-name()='classification']";

                NodeList nList = (NodeList) taxonpath.evaluate(expression, doc, XPathConstants.NODESET);

                for (int s = 0; s < nList.getLength(); s++) {
                    Element classification = (Element) nList.item(s);

                    if (classification == null) {
                        throw new Exception("Classification 1 not found");
                    } else {
                        classificationIDS.put(classificationLink, classification.getAttribute("ID"));

                        NodeList tList = classification.getChildNodes();
                        for (int z = 0; z < tList.getLength(); z++) {
                            if (tList.item(z).getNodeType() == Node.ELEMENT_NODE) {
                                Element taxons = (Element) tList.item(z);

                                if (taxons.getTagName().equals("taxons")) {
                                    classifications_reader_taxons(taxons, rval);
                                }
                            }
                        }

                        oefos.put(classificationLink, rval);
                    }
                }
            }
        }

    } catch (Exception ex) {
        throw new Exception(Utility.getBundleString("error4", bundle) + ": " + ex.getMessage());
    }
}

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

public void setSessionMetadataFile(String filetoparse, String panelname) {
    try {/*from   www .j a  v  a 2s. com*/
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc;

        File f = new File(Globals.BACKUP_METADATA);
        File s = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);
        FileUtils.copyFile(f, s);

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

        File impmetadata = new File(filetoparse);
        doc = dBuilder.parse(impmetadata);

        String expression = "//*[local-name()='contribute']";
        NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength() - 1; i++) {
            addContributorToMetadata(panelname);
        }

        expression = "//*[local-name()='taxonpath']";
        nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength() - 1; i++) {
            addClassificationToMetadata(panelname);
        }
    } catch (ParserConfigurationException ex) {
        logger.error(ex.getMessage());
    } catch (XPathExpressionException ex) {
        logger.error(ex.getMessage());
    } catch (SAXException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    }
}

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

private void read_uwmetadata_recursive(Map<Object, Metadata> submetadatas, String xpath,
        NamespaceContextImpl nsmgr, Document nav, String panelname) throws XPathExpressionException {
    for (Map.Entry<Object, Metadata> field : submetadatas.entrySet()) {
        String actXpath = "";
        if (field.getValue().MID_parent == 11 || field.getValue().MID_parent == 13) {
            actXpath = xpath + "[@seq='" + field.getValue().sequence + "']/"
                    + nsmgr.getPrefix(field.getValue().foxmlnamespace) + ":" + field.getValue().foxmlname;
        } else {//  w  ww.  j av  a  2s . c  o m
            actXpath = xpath + "/" + nsmgr.getPrefix(field.getValue().foxmlnamespace) + ":"
                    + field.getValue().foxmlname;
        }

        if (!field.getValue().datatype.equals("Node") && field.getValue().editable.equals("Y")) {

            Element node = Utility.getXPathNode(actXpath, nsmgr, nav);

            if (node != null) {
                if (field.getValue().datatype.equals("LangString")) {
                    field.getValue().value = node.getTextContent();
                    field.getValue().language = node.getAttribute("language");
                } else if (field.getValue().datatype.equals("ClassificationSource")) {
                    XPath taxonpath = XPathFactory.newInstance().newXPath();
                    String expression = "//*[local-name()='taxonpath'][@seq='" + field.getValue().sequence
                            + "']";
                    ;
                    NodeList nodeList = (NodeList) taxonpath.evaluate(expression, nav, XPathConstants.NODESET);
                    TreeMap<Integer, Integer> single_path = new TreeMap<Integer, Integer>();

                    int countpaths = 1;
                    for (int j = 0; j < nodeList.getLength(); j++) {
                        NodeList children = nodeList.item(j).getChildNodes();

                        for (int i = 0; i < children.getLength(); i++) {
                            Node nodetaxon = (Node) children.item(i);
                            if (nodetaxon.getNodeName().equals("ns7:source")) {
                                String link = this.addClassificationLinkFromid(nodetaxon.getTextContent());
                                this.selectedClassificationList
                                        .put(panelname + "---" + field.getValue().sequence, link);
                            }
                            if (nodetaxon.getNodeName().equals("ns7:taxon")) {
                                single_path.put(countpaths, Integer.parseInt(nodetaxon.getTextContent()));
                                countpaths++;
                            }
                        }
                        //OefosPaths path = new OefosPaths(panelname, field.getValue().sequence);
                        this.oefos_path.put(panelname + "----" + field.getValue().sequence, single_path);
                    }
                } else {
                    field.getValue().value = node.getTextContent();
                }
            }
        }
        if (field.getValue().submetadatas != null) {
            read_uwmetadata_recursive(field.getValue().submetadatas, actXpath, nsmgr, nav, panelname);
        }
    }
}

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 w w w. j  av  a 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:it.imtech.metadata.MetaUtility.java

private void addContributorToMetadata(String panelname) {
    try {/*from   w  w  w  .j av  a  2  s. co  m*/
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc;

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        File backupmetadata = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);
        //File backupmetadata = new File(Globals.SESSION_METADATA);
        doc = dBuilder.parse(backupmetadata);

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

        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;
            }
        }
        maxseq++;

        Node newNode = nodeList.item(0).cloneNode(true);
        Element nodetocopy = (Element) newNode;
        NamedNodeMap attr = nodeList.item(0).getAttributes();
        Node nodeAttr = attr.getNamedItem("sequence");
        nodeAttr.setTextContent(Integer.toString(maxseq));

        Node copyOfn = doc.importNode(nodetocopy, true);
        nodeList.item(0).getParentNode().appendChild(copyOfn);

        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:it.imtech.metadata.MetaUtility.java

private void removeContributorToMetadata(String panelname) {
    try {/*  w w w. j a v  a2s  . c o m*/
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc;

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        File backupmetadata = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname);
        //File backupmetadata = new File(Globals.SESSION_METADATA);
        doc = dBuilder.parse(backupmetadata);

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

        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;
            }
        }
        //maxseq++;

        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++;
        }

        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());
    }
}