Example usage for org.w3c.dom Document getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:org.oscarehr.phr.service.PHRService.java

public void sendQueuedDocuments(PHRAuthentication auth, String providerNo) throws Exception {
    // package sharing
    // IndivoAPService apService = new IndivoAPService(this);
    // apService.packageAllAccessPolicies(auth);

    List<PHRAction> actions = phrActionDAO.getQueuedActions(providerNo);
    logger.debug("Processing " + actions.size() + " actions ");

    // TalkClient client = getTalkClient();
    for (PHRAction action : actions) {

        boolean updated = false;
        Long resultId = null;//from   w w  w. j  a v a 2  s .  co  m
        // handle messages differently
        logger.debug("ACTION classification " + action.getPhrClassification() + " action type "
                + action.getActionType() + ", phr_action.id=" + action.getId());
        try {
            if (action.getPhrClassification().equalsIgnoreCase("MESSAGE")
                    && (action.getActionType() == PHRAction.ACTION_ADD
                            || action.getActionType() == PHRAction.ACTION_UPDATE)) {
                sendMessage(auth, action);
                updated = true;
            } else if (action.getPhrClassification().equalsIgnoreCase("RELATIONSHIP")
                    && (action.getActionType() == PHRAction.ACTION_ADD
                            || action.getActionType() == PHRAction.ACTION_UPDATE)) {
                sendRelationship(auth, action);
                updated = true;
            } else if (action.getActionType() == PHRAction.ACTION_ADD
                    || action.getActionType() == PHRAction.ACTION_UPDATE) {// dealing with medication type document

                // if adding
                IndivoDocumentType doc = action.getIndivoDocument();
                if (action.getPhrClassification().equals(MedicalDataType.BINARY_DOCUMENT.name())) {
                    doc = PHRBinaryData.mountDocument(action.getOscarId(), doc);

                    MedicalDataWs medicalDataWs = MyOscarServerWebServicesManager
                            .getMedicalDataWs(auth.getMyOscarUserId(), auth.getMyOscarPassword());
                    logger.debug("sending medical data : " + action.getOscarId() + ", " + action.getDateSent()
                            + ", " + action.getPhrClassification() + ", " + auth.getMyOscarUserId() + ", "
                            + doc);

                    GregorianCalendar dataTime = new GregorianCalendar();

                    EDoc edoc = EDocUtil.getDoc(action.getOscarId());

                    org.w3c.dom.Document xmlDocument = XmlUtils.newDocument("BinaryDocument");
                    XmlUtils.appendChildToRoot(xmlDocument, "Filename", edoc.getFileName());
                    XmlUtils.appendChildToRoot(xmlDocument, "FileDescription", edoc.getDescription());
                    XmlUtils.appendChildToRoot(xmlDocument, "MimeType", edoc.getContentType());
                    XmlUtils.appendChildToRoot(xmlDocument, "Data", edoc.getFileBytes());
                    String xmlString = XmlUtils.toString(xmlDocument, false);

                    if (doc.getDocumentHeader().getCreationDateTime() != null)
                        dataTime = doc.getDocumentHeader().getCreationDateTime().toGregorianCalendar();

                    MedicalDataTransfer3 medicalDataTransfer = new MedicalDataTransfer3();
                    medicalDataTransfer.setActive(true);
                    medicalDataTransfer.setCompleted(true);
                    medicalDataTransfer.setData(xmlString);
                    medicalDataTransfer.setDateOfData(dataTime);
                    medicalDataTransfer.setMedicalDataType(action.getPhrClassification());
                    medicalDataTransfer.setObserverOfDataPersonId(auth.getMyOscarUserId());

                    LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();
                    medicalDataTransfer
                            .setObserverOfDataPersonName(loggedInInfo.loggedInProvider.getFormattedName());
                    medicalDataTransfer.setOriginalSourceId(
                            loggedInInfo.currentFacility.getName() + ":EDoc:" + edoc.getDocId());
                    medicalDataTransfer.setOwningPersonId(action.getReceiverMyOscarUserId());

                    resultId = medicalDataWs.addMedicalData3(medicalDataTransfer);
                } else if (action.getPhrClassification().equals("ANNOTATION")) {
                    try {
                        String referenceIndex = PHRIndivoAnnotation.getAnnotationReferenceIndex(doc);// temporarily stored
                        PHRAction referencedDocumentAction = phrActionDAO.getActionById(referenceIndex);
                        if (referencedDocumentAction == null)
                            throw new Exception("Cannot find annotated document");
                        if (referencedDocumentAction.getPhrIndex() == null)
                            continue; // referenced document must be sent first
                        doc = PHRIndivoAnnotation.mountReferenceDocument(
                                referencedDocumentAction.getPhrClassification(),
                                referencedDocumentAction.getPhrIndex(),
                                referencedDocumentAction.getIndivoDocument().getDocumentVersion().size() - 1,
                                doc);
                        action = PHRIndivoDocument.setDocContent(doc, action);
                        phrActionDAO.save(action);
                    } catch (Exception e) {
                        logger.error("Could not send the annotation with ID: '" + action.getId()
                                + "' to PHR; skipping it...", e);
                        action.setStatus(PHRAction.STATUS_OTHER_ERROR);
                        phrActionDAO.update(action);
                        continue; // if there is an error sending annotation, screw it...move on
                    }
                } else if (action.getPhrClassification().equals(MedicalDataType.MEDICATION.name())) {

                    MedicalDataWs medicalDataWs = MyOscarServerWebServicesManager
                            .getMedicalDataWs(auth.getMyOscarUserId(), auth.getMyOscarPassword());

                    GregorianCalendar dataTime = new GregorianCalendar();

                    Node medicationNode = doc.getDocumentVersion().get(0).getVersionBody().getAny();

                    org.w3c.dom.Document xmlDocument = XmlUtils.newDocument("Medication");
                    Node xmlDocumentRootNode = xmlDocument.getFirstChild();

                    NodeList nodeList = medicationNode.getChildNodes();
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Node node = nodeList.item(i);
                        node = xmlDocument.importNode(node, true);
                        xmlDocumentRootNode.appendChild(node);
                    }

                    String xmlString = XmlUtils.toString(xmlDocument, false);

                    logger.debug("sending medical data : " + action.getOscarId() + ", " + action.getDateSent()
                            + ", " + action.getPhrClassification() + ", " + auth.getMyOscarUserId() + ", "
                            + xmlString);

                    if (doc.getDocumentHeader().getCreationDateTime() != null)
                        dataTime = doc.getDocumentHeader().getCreationDateTime().toGregorianCalendar();

                    MedicalDataTransfer3 medicalDataTransfer = new MedicalDataTransfer3();
                    medicalDataTransfer.setActive(true);
                    medicalDataTransfer.setCompleted(true);
                    medicalDataTransfer.setData(xmlString);
                    medicalDataTransfer.setDateOfData(dataTime);
                    medicalDataTransfer.setMedicalDataType(action.getPhrClassification());
                    medicalDataTransfer.setObserverOfDataPersonId(auth.getMyOscarUserId());

                    LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();
                    medicalDataTransfer
                            .setObserverOfDataPersonName(loggedInInfo.loggedInProvider.getFormattedName());
                    medicalDataTransfer.setOriginalSourceId(
                            loggedInInfo.currentFacility.getName() + ":medication:" + action.getOscarId());
                    medicalDataTransfer.setOwningPersonId(action.getReceiverMyOscarUserId());

                    resultId = medicalDataWs.addMedicalData3(medicalDataTransfer);
                }

                // AddDocumentResultType result = client.addDocument(auth.getToken(), action.getReceiverPhr(), doc);
                String resultIndex = resultId.toString();
                action.setPhrIndex(resultId.toString());
                // updates indexes to handle the case where two operations on this file are queued
                phrActionDAO.updatePhrIndexes(action.getPhrClassification(), action.getOscarId(),
                        action.getSenderOscar(), resultIndex);
                actions = PHRAction.updateIndexes(action.getPhrClassification(), action.getOscarId(),
                        resultIndex, actions);
                updated = true;
                // if updating

            } else if (action.getPhrClassification().equalsIgnoreCase("MESSAGE")
                    && action.getActionType() == PHRAction.ACTION_UPDATE) {
                logger.info(
                        "excuse me but since when can you ever update a message that's been sent? no messaging system allows that.");

                // logger.debug("HERE MESSAGE UPDATE");
                // org.indivo.xml.JAXBUtils jaxbUtils = new org.indivo.xml.JAXBUtils();
                //
                // IndivoDocumentType document = action.getIndivoDocument();
                //
                // JAXBContext messageContext = JAXBContext.newInstance("org.indivo.xml.phr.message");
                // MessageType msg = (MessageType) org.indivo.xml.phr.DocumentUtils.getDocumentAnyObject(document, messageContext.createUnmarshaller());
                // // ??? Should i use reflection to abstract the call to ObjectFactory??? how will in know what method to call? the one that will take MessageType as a param???
                // logger.debug("IS READ " + msg.isRead());
                // Element element = jaxbUtils.marshalToElement(new org.indivo.xml.phr.message.ObjectFactory().createMessage(msg), JAXBContext.newInstance("org.indivo.xml.phr.message"));
                //
                // DocumentVersionGenerator dvg = new DocumentVersionGenerator();
                // DocumentVersionType newVersion = dvg.generateDefaultDocumentVersion(auth.getUserId(), auth.getName(), auth.getRole(), element);
                // logger.debug("BEFORE UPDATE DOCUMENT calling with token " + auth.getToken() + " id " + auth.getUserId() + " idx " + action.getPhrIndex() + " v " + newVersion);
                // UpdateDocumentResultType updateDocRes = client.updateDocument(auth.getToken(), auth.getUserId(), action.getPhrIndex(), newVersion);
                // if (updateDocRes == null) {
                // logger.debug("UPDATE DOC IS NULL");
                // } else {
                // logger.debug("UPDATE DOC IS NOT NULL" + updateDocRes.toString());
                // }
                // logger.debug("AFTER UPDATE DOCUMENT");
                // updated = true;

            } else if (action.getActionType() == PHRAction.ACTION_UPDATE) {
                logger.info(
                        "sorry but there's no such thing as update for relationship / medical documents / messages, you can create or delete them only.");

                // logger.debug("else 2");
                // if (action.getPhrIndex() == null && !action.getPhrClassification().equals(PHRConstants.DOCTYPE_ACCESSPOLICIES())) throw new Exception("Error: PHR index not set");
                //
                // if (action.getPhrClassification().equals(PHRConstants.DOCTYPE_ACCESSPOLICIES())) action = apService.packageAccessPolicy(auth, action);
                // IndivoDocumentType doc = action.getIndivoDocument();
                // if (action.getPhrClassification().equals(PHRConstants.DOCTYPE_BINARYDATA())) doc = PHRBinaryData.mountDocument(action.getOscarId(), doc);
                // Element documentElement = DocumentUtils.getDocumentAnyElement(doc);
                // // Retrieve current file record from indivo
                // logger.debug("phr index " + action.getPhrIndex());
                // // ReadDocumentResultType readResult = client.readDocument(auth.getToken(), action.getSenderPhr(), action.getPhrIndex());
                // // IndivoDocumentType phrDoc = readResult.getIndivoDocument();
                //
                // IndivoDocumentType phrDoc = null;
                // if (action.getPhrClassification().equals(PHRConstants.DOCTYPE_MESSAGE())) {
                // PHRDocument phrd = phrDocumentDAO.getDocumentByIndex(action.getPhrIndex());
                // JAXBContext docContext = JAXBContext.newInstance(IndivoDocumentType.class.getPackage().getName());
                // Unmarshaller unmarshaller = docContext.createUnmarshaller();
                //
                // JAXBElement jaxment = (JAXBElement) unmarshaller.unmarshal(new StringReader(phrd.getDocContent()));
                // phrDoc = (IndivoDocumentType) jaxment.getValue();
                // } else {
                // ReadDocumentResultType readResult = client.readDocument(auth.getToken(), action.getReceiverPhr(), action.getPhrIndex());
                // phrDoc = readResult.getIndivoDocument();
                // }
                //
                // DocumentVersionType version = phrDoc.getDocumentVersion().get(phrDoc.getDocumentVersion().size() - 1);
                //
                // // send new version
                // VersionBodyType body = version.getVersionBody();
                // body.setAny(documentElement);
                // version.setVersionBody(body);
                // if (action.getPhrClassification().equals(PHRConstants.DOCTYPE_MESSAGE())) {
                // client.updateDocument(auth.getToken(), auth.getUserId(), action.getPhrIndex(), version);
                // } else {
                // client.updateDocument(auth.getToken(), action.getReceiverPhr(), action.getPhrIndex(), version);
                // }
                // updated = true;
            } else {
                logger.debug("NOTHING IS GETTING CALLED FOR THIS ");

            }
        } catch (ActionNotPerformedException anpe) {
            // assuming user does not have authorization for the action - in this case mark it as unauthorized and stop trying to send
            logger.debug("Setting Status Not Authorized");
            action.setStatus(PHRAction.STATUS_NOT_AUTHORIZED);
            phrActionDAO.update(action);
        } catch (IndivoException ie) {
            // assuming connection problems - in this case log the user off to take load off the server
            logger.debug("IndivoException thrown");
            throw new Exception(ie);
        } catch (Exception e) {
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
            logger.error(
                    "Exception Thrown that is not due to connection or Authorization...probably jaxb problem "
                            + formatter.format(new Date()),
                    e);
            updated = false;
            action.setStatus(PHRAction.STATUS_OTHER_ERROR);
            phrActionDAO.update(action);
        }
        if (updated) {
            action.setStatus(PHRAction.STATUS_SENT);
            phrActionDAO.update(action);
        }
    }
}

From source file:org.oscarehr.PMmodule.caisi_integrator.ConformanceTestHelper.java

public static void populateLocalTicklerWithRemoteProviderMessageFollowUps() {
    try {/*from  w w w .ja  v  a2 s  .c o m*/
        LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();

        ProviderWs providerWs = CaisiIntegratorManager.getProviderWs();
        List<ProviderCommunicationTransfer> followUps = providerWs
                .getProviderCommunications(loggedInInfo.loggedInProvider.getProviderNo(), "FOLLOWUP", true);

        if (followUps == null)
            return;

        logger.debug("Folowups found : " + followUps.size());

        for (ProviderCommunicationTransfer providerCommunication : followUps) {
            Document doc = XmlUtils.toDocument(providerCommunication.getData());
            Node root = doc.getFirstChild();
            String demographicId = XmlUtils.getChildNodeTextContents(root, "destinationDemographicId");
            String note = XmlUtils.getChildNodeTextContents(root, "note");

            TicklerCreator t = new TicklerCreator();

            logger.debug("Create tickler : " + demographicId + ", "
                    + providerCommunication.getDestinationProviderId() + ", " + note);

            FacilityIdStringCompositePk senderProviderId = new FacilityIdStringCompositePk();
            senderProviderId.setIntegratorFacilityId(providerCommunication.getSourceIntegratorFacilityId());
            senderProviderId.setCaisiItemId(providerCommunication.getSourceProviderId());
            CachedProvider senderProvider = CaisiIntegratorManager.getProvider(senderProviderId);
            if (senderProvider != null) {
                note = "Sent by remote provider : " + senderProvider.getLastName() + ", "
                        + senderProvider.getFirstName() + "<br />--------------------<br />" + note;
            }

            t.createTickler(demographicId, providerCommunication.getDestinationProviderId(), note);

            providerWs.deactivateProviderCommunication(providerCommunication.getId());
        }
    } catch (Exception e) {
        logger.error("Error", e);
    }
}

From source file:org.peertrust.demo.common.InstallationSession.java

/**
 * Gets the version of the install.xml document.
 * @param doc - a Document built from an install.xml file
 * @return the version as string // ww w. j a va2s .  c om
 *          or null if doc is null or the document das not
 *          have a version attribute  
 */
final private static String getVersion(Document doc) {
    if (doc == null) {
        return null;
    }
    Node root = doc.getFirstChild();
    Node versionAtt = root.getAttributes().getNamedItem("version");
    if (versionAtt == null) {
        return null;
    } else {
        String version = versionAtt.getTextContent();
        return version;
    }
}

From source file:org.pentaho.di.core.row.RowMetaTest.java

@Test
public void testRowMetaInitializingFromXmlNode() throws Exception {
    String testXmlNode = null;/*from   w w  w. jav a  2s .c  o  m*/
    try (InputStream in = RowMetaTest.class.getResourceAsStream("rowMetaNode.xml")) {
        testXmlNode = IOUtils.toString(in);
    }
    Document xmlDoc = XMLHandler.loadXMLString(testXmlNode);
    RowMeta rowMeta = spy(new RowMeta(xmlDoc.getFirstChild()));
    assertEquals(2, rowMeta.getValueMetaList().size());
    ValueMetaInterface valueMeta = rowMeta.getValueMeta(0);
    assertTrue(valueMeta instanceof ValueMetaDate);
    assertEquals("testDate", valueMeta.getName());
    assertNull(valueMeta.getConversionMask());
    valueMeta = rowMeta.getValueMeta(1);
    assertTrue(valueMeta instanceof ValueMetaTimestamp);
    assertEquals("testTimestamp", valueMeta.getName());
    assertEquals("yyyy/MM/dd HH:mm:ss.000000000", valueMeta.getConversionMask());
}

From source file:org.pentaho.di.trans.steps.webservices.WebService.java

private void processRows(InputStream anXml, Object[] rowData, RowMetaInterface rowMeta,
        boolean ignoreNamespacePrefix, String encoding) throws KettleException {
    // Just to make sure the old transformations keep working...
    ////  ww  w.  j a v  a  2s.  com
    if (meta.isCompatible()) {
        compatibleProcessRows(anXml, rowData, rowMeta, ignoreNamespacePrefix, encoding);
        return;
    }

    // First we should get the complete string
    // The problem is that the string can contain XML or any other format such as HTML saying the service is no longer
    // available.
    // We're talking about a WEB service here.
    // As such, to keep the original parsing scheme, we first read the content.
    // Then we create an input stream from the content again.
    // It's elaborate, but that way we can report on the failure more correctly.
    //
    String response = readStringFromInputStream(anXml, encoding);

    try {

        // What is the expected response object for the operation?
        //
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        Document doc = documentBuilder.parse(new InputSource(new StringReader(response)));

        Node envelopeNode = doc.getFirstChild();
        String nsPrefix = envelopeNode.getPrefix();
        Node bodyNode = XMLHandler.getSubNode(envelopeNode, nsPrefix + ":Body");
        if (bodyNode == null) {
            XMLHandler.getSubNode(envelopeNode, nsPrefix + ":body"); // retry, just in case!
        }

        // Create a few objects to help do the layout of XML snippets we find along the way
        //
        Transformer transformer = null;
        try {
            Class<?> clazz = Class.forName("org.apache.xalan.processor.TransformerFactoryImpl");
            TransformerFactory transformerFactory = (TransformerFactory) clazz.newInstance();
            transformer = transformerFactory.newTransformer();
        } catch (Throwable t) {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            transformer = transformerFactory.newTransformer();
        }
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        if (log.isDetailed()) {
            StringWriter bodyXML = new StringWriter();
            transformer.transform(new DOMSource(bodyNode), new StreamResult(bodyXML));

            logDetailed(bodyXML.toString());
        }

        // The node directly below the body is the response node
        // It's apparently a hassle to get the name in a consistent way, but we know it's the first element node
        //
        Node responseNode = null;
        NodeList nodeList = null;
        if (!Const.isEmpty(meta.getRepeatingElementName())) {

            // We have specified the repeating element name : use it
            //
            nodeList = ((Element) bodyNode).getElementsByTagName(meta.getRepeatingElementName());

        } else {

            if (meta.isReturningReplyAsString()) {

                // Just return the body node as an XML string...
                //
                StringWriter nodeXML = new StringWriter();
                transformer.transform(new DOMSource(bodyNode), new StreamResult(nodeXML));
                String xml = response; // nodeXML.toString();
                Object[] outputRowData = createNewRow(rowData);
                int index = rowData == null ? 0 : getInputRowMeta().size();
                outputRowData[index++] = xml;
                putRow(data.outputRowMeta, outputRowData);

            } else {

                // We just grab the list of nodes from the children of the body
                // Look for the first element node (first real child) and take that one.
                // For that child-element, we consider all the children below
                //
                NodeList responseChildren = bodyNode.getChildNodes();
                for (int i = 0; i < responseChildren.getLength(); i++) {
                    Node responseChild = responseChildren.item(i);
                    if (responseChild.getNodeType() == Node.ELEMENT_NODE) {
                        responseNode = responseChild;
                        break;
                    }
                }

                // See if we want the whole block returned as XML...
                //
                if (meta.getFieldsOut().size() == 1) {
                    WebServiceField field = meta.getFieldsOut().get(0);
                    if (field.getWsName().equals(responseNode.getNodeName())) {
                        // Pass the data as XML
                        //
                        StringWriter nodeXML = new StringWriter();
                        transformer.transform(new DOMSource(responseNode), new StreamResult(nodeXML));
                        String xml = nodeXML.toString();

                        Object[] outputRowData = createNewRow(rowData);
                        int index = rowData == null ? 0 : getInputRowMeta().size();
                        outputRowData[index++] = xml;
                        putRow(data.outputRowMeta, outputRowData);

                    } else {
                        if (responseNode != null) {
                            nodeList = responseNode.getChildNodes();
                        }
                    }

                } else {
                    if (responseNode != null) {
                        nodeList = responseNode.getChildNodes();
                    }
                }
            }
        }

        // The section below is just for repeating nodes. If we don't have those it ends here.
        //
        if (nodeList == null || meta.isReturningReplyAsString()) {
            return;
        }

        // Allocate a result row in case we are dealing with a single result row
        //
        Object[] outputRowData = createNewRow(rowData);

        // Now loop over the node list found above...
        //
        boolean singleRow = false;
        int fieldsFound = 0;
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);

            if (meta.isReturningReplyAsString()) {

                // Just return the body node as an XML string...
                //
                StringWriter nodeXML = new StringWriter();
                transformer.transform(new DOMSource(bodyNode), new StreamResult(nodeXML));
                String xml = nodeXML.toString();
                outputRowData = createNewRow(rowData);
                int index = rowData == null ? 0 : getInputRowMeta().size();
                outputRowData[index++] = xml;
                putRow(data.outputRowMeta, outputRowData);

            } else {

                // This node either contains the data for a single row or it contains the first element of a single result
                // response
                // If we find the node name in out output result fields list, we are going to consider it a single row result.
                //
                WebServiceField field = meta.getFieldOutFromWsName(node.getNodeName(), ignoreNamespacePrefix);
                if (field != null) {
                    if (getNodeValue(outputRowData, node, field, transformer, true)) {
                        // We found a match.
                        // This means that we are dealing with a single row
                        // It also means that we need to update the output index pointer
                        //
                        singleRow = true;
                        fieldsFound++;
                    }
                } else {
                    // If we didn't already get data in the previous block we'll assume multiple rows coming back.
                    //
                    if (!singleRow) {
                        // Sticking with the multiple-results scenario...
                        //

                        // TODO: remove next 2 lines, added for debug reasons.
                        //
                        if (log.isDetailed()) {
                            StringWriter nodeXML = new StringWriter();
                            transformer.transform(new DOMSource(node), new StreamResult(nodeXML));
                            logDetailed(BaseMessages.getString(PKG, "WebServices.Log.ResultRowDataFound",
                                    nodeXML.toString()));
                        }

                        // Allocate a new row...
                        //
                        outputRowData = createNewRow(rowData);

                        // Let's see what's in there...
                        //
                        NodeList childNodes = node.getChildNodes();
                        for (int j = 0; j < childNodes.getLength(); j++) {
                            Node childNode = childNodes.item(j);

                            field = meta.getFieldOutFromWsName(childNode.getNodeName(), ignoreNamespacePrefix);
                            if (field != null) {

                                if (getNodeValue(outputRowData, childNode, field, transformer, false)) {
                                    // We found a match.
                                    // This means that we are dealing with a single row
                                    // It also means that we need to update the output index pointer
                                    //
                                    fieldsFound++;
                                }
                            }
                        }

                        // Prevent empty rows from being sent out.
                        //
                        if (fieldsFound > 0) {
                            // Send a row in a series of rows on its way.
                            //
                            putRow(data.outputRowMeta, outputRowData);
                        }
                    }
                }
            }
        }

        if (singleRow && fieldsFound > 0) {
            // Send the single row on its way.
            //
            putRow(data.outputRowMeta, outputRowData);
        }
    } catch (Exception e) {
        throw new KettleStepException(
                BaseMessages.getString(PKG, "WebServices.ERROR0010.OutputParsingError", response.toString()),
                e);
    }
}

From source file:org.pentaho.platform.plugin.action.kettle.KettleComponent.java

/**
 * Execute the specified transformation in the chosen repository.
 *///from   w w w .ja v a  2s. c  om
@SuppressWarnings("unchecked")
@Override
public boolean executeAction() {

    if (ComponentBase.debug) {
        debug(Messages.getInstance().getString("Kettle.DEBUG_START")); //$NON-NLS-1$
    }

    TransMeta transMeta = null;
    JobMeta jobMeta = null;

    // Build lists of parameters, variables and command line arguments

    Map<String, String> argumentMap = new HashMap<String, String>();
    Map<String, String> variableMap = new HashMap<String, String>();
    Map<String, String> parameterMap = new HashMap<String, String>();

    for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_CMD_ARG)) {
        argumentMap.put(n.selectSingleNode("name").getText(),
                applyInputsToFormat(getInputStringValue(n.selectSingleNode("mapping").getText()))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_VARIABLE)) {
        variableMap.put(n.selectSingleNode("name").getText(),
                applyInputsToFormat(getInputStringValue(n.selectSingleNode("mapping").getText()))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_PARAMETER)) {
        parameterMap.put(n.selectSingleNode("name").getText(),
                applyInputsToFormat(getInputStringValue(n.selectSingleNode("mapping").getText()))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    String[] arguments = null;

    // If no mappings are provided, assume all inputs are command line
    // arguments (This supports the legacy method)
    if (argumentMap.size() <= 0 && variableMap.size() <= 0 && parameterMap.size() <= 0) {
        // this use is now considered obsolete, as we prefer the
        // action-sequence inputs since they
        // now maintain order
        boolean running = true;
        int index = 1;
        ArrayList<String> argumentList = new ArrayList<String>();
        while (running) {
            if (isDefinedInput("parameter" + index)) { //$NON-NLS-1$
                String value = null;
                String inputName = getInputStringValue("parameter" + index); //$NON-NLS-1$
                // see if we have an input with this name
                if (isDefinedInput(inputName)) {
                    value = getInputStringValue(inputName);
                }
                argumentList.add(value);
            } else {
                running = false;
            }
            index++;
        }

        // this is the preferred way to provide inputs to the
        // KetteComponent, the order of inputs is now preserved
        Iterator<?> inputNamesIter = getInputNames().iterator();
        while (inputNamesIter.hasNext()) {
            String name = (String) inputNamesIter.next();
            argumentList.add(getInputStringValue(name));
        }

        arguments = (String[]) argumentList.toArray(new String[argumentList.size()]);
    } else {
        // Extract arguments from argumentMap (Throw an error if the
        // sequential ordering is broken)
        arguments = new String[argumentMap.size()];
        for (int i = 0; i < argumentMap.size(); i++) {
            arguments[i] = argumentMap.get(Integer.toString(i + 1)); // Mapping
            // is
            // 1
            // based
            // to
            // match
            // Kettle
            // UI
            if (arguments[i] == null) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0030_INVALID_ARGUMENT_MAPPING")); //$NON-NLS-1$
            }
        }
    }

    // initialize environment variables
    try {
        KettleSystemListener.environmentInit(getSession());
    } catch (KettleException ke) {
        error(ke.getMessage(), ke);
    }

    String solutionPath = "solution:";

    Repository repository = connectToRepository();
    boolean result = false;

    try {
        if (isDefinedInput(KettleComponent.DIRECTORY)) {
            String directoryName = getInputStringValue(KettleComponent.DIRECTORY);

            if (repository == null) {
                return false;
            }

            if (isDefinedInput(KettleComponent.TRANSFORMATION)) {
                String transformationName = getInputStringValue(KettleComponent.TRANSFORMATION);
                transMeta = loadTransformFromRepository(directoryName, transformationName, repository);
                if (transMeta != null) {
                    try {
                        for (String key : parameterMap.keySet()) {
                            transMeta.setParameterValue(key, parameterMap.get(key));
                        }
                        for (String key : variableMap.keySet()) {
                            transMeta.setVariable(key, variableMap.get(key));
                        }

                    } catch (UnknownParamException e) {
                        error(e.getMessage());
                    }
                    transMeta.setArguments(arguments);
                } else {
                    return false;
                }
            } else if (isDefinedInput(KettleComponent.JOB)) {
                String jobName = getInputStringValue(KettleComponent.JOB);
                jobMeta = loadJobFromRepository(directoryName, jobName, repository);
                if (jobMeta != null) {
                    try {
                        for (String key : parameterMap.keySet()) {
                            jobMeta.setParameterValue(key, parameterMap.get(key));
                        }
                        for (String key : variableMap.keySet()) {
                            jobMeta.setVariable(key, variableMap.get(key));
                        }

                    } catch (UnknownParamException e) {
                        error(e.getMessage());
                    }
                    jobMeta.setArguments(arguments);
                } else {
                    return false;
                }
            }
        } else if (isDefinedResource(KettleComponent.TRANSFORMFILE)) {
            IActionSequenceResource transformResource = getResource(KettleComponent.TRANSFORMFILE);
            String fileAddress = getActualFileName(transformResource);

            try {
                if (fileAddress != null) { // We have an actual loadable
                    // filesystem and file
                    transMeta = new TransMeta(fileAddress, repository, true);
                    transMeta.setFilename(fileAddress);
                } else if (repository != null && repository.isConnected()) {

                    fileAddress = transformResource.getAddress();
                    // load transformation resource from kettle/settings.xml configured repository
                    transMeta = loadTransformFromRepository(FilenameUtils.getPathNoEndSeparator(fileAddress),
                            FilenameUtils.getBaseName(fileAddress), repository);
                } else {
                    String jobXmlStr = getResourceAsString(getResource(KettleComponent.TRANSFORMFILE));
                    jobXmlStr = jobXmlStr.replaceAll("\\$\\{pentaho.solutionpath\\}", solutionPath); //$NON-NLS-1$
                    jobXmlStr = jobXmlStr.replaceAll("\\%\\%pentaho.solutionpath\\%\\%", solutionPath); //$NON-NLS-1$
                    org.w3c.dom.Document doc = XmlW3CHelper.getDomFromString(jobXmlStr);
                    // create a tranformation from the document
                    transMeta = new TransMeta(doc.getFirstChild(), repository);
                }
            } catch (Exception e) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                        KettleComponent.TRANSFORMFILE, fileAddress), e);
                return false;
            }

            /*
             * Unreachable code below... if (transMeta == null) {
             * error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", KettleComponent.TRANSFORMFILE,
             * fileAddress)); //$NON-NLS-1$ debug(getKettleLog(true)); return false; }
             */

            // Don't forget to set the parameters here as well...
            try {
                for (String key : parameterMap.keySet()) {
                    transMeta.setParameterValue(key, parameterMap.get(key));
                }
                for (String key : variableMap.keySet()) {
                    transMeta.setVariable(key, variableMap.get(key));
                }

            } catch (UnknownParamException e) {
                error(e.getMessage());
            }
            transMeta.setArguments(arguments);
            /*
             * We do not need to concatenate the solutionPath info as the fileAddress has the complete location of the file
             * from start to end. This is to resolve BISERVER-502.
             */
            transMeta.setFilename(fileAddress);

        } else if (isDefinedResource(KettleComponent.JOBFILE)) {
            String fileAddress = ""; //$NON-NLS-1$
            try {
                fileAddress = getResource(KettleComponent.JOBFILE).getAddress();

                if (repository != null && repository.isConnected()) {

                    solutionPath = StringUtils.EMPTY;

                    // load job resource from kettle/settings.xml configured repository
                    jobMeta = loadJobFromRepository(FilenameUtils.getPathNoEndSeparator(fileAddress),
                            FilenameUtils.getBaseName(fileAddress), repository);

                } else {

                    String jobXmlStr = getResourceAsString(getResource(KettleComponent.JOBFILE));
                    // String jobXmlStr =
                    // XmlW3CHelper.getContentFromSolutionResource(fileAddress);
                    jobXmlStr = jobXmlStr.replaceAll("\\$\\{pentaho.solutionpath\\}", solutionPath); //$NON-NLS-1$
                    jobXmlStr = jobXmlStr.replaceAll("\\%\\%pentaho.solutionpath\\%\\%", solutionPath); //$NON-NLS-1$
                    org.w3c.dom.Document doc = XmlW3CHelper.getDomFromString(jobXmlStr);
                    if (doc == null) {
                        error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                                KettleComponent.JOBFILE, fileAddress));
                        debug(getKettleLog(true));
                        return false;
                    }
                    // create a job from the document
                    try {
                        repository = connectToRepository();
                        // if we get a valid repository its great, if not try it
                        // without

                        jobMeta = new JobMeta(solutionPath + fileAddress, repository);
                    } catch (Exception e) {
                        error(Messages.getInstance().getString("Kettle.ERROR_0023_NO_META"), e); //$NON-NLS-1$
                    } finally {
                        if (repository != null) {
                            if (ComponentBase.debug) {
                                debug(Messages.getInstance().getString("Kettle.DEBUG_DISCONNECTING")); //$NON-NLS-1$
                            }
                            repository.disconnect();
                        }
                    }
                }
            } catch (Exception e) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                        KettleComponent.JOBFILE, fileAddress), e);
                return false;
            }
            if (jobMeta == null) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                        KettleComponent.JOBFILE, fileAddress));
                debug(getKettleLog(true));
                return false;
            } else {
                try {
                    for (String key : parameterMap.keySet()) {
                        jobMeta.setParameterValue(key, parameterMap.get(key));
                    }
                    for (String key : variableMap.keySet()) {
                        jobMeta.setVariable(key, variableMap.get(key));
                    }

                } catch (UnknownParamException e) {
                    error(e.getMessage());
                }
                jobMeta.setArguments(arguments);
                jobMeta.setFilename(solutionPath + fileAddress);
            }

        }

        // OK, we have the information, let's load and execute the
        // transformation or job

        if (transMeta != null) {
            result = executeTransformation(transMeta);
        }
        if (jobMeta != null) {
            result = executeJob(jobMeta, repository);
        }

    } finally {

        if (repository != null) {
            if (ComponentBase.debug) {
                debug(Messages.getInstance().getString("Kettle.DEBUG_DISCONNECTING")); //$NON-NLS-1$
            }
            try {
                repository.disconnect();
            } catch (Exception ignored) {
                //ignore
            }
        }

        if (transMeta != null) {
            try {
                cleanLogChannel(transMeta);
                transMeta.clear();
            } catch (Exception ignored) {
                //ignore
            }
            transMeta = null;
        }
        if (jobMeta != null) {
            try {
                cleanLogChannel(jobMeta);
                jobMeta.clear();
            } catch (Exception ignored) {
                //ignored
            }
            // Can't do anything about an exception here.
            jobMeta = null;
        }
    }

    if (isDefinedOutput(EXECUTION_LOG_OUTPUT)) {
        setOutputValue(EXECUTION_LOG_OUTPUT, executionLog);
    }

    if (isDefinedOutput(EXECUTION_STATUS_OUTPUT)) {
        setOutputValue(EXECUTION_STATUS_OUTPUT, executionStatus);
    }

    XMLHandlerCache.getInstance().clear();
    return result;

}

From source file:org.pentaho.platform.plugin.kettle.PdiFileInfo.java

/**
 * Parses a PDI job or transformation file and returns an IFileInfo object
 * containing the name, description, and author.
 *///from   w w  w. j  ava  2 s .c o  m
@Override
public IFileInfo getFileInfo(ISolutionFile solutionFile, InputStream in) {
    try {

        String filename = solutionFile.getFileName();

        //FIXME: don't assume UTF-8
        String xml = IOUtils.toString(in, "UTF-8");

        // parse the document
        Document doc = XmlW3CHelper.getDomFromString(xml);
        Node root = doc.getFirstChild();

        if (filename.toLowerCase().endsWith(".ktr")) { //$NON-NLS-1$
            // handle a transformation
            // create a TransMeta from the document
            TransMeta transMeta = new TransMeta(root, null);
            // get the information we need
            IFileInfo info = new FileInfo();
            info.setAuthor(transMeta.getCreatedUser());
            info.setDescription(transMeta.getDescription());
            info.setDisplayType("pdi-transformation"); //$NON-NLS-1$
            info.setIcon(null);
            info.setTitle(transMeta.getName());
            // return the IFileInfo object
            return info;
        }
        if (filename.toLowerCase().endsWith(".kjb")) { //$NON-NLS-1$
            // handle a transformation
            // create a JobMeta from the document
            JobMeta jobMeta = new JobMeta(root, null, null);
            // get the information we need
            IFileInfo info = new FileInfo();
            info.setAuthor(jobMeta.getCreatedUser());
            info.setDescription(jobMeta.getDescription());
            info.setDisplayType("pdi-job"); //$NON-NLS-1$
            info.setIcon(null);
            info.setTitle(jobMeta.getName());
            // return the IFileInfo object
            return info;
        }

        return null;
    } catch (Exception e) {
        logger.error(Messages.getInstance().getErrorString("PdiFileInfo.ERROR_0001_PARSING_DOCUMENT",
                solutionFile.getFullPath()), e); //$NON-NLS-1
    }
    return null;
}

From source file:org.pentaho.pms.schema.security.SecurityService.java

/**
 * Contact the server and get back the content as XML
 * /*from  w  ww . j  ava2 s . c o  m*/
 * @return the requested security reference information
 * @throws Exception
 *           in case something goes awry
 */
public Node getContentFromServer(String urlToUse) throws PentahoMetadataException {

    String result = null;
    int status = -1;

    URL tempURL;
    try {

        // verify the URL is syntactically correct; we will use these pieces later in this method
        tempURL = new URL(urlToUse);

    } catch (MalformedURLException e) {

        String msg = Messages.getString("SecurityService.ERROR_0002_INVALID_URL", urlToUse, e.getMessage()); //$NON-NLS-1$
        log.logError(msg, e);
        throw new PentahoMetadataException(msg, e);

    }

    HttpClient client = new HttpClient();
    log.logDebug(Messages.getString("SecurityService.INFO_CONNECTING_TO_URL", urlToUse)); //$NON-NLS-1$

    // Assume we are using a proxy if proxyHostName is set?
    // TODO: Mod ui to include check for enable or disable proxy; rather than rely on proxyhostname (post v1)
    if ((proxyHostname != null) && (proxyHostname.trim().length() > 0)) {

        int port = (proxyPort == null) || (proxyPort.trim().length() == 0)
                ? client.getHostConfiguration().getPort()
                : Integer.parseInt(proxyPort);

        // TODO: Where to set nonProxyHosts?

        client.getHostConfiguration().setProxy(proxyHostname, port);

        // TODO: Credentials for proxy will be added if demand shows for it (post v1)
        // if (username != null && username.length() > 0) {
        // client.getState().setProxyCredentials(AuthScope.ANY,
        // new UsernamePasswordCredentials(username, password != null ? password : new String()));
        // }

    }

    // If server userid/password was supplied, use basic authentication to
    // authenticate with the server.
    if ((username != null) && (username.length() > 0) && (password != null) && (password.length() > 0)) {

        Credentials creds = new UsernamePasswordCredentials(username, password);
        client.getState().setCredentials(new AuthScope(tempURL.getHost(), tempURL.getPort()), creds);
        client.getParams().setAuthenticationPreemptive(true);

    }

    // Get a stream for the specified URL
    GetMethod getMethod = new GetMethod(urlToUse);
    try {

        status = client.executeMethod(getMethod);

        if (status == HttpStatus.SC_OK) {

            log.logDetailed(Messages.getString("SecurityService.INFO_START_READING_WEBSERVER_REPLY")); //$NON-NLS-1$
            result = getMethod.getResponseBodyAsString();

            log.logBasic(Messages.getString("SecurityService.INFO_FINISHED_READING_RESPONSE", //$NON-NLS-1$
                    Integer.toString(result.length())));

        } else if (status == HttpStatus.SC_UNAUTHORIZED) {

            String msg = Messages.getString("SecurityService.ERROR_0009_UNAUTHORIZED_ACCESS_TO_URL", urlToUse); //$NON-NLS-1$
            log.logError(msg);
            throw new PentahoMetadataException(msg);

        }

    } catch (HttpException e) {

        String msg = Messages.getString("SecurityService.ERROR_0003_CANT_SAVE_IO_ERROR", e.getMessage()); //$NON-NLS-1$
        log.logError(msg);
        log.logError(Const.getStackTracker(e));
        throw new PentahoMetadataException(msg, e);

    } catch (IOException e) {

        String msg = Messages.getString("SecurityService.ERROR_0004_ERROR_RETRIEVING_FILE_FROM_HTTP", //$NON-NLS-1$
                e.getMessage());
        // log.logError(toString(), msg);
        // log.logError(toString(), Const.getStackTracker(e));
        throw new PentahoMetadataException(msg, e);

    }

    if (result != null) {

        // Get the result back...
        Document doc;
        try {

            doc = XMLHandler.loadXMLString(result);

        } catch (KettleXMLException e) {

            String msg = Messages.getString("SecurityService.ERROR_0008_ERROR_PARSING_XML", e.getMessage()); //$NON-NLS-1$
            log.logError(msg);
            log.logError(Const.getStackTracker(e));
            throw new PentahoMetadataException(msg, e);

        }

        if (serviceURL.endsWith("ServiceAction")) {
            Node envelope = XMLHandler.getSubNode(doc, "SOAP-ENV:Envelope"); //$NON-NLS-1$
            if (envelope != null) {
                Node body = XMLHandler.getSubNode(envelope, "SOAP-ENV:Body"); //$NON-NLS-1$
                if (body != null) {
                    Node response = XMLHandler.getSubNode(body, "ExecuteActivityResponse"); //$NON-NLS-1$
                    if (response != null) {
                        Node content = XMLHandler.getSubNode(response, "content"); //$NON-NLS-1$
                        return content;
                    }
                }
            }
        } else {
            return doc.getFirstChild();
        }
    }
    return null;

}

From source file:org.primaresearch.web.gwt.server.UserServiceImpl.java

/**
 * Calls the integration web service and retrieves the relevant parameters for getting the document image, the
 * page content and the permissions.//from  w w w  .java2s . c o  m
 */
private WebServiceInfo getWebServiceInfo(String webServiceUrl, String userId, String attachmentId) {
    WebServiceInfo services = new WebServiceInfo();

    //Soap request
    try {
        SimpleSoapRequest request = new SimpleSoapRequest(webServiceUrl, "getDocumentAttachmentSources");
        request.addMethodParameter("Uid", userId);
        request.addMethodParameter("Aid", attachmentId);
        request.setDEBUG(DEBUG);

        String soapResponseContent = request.send();

        InputStream is = new ByteArrayInputStream(soapResponseContent.getBytes());

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

        Node root = doc.getFirstChild();
        if (root != null) {
            Node node = root.getFirstChild();
            while (node != null) {
                if ("DocumentAttachmentSources".equals(node.getNodeName())) {

                    Node param = node.getFirstChild();
                    while (param != null) {
                        if ("ImageSource".equals(param.getNodeName()))
                            services.imageWebService = param.getTextContent();
                        else if ("AttachmentSource".equals(param.getNodeName()))
                            services.pageContentWebService = param.getTextContent();

                        param = param.getNextSibling();
                    }
                    break;
                }
                node = node.getNextSibling();
            }
        }

        is.close();

    } catch (Exception exc) {
        exc.printStackTrace();
    }

    return services;
}

From source file:org.primaresearch.web.gwt.server.UserServiceImpl.java

/**
 * Calls the permission web service and retrieves the user permissions.
 *//*from   w  ww  .j  a v a  2s.c o m*/
private Permissions getPermissions(String webServiceUrl, String userId, String attachmentId) {

    ArrayList<String> permissionStrings = new ArrayList<String>();

    //Soap request
    try {
        SimpleSoapRequest request = new SimpleSoapRequest(webServiceUrl, "getDocumentAttachmentPermissions");
        request.addMethodParameter("Uid", userId);
        request.addMethodParameter("Aid", attachmentId);
        String soapResponseContent = request.send();

        InputStream is = new ByteArrayInputStream(soapResponseContent.getBytes());

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

        Node root = doc.getFirstChild();
        if (root != null) {
            Node node = root.getFirstChild();
            while (node != null) {
                if ("DocumentAttachmentPermissions".equals(node.getNodeName())) {

                    Node permission = node.getFirstChild();
                    while (permission != null) {

                        if ("Permission".equals(permission.getNodeName())) {
                            NamedNodeMap attrs = node.getAttributes();
                            if (attrs != null && attrs.getNamedItem("name") != null) {
                                Node attr = attrs.getNamedItem("name");
                                permissionStrings.add(attr.getNodeValue());
                            }
                        }
                        permission = permission.getNextSibling();
                    }
                }
                node = node.getNextSibling();
            }
        }
        is.close();

    } catch (Exception exc) {
        exc.printStackTrace();
        return null;
    }

    Permissions ret = new Permissions();
    ret.init(permissionStrings.toArray(new String[permissionStrings.size()]));

    return ret;
}