Appendchild from DocumentFragment
Hello:
I need help in understanding the issue with the code specifically documentfragment. On searching the forums, I could find an alternate way of getting the required result. However I am interested in understanding why my original code with DocumentFragment does not work. I am not able to understand why the Node created from DocumentFragment wont get added as Child in the main XML after I have imported it.
I am running this on 10g - version 10.2.0.4 database.
Orginal Code
DECLARE
l_xml DBMS_XMLDOM.DOMDocument;
l_tmp_xml DBMS_XMLDOM.DOMDocument;
l_root_node DBMS_XMLDOM.DOMNode;
l_curr_node DBMS_XMLDOM.DOMNode;
l_node DBMS_XMLDOM.DOMNode;
l_element DBMS_XMLDOM.DOMElement;
l_fragment DBMS_XMLDOM.DOMDocumentFragment;
l_cnt_req NUMBER := 0;
l_cnt_obj NUMBER := 0;
l_c CLOB;
l_buffer varchar2(4000);
elem DBMS_XMLDOM.DOMELEMENT;
BEGIN
l_xml := DBMS_XMLDOM.newDOMDocument();
DBMS_XMLDOM.setVersion(l_xml, '1.0');
DBMS_XMLDOM.setCharset(l_xml, 'windows-1251');
DBMS_XMLDOM.setStandalone(l_xml, 'yes');
l_element := DBMS_XMLDOM.createElement(l_xml, 'rde');
l_root_node := DBMS_XMLDOM.makeNode(l_element);
l_node := DBMS_XMLDOM.makeNode(l_xml);
l_node := DBMS_XMLDOM.appendChild(l_node, l_root_node);
l_element := DBMS_XMLDOM.createElement(l_xml, 'data');
l_node := DBMS_XMLDOM.makeNode(l_element);
l_root_node := DBMS_XMLDOM.appendChild(l_root_node, l_node);
FOR cur_req IN (
SELECT XMLELEMENT("PARTYADDRESSES",
XMLELEMENT("VOBASECOLLECTION",
XMLELEMENT("VOPartyAddress",
XMLFOREST(POVS.VENDOR_SITE_ID AS "PartyAddressId",
'Street' AS "AddressType",
POVS.CREATION_DATE AS "EffectDtFrom",
POVS.INACTIVE_DATE AS "EffectDtTo",
DECODE(POVS.INACTIVE_DATE,NULL,'TRUE','FALSE') AS "IsCurrent",
0 AS "UploadPackageId",
0 AS "UploadBatchId",
0 AS "AddressId",
POVS.ADDRESS_LINE1 ||' '||
POVS.ADDRESS_LINE2 ||' '||
POVS.ADDRESS_LINE3 AS "Street"),
XMLELEMENT("CityID", XMLATTRIBUTES('city' AS "location_type",
POVS.CITY AS "name",
POVS.STATE AS "owner_id")),
XMLELEMENT("ZipCode",POVS.ZIP),
XMLELEMENT("CountryRegionID",XMLATTRIBUTES('Country' AS "location_type",
'United States' AS "name",
'The World' As "Owner_id"))))).GetClobVal() AS PartyAddressesXML
FROM PO_VENDORS POV,
PO_VENDOR_SITES_ALL POVS
WHERE POV.VENDOR_ID = POVS.VENDOR_ID
AND POVS.VENDOR_SITE_ID = 2385298)
LOOP
l_tmp_xml := DBMS_XMLDOM.newDOMDocument(cur_req.PartyAddressesXML);
l_fragment := DBMS_XMLDOM.createDocumentFragment(l_tmp_xml);
l_curr_node := DBMS_XMLDOM.makeNode(l_fragment);
DBMS_XMLDOM.WRITETOBUFFER(l_tmp_xml,l_buffer);
dbms_output.put_line(l_buffer);
l_curr_node := DBMS_XMLDOM.IMPORTNODE(l_xml,l_curr_node,TRUE);
l_curr_node := DBMS_XMLDOM.APPENDCHILD(l_node, l_curr_node);
DBMS_XMLDOM.freeDocument(l_tmp_xml);
END LOOP; --FOR cur_req
DBMS_XMLDOM.WRITETOBUFFER(l_xml,l_buffer);
dbms_output.put_line(l_buffer);
END;
Output
<PARTYADDRESSES><VOBASECOLLECTION><VOPartyAddress><PartyAddressId>2385298</PartyAddressId><AddressType>Street</AddressType><EffectDtFrom>2009-11-21</EffectDtFrom><IsCurrent>TRUE</IsCurrent><UploadPackageId>0</UploadPackageId><UploadBatchId>0</UploadBatchId><AddressId>0</AddressId><Street>PO BOX 6685 </Street><CityID location_type="city" name="GREENVILLE" owner_id="SC"></CityID><ZipCode>29606</ZipCode><CountryRegionID location_type="Country" name="United States" Owner_id="The World"></CountryRegionID></VOPartyAddress></VOBASECOLLECTION></PARTYADDRESSES>
<?xml version="1.0" standalone='yes'?>
<rde>
<data/>
</rde>
Code that gives Required Output
DECLARE
l_xml DBMS_XMLDOM.DOMDocument;
l_tmp_xml DBMS_XMLDOM.DOMDocument;
l_root_node DBMS_XMLDOM.DOMNode;
l_curr_node DBMS_XMLDOM.DOMNode;
l_node DBMS_XMLDOM.DOMNode;
l_worknode DBMS_XMLDOM.DOMNode;
l_add_node DBMS_XMLDOM.DOMNode;
l_element DBMS_XMLDOM.DOMElement;
l_fragment DBMS_XMLDOM.DOMDocumentFragment;
l_cnt_req NUMBER := 0;
l_cnt_obj NUMBER := 0;
l_c CLOB;
l_buffer varchar2(4000);
elem DBMS_XMLDOM.DOMELEMENT;
BEGIN
l_xml := DBMS_XMLDOM.newDOMDocument();
DBMS_XMLDOM.setVersion(l_xml, '1.0');
DBMS_XMLDOM.setCharset(l_xml, 'windows-1251');
DBMS_XMLDOM.setStandalone(l_xml, 'yes');
l_element := DBMS_XMLDOM.createElement(l_xml, 'rde');
l_root_node := DBMS_XMLDOM.makeNode(l_element);
l_node := DBMS_XMLDOM.makeNode(l_xml);
l_node := DBMS_XMLDOM.appendChild(l_node, l_root_node);
l_element := DBMS_XMLDOM.createElement(l_xml, 'data');
l_node := DBMS_XMLDOM.makeNode(l_element);
l_root_node := DBMS_XMLDOM.appendChild(l_root_node, l_node);
FOR cur_req IN (
SELECT XMLELEMENT("PARTYADDRESSES",
XMLELEMENT("VOBASECOLLECTION",
XMLELEMENT("VOPartyAddress",
XMLFOREST(POVS.VENDOR_SITE_ID AS "PartyAddressId",
'Street' AS "AddressType",
POVS.CREATION_DATE AS "EffectDtFrom",
POVS.INACTIVE_DATE AS "EffectDtTo",
DECODE(POVS.INACTIVE_DATE,NULL,'TRUE','FALSE') AS "IsCurrent",
0 AS "UploadPackageId",
0 AS "UploadBatchId",
0 AS "AddressId",
POVS.ADDRESS_LINE1 ||' '||
POVS.ADDRESS_LINE2 ||' '||
POVS.ADDRESS_LINE3 AS "Street"),
XMLELEMENT("CityID", XMLATTRIBUTES('city' AS "location_type",
POVS.CITY AS "name",
POVS.STATE AS "owner_id")),
XMLELEMENT("ZipCode",POVS.ZIP),
XMLELEMENT("CountryRegionID",XMLATTRIBUTES('Country' AS "location_type",
'United States' AS "name",
'The World' As "Owner_id"))))).GetClobVal() AS PartyAddressesXML
FROM PO_VENDORS POV,
PO_VENDOR_SITES_ALL POVS
WHERE POV.VENDOR_ID = POVS.VENDOR_ID
AND POVS.VENDOR_SITE_ID = 2385298)
LOOP
l_tmp_xml := DBMS_XMLDOM.newDOMDocument(cur_req.PartyAddressesXML);
l_curr_node := dbms_xmldom.makeNode(dbms_xmldom.getDocumentElement(l_tmp_xml));
l_curr_node := DBMS_XMLDOM.IMPORTNODE(l_xml,l_curr_node,true);
l_curr_node := DBMS_XMLDOM.APPENDCHILD(l_node, l_curr_node);
DBMS_XMLDOM.freeDocument(l_tmp_xml);
END LOOP; --FOR cur_req
DBMS_XMLDOM.WRITETOBUFFER(l_xml,l_buffer);
dbms_output.put_line(l_buffer);
DBMS_XMLDOM.freeDocument(l_xml);
Exception
When others then
dbms_output.put_line (sqlerrm);
END;
Desired Output
<?xml version="1.0" standalone='yes'?>
<rde>
<data>
<PARTYADDRESSES>
<VOBASECOLLECTION>
<VOPartyAddress>
<PartyAddressId>2385298</PartyAddressId>
<AddressType>Street</AddressType>
<EffectDtFrom>2009-11-21</EffectDtFrom>
<IsCurrent>TRUE</IsCurrent>
<UploadPackageId>0</UploadPackageId>
<UploadBatchId>0</UploadBatchId>
<AddressId>0</AddressId>
<Street>PO BOX 6685 </Street>
<CityID location_type="city" name="GREENVILLE" owner_id="SC"/>
<ZipCode>29606</ZipCode>
<CountryRegionID location_type="Country" name="United States" Owner_id="The World"/>
</VOPartyAddress>
</VOBASECOLLECTION>
</PARTYADDRESSES>
</data>
</rde>
A DocumentFragment is a 'minimal' Document object.
Similar Messages
-
How to get document from documentfragment
hi,
I tried the xsl Sample Code from Oracle XDK,
The Output is a documentfragment.
How can I build a domdocument out of that documentfragment?
Sorry about the short description, but I think XML Gurus
know what I mean ;-).
Thanks
DeltevA DocumentFragment is a 'minimal' Document object.
-
Third question - Using parameters in powershell recovery - Alert description
Hi guys,
With help i created powershell recovery in a management pack. Once again thanks very much, this is new to me. Now i know these parameters (variables):
http://blogs.technet.com/b/kevinholman/archive/2009/09/23/alert-notification-subscription-variables-and-linking-that-to-the-console-database-and-sdk.aspx
But how can i implement this in this XML? I think i must declare them in the XML, because when i put the variable there, it doesn't work. I would like to get the alert description in the message variable (see xml below)
</Recovery>
<Recovery ID="MomUIGenaratedRecovery28e1547022254ccbb82784c60d51b1d2" Accessibility="Public" Enabled="true" Target="Type603f92b7b83945598af55495615db953" Monitor="UIGeneratedMonitor0cd347f57f3949deb958cebb02d25555" ResetMonitor="false" ExecuteOnState="Error" Remotable="true" Timeout="300">
<Category>Custom</Category>
<WriteAction ID="MomUIGenaratedModule75df98fbfc5b48e39fd605cccd97d29b" TypeID="Windows!Microsoft.Windows.PowerShellWriteAction">
<ScriptName>sendSMS.ps1</ScriptName>
<ScriptBody>
# function SendSMS
# PowerShell function to send SMS messages via the CM SMS Gateway.
function SendSMS{
param([string]$url, [int]$customer, [string]$login, [string]$password, [string]$recipient, [string]$sender,[string]$reference)
$xml = New-Object XML
$messages = $xml.CreateElement("MESSAGES")
$customerxml = $xml.CreateElement("CUSTOMER")
$customerxml.SetAttribute("ID", $customer)
$messages.AppendChild($customerxml)|Out-Null
$user = $xml.CreateElement("USER")
$user.SetAttribute("LOGIN", $login)
$user.SetAttribute("PASSWORD", $password)
$messages.AppendChild($user) |Out-Null
if (!($reference.Equals(''))) {
$refxml = $xml.CreateElement("REFERENCE")
$refxml.Innertext = $reference
$messages.AppendChild($refxml) |Out-Null
$tariff = $xml.CreateElement("TARIFF")
$tariff.InnerText = 0
$messages.AppendChild($tariff) |Out-Null
$msg = $xml.CreateElement("MSG")
$from = $xml.CreateElement("FROM")
$from.InnerText = $sender
$msg.AppendChild($from) |Out-Null
$to = $xml.CreateElement("TO")
$to.InnerText = $recipient
$msg.AppendChild($to) |Out-Null
$body = $xml.CreateElement("BODY")
$body.SetAttribute("TYPE", "TEXT")
$body.InnerText = $message
$msg.AppendChild($body) |Out-Null
$messages.AppendChild($msg) |Out-Null
$xml.AppendChild($messages) |Out-Null
Write-Output $xml.OuterXml
$webClient = New-Object net.WebClient
return ($webClient.UploadString($url, $xml.OuterXml))
# test
SendSMS -url 'https://website.sms.nl/webservice.ashx' -recipient 0031612345678 -customer 1 -login 1 -password 'password' -sender 'Standby' -message 'Here i want the alert description' -reference '1234'
</ScriptBody>
<TimeoutSeconds>60</TimeoutSeconds>
</WriteAction>
Kind regards,
AndréParameters are defined between ScriptBody and TimeoutSeconds like this:
<Parameters>
<Parameter>
<Name>param1</Name>
<Value>$Config/param1$</Value>
</Parameter>
<Parameter>
<Name>param2</Name>
<Value>$Config/param2$</Value>
</Parameter>
</Parameters
This information is available on MSDN.
Jonathan Almquist | SCOMskills, LLC (http://scomskills.com) -
Hi experts
when I run Network UI Element
to presnt org Chart
I get in IE->Tools->Java Console
the follow error:
<<<--- Applet.destroy(): AppWin0/JNET --->>>
<<<--- EXIT for AppWin0/JNET --->>>
java.lang.NullPointerException
at sun.plugin.javascript.ocx.JSObject.eval(Unknown Source)
at com.sap.tc.webdynpro.ace.Acf2JavaScriptClient$1.run(Acf2JavaScriptClient.java:55)
at java.lang.Thread.run(Unknown Source)
ACF 7.1000.0.71
<<< frog.jar: version 5.4.6 02/01/06 sap.theme: null >>>this is the file:
// This file has been generated partially by the Web Dynpro Code Generator.
// MODIFY CODE ONLY IN SECTIONS ENCLOSED BY @@begin AND @@end.
// ALL OTHER CHANGES WILL BE LOST IF THE FILE IS REGENERATED.
package co.il.bnhp;
// IMPORTANT NOTE:
// ALL IMPORT STATEMENTS MUST BE PLACED IN THE FOLLOWING SECTION ENCLOSED
// BY @@begin imports AND @@end. FURTHERMORE, THIS SECTION MUST ALWAYS CONTAIN
// AT LEAST ONE IMPORT STATEMENT (E.G. THAT FOR IPrivateOrgTree).
// OTHERWISE, USING THE ECLIPSE FUNCTION "Organize Imports" FOLLOWED BY
// A WEB DYNPRO CODE GENERATION (E.G. PROJECT BUILD) WILL RESULT IN THE LOSS
// OF IMPORT STATEMENTS.
//@@begin imports
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Entity;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import co.i.bnhp.model.Zhr_Rfc_Disp_Manger_Employees2_Input;
import co.il.bnhp.wdp.IPrivateOrgTree;
import co.il.bnhp.wdp.IPublicOrgTree;
import com.sap.tc.webdynpro.modelimpl.dynamicrfc.WDDynamicRFCExecuteException;
import com.sap.tc.webdynpro.progmodel.api.WDResourceFactory;
import com.sap.tc.webdynpro.services.sal.deployment.api.WDAliasResolvingException;
import com.sap.tc.webdynpro.services.sal.url.api.WDURLGenerator;
import com.sap.tc.webdynpro.services.sal.url.api.WDWebResource;
import com.sap.tc.webdynpro.services.sal.url.api.WDWebResourceType;
//@@end
//@@begin documentation
//@@end
public class OrgTree
Logging location.
private static final com.sap.tc.logging.Location logger =
com.sap.tc.logging.Location.getLocation(OrgTree.class);
static
//@@begin id
String id = "$Id$";
//@@end
com.sap.tc.logging.Location.getLocation("ID.com.sap.tc.webdynpro").infoT(id);
Private access to the generated Web Dynpro counterpart
for this controller class. </p>
Use <code>wdThis</code> to gain typed access to the context,
to trigger navigation via outbound plugs, to get and enable/disable
actions, fire declared events, and access used controllers and/or
component usages.
@see co.il.bnhp.wdp.IPrivateOrgTree for more details
private final IPrivateOrgTree wdThis;
Root node of this controller's context. </p>
Provides typed access not only to the elements of the root node
but also to all nodes in the context (methods node<i>XYZ</i>())
and their currently selected element (methods current<i>XYZ</i>Element()).
It also facilitates the creation of new elements for all nodes
(methods create<i>XYZ</i>Element()). </p>
@see co.il.bnhp.wdp.IPrivateOrgTree.IContextNode for more details.
private final IPrivateOrgTree.IContextNode wdContext;
A shortcut for <code>wdThis.wdGetAPI()</code>. </p>
Represents the generic API of the generic Web Dynpro counterpart
for this controller. </p>
private final com.sap.tc.webdynpro.progmodel.api.IWDComponent wdControllerAPI;
A shortcut for <code>wdThis.wdGetAPI().getComponent()</code>. </p>
Represents the generic API of the Web Dynpro component this controller
belongs to. Can be used to access the message manager, the window manager,
to add/remove event handlers and so on. </p>
private final com.sap.tc.webdynpro.progmodel.api.IWDComponent wdComponentAPI;
public OrgTree(IPrivateOrgTree wdThis)
this.wdThis = wdThis;
this.wdContext = wdThis.wdGetContext();
this.wdControllerAPI = wdThis.wdGetAPI();
this.wdComponentAPI = wdThis.wdGetAPI().getComponent();
//@@begin javadoc:wdDoInit()
/** Hook method called to initialize controller. */
//@@end
public void wdDoInit()
//@@begin wdDoInit()
buildDOM();
//@@end
//@@begin javadoc:wdDoExit()
/** Hook method called to clean up controller. */
//@@end
public void wdDoExit()
//@@begin wdDoExit()
//@@end
//@@begin javadoc:wdDoPostProcessing()
Hook called to handle data retrieval errors before rendering.
After doModifyView(), the Web Dynpro Framework gets all context data needed
for rendering by validating the contexts (which in turn calls the supply
functions and supplying relation roles). In this hook, the application
should handle the errors which occurred during validation of the contexts.
Using preorder depth-first traversal, this hook is called for all component
controllers starting with the current root component.
Permitted operations:
- Flushing model queue
- Creating messages
- Reading context and model data
Forbidden operations:
- Invalidating model data
- Manipulating the context
- Firing outbound plugs
- Creating components
@param isCurrentRoot true if this is the root of the current request
//@@end
public void wdDoPostProcessing(boolean isCurrentRoot)
//@@begin wdDoPostProcessing()
//@@end
//@@begin javadoc:wdDoBeforeNavigation()
Hook before the navigation phase starts.
This hook allows you to flush the model queue and handle any
errors that occur. Firing outbound plugs is allowed in this hook.
Using preorder depth-first traversal, this hook is called for all component
controllers starting with the current root component.
@param isCurrentRoot true if this is the root of the current request
//@@end
public void wdDoBeforeNavigation(boolean isCurrentRoot)
//@@begin wdDoBeforeNavigation()
//@@end
//@@begin javadoc:wdDoApplicationStateChange()
Hook that informs the application about a state change.
<p>
This hook is called e.g. to tell the application that will be
<ul>
<li>left via a suspend plug and therefore should go into a suspend/sleep
mode with minimal need of resources. errors that occur. Firing
outbound plugs is allowed in this hook.
<li>left due to a timeout and could write it's state to a data base if the
user comes back later on
</ul>
The concrete reason is available via IWDApplicationStateChangeInfo
<p>
<b>Important</b>: This hook is called for the top level component only!
@param stateChangeInfo contains the information about the nature of the state change
@param stateChangeReturn allows the application to ask for a different state change.
The framework is allowed to ignore it considering i.e. the current resources situation.
//@@end
public void wdDoApplicationStateChange(com.sap.tc.webdynpro.progmodel.api.IWDApplicationStateChangeInfo stateChangeInfo, com.sap.tc.webdynpro.progmodel.api.IWDApplicationStateChangeReturn stateChangeReturn)
//@@begin wdDoApplicationStateChange()
//@@end
//@@begin javadoc:buildDOM()
/** Declared method. */
//@@end
public void buildDOM( )
//@@begin buildDOM()
// File fileName = new File ("orgchart.xml");
wdThis.wdGetEmpUserIdInterface().getemp();
wdContext.currentContextElement().setPernrRet(wdContext.currentContextElement().getPernrRet());
Zhr_Rfc_Disp_Manger_Employees2_Input input = new co.i.bnhp.model.Zhr_Rfc_Disp_Manger_Employees2_Input();
wdContext.nodeZhr_Rfc_Disp_Manger_Employees2_Input().bind(input);
input.setP_Pernr("1511");
//input.setP_Pernr(wdContext.currentContextElement().getPernrRet());
try{
String xmlFile =WDURLGenerator.getResourcePath(wdComponentAPI.getDeployableObjectPart(), "//tmp//tipex.xml");
File file = new File(xmlFile);
//Creating an empty XML Document
//We need a Document
input.execute();
wdContext.nodeSource().invalidate();
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
// DOMImplementation impl = docBuilder.getDOMImplementation();
Document doc = docBuilder.newDocument();
//Creating the XML tree
Element SapJNETData = doc.createElement("SAPJNetData");
SapJNETData.setAttribute("version","1.0");
doc.appendChild(SapJNETData);
// Element typeRepository = doc.createElement("TypeRepository");
// typeRepository.setAttribute("href","
tmp
TypeRepository.xml");
// SapJNETData.appendChild(typeRepository);
Element typeRepository = doc.createElement("TypeRepository");
typeRepository.setAttribute("id","orgchart");
typeRepository.setAttribute("version","1.0");
SapJNETData.appendChild(typeRepository);
Element color = doc.createElement("COLOR");
typeRepository.appendChild(color);
Element type1 = doc.createElement("type");
type1.setAttribute("name","OCBlue");
Element rgb1 = doc.createElement("rgb");
Text textRGB1 = doc.createTextNode("0,0,128");
color.appendChild(type1);
rgb1.appendChild(textRGB1);
type1.appendChild(rgb1);
Element type2 = doc.createElement("type");
type2.setAttribute("name","OCGray");
Element rgb2 = doc.createElement("rgb");
Text textRGB2 = doc.createTextNode("215,220,216");
color.appendChild(type2);
rgb2.appendChild(textRGB2);
type2.appendChild(rgb2);
Element type3 = doc.createElement("type");
type3.setAttribute("name","OCGrayer");
Element rgb3 = doc.createElement("rgb");
Text textRGB3 = doc.createTextNode("195,200,196");
color.appendChild(type3);
rgb3.appendChild(textRGB3);
type3.appendChild(rgb3);
Element type4 = doc.createElement("type");
type4.setAttribute("name","OCLighter");
Element rgb4 = doc.createElement("rgb");
Text textRGB4 = doc.createTextNode("235,240,236");
color.appendChild(type4);
rgb4.appendChild(textRGB4);
type4.appendChild(rgb4);
Element layout = doc.createElement("LAYOUT");
typeRepository.appendChild(layout);
Element typeLayout = doc.createElement("type");
typeLayout.setAttribute("name","OCLayout");
Element style = doc.createElement("style");
Text textStyle = doc.createTextNode("VERTICAL_FLOW");
layout.appendChild(typeLayout);
typeLayout.appendChild(style);
style.appendChild(textStyle);
Element label = doc.createElement("LABEL");
typeRepository.appendChild(label);
Element typeLabel1 = doc.createElement("type");
typeLabel1.setAttribute("name","OCLabelBase");
Element colorLabel = doc.createElement("color");
colorLabel.setAttribute("type","Black");
Element font1 = doc.createElement("font");
Element size1 = doc.createElement("size");
Text textSize1 = doc.createTextNode("12");
Element multiLine =doc.createElement("multiLine");
Text textMultiLine=doc.createTextNode("TRUE");
Element hAlign = doc.createElement("halign");
Text textHalign = doc.createTextNode("CENTER");
Element hAlignText = doc.createElement("halignText");
Text textHalignText = doc.createTextNode("CENTER");
Element border1 = doc.createElement("border");
Element insets1 = doc.createElement("insets");
insets1.setAttribute("top","3");
Element typeLabel2 = doc.createElement("type");
typeLabel2.setAttribute("name","OCLabelOrgUnit");
typeLabel2.setAttribute("inherits","OCLabelBase");
Element colorLabel2 = doc.createElement("color");
colorLabel2.setAttribute("type","OCBlue");
Element fillColorLabel2 = doc.createElement("fillColor");
fillColorLabel2.setAttribute("type","OCGrayer");
Element font2 = doc.createElement("font");
Element style2 = doc.createElement("style");
Text textStyle2 = doc.createTextNode("BOLD");
Element border2 = doc.createElement("border");
Element thickness = doc.createElement("thickness");
Text textThickness = doc.createTextNode("1");
Element Side = doc.createElement("sides");
Text textSide = doc.createTextNode("SOUTH");
Element typeLabel3 = doc.createElement("type");
typeLabel3.setAttribute("name","OCLabelNumber");
typeLabel3.setAttribute("inherits","OCLabelBase");
Element colorLabel3 = doc.createElement("color");
colorLabel3.setAttribute("type","OCBlue");
Element size3 = doc.createElement("size");
Text textSize3 = doc.createTextNode("40,0");
Element halign3 = doc.createElement("halign");
Text textHalign3 = doc.createTextNode("RIGHT");
Element multiLine3 = doc.createElement("multiline");
Text textMultiLine3 = doc.createTextNode("FALSE");
Element border3 = doc.createElement("border");
Element Thickness3 = doc.createElement("thickness");
Text textThickness3 = doc.createTextNode("1");
Element insets3 = doc.createElement("insets");
insets3.setAttribute("top","0");
Element Sides3 = doc.createElement("sides");
Text textSides3 = doc.createTextNode("NORTH,WEST");
Element typeLabel4 = doc.createElement("type");
typeLabel4.setAttribute("name","OCLabelChief");
typeLabel4.setAttribute("inherits","OCLabelBase");
Element font4 = doc.createElement("font");
Element style4 = doc.createElement("style");
Element border4 = doc.createElement("border");
Element insets4 = doc.createElement("insets");
insets4.setAttribute("top","6");
Element edgeT = doc.createElement("EDGE");
Element typeEdge= doc.createElement("type");
typeEdge.setAttribute("name","OCLink");
Element Shape = doc.createElement("shape");
Element ThickNess =doc.createElement("thickness");
Element targetDeco = doc.createElement("targetdeco");
targetDeco.setAttribute("shape","NONE");
Element nodeT = doc.createElement("NODE");
Element typeNode = doc.createElement("type");
typeNode.setAttribute("name","OCNodeBase");
Element shape = doc.createElement("shape");
shape.setAttribute("type","Box");
Element fillColor = doc.createElement("fillColor");
fillColor.setAttribute("type","OCGray");
Element borderNode = doc.createElement("border");
Element styleNode = doc.createElement("style");
Element plugs = doc.createElement("plugs");
plugs.setAttribute("min","0");
plugs.setAttribute("position","SOUTH");
plugs.setAttribute("positionMode","CENTRIC");
Element socket = doc.createElement("sockets");
socket.setAttribute("min","0");
socket.setAttribute("position","NORTH");
socket.setAttribute("positionMode","CENTRIC");
Element OCNode = doc.createElement("type");
OCNode.setAttribute("name","OCNode");
OCNode.setAttribute("inherits","OCNodeBase");
Element OCNodeShape = doc.createElement("shape");
Element OCNodeSize = doc.createElement("size");
OCNodeSize.setAttribute("pack","true");
Element OClayout = doc.createElement("layout");
OClayout.setAttribute("type","OCLayout");
Element OCNodeArrowUp = doc.createElement("type");
OCNodeArrowUp.setAttribute("name","OCNodeArrowUp");
OCNodeArrowUp.setAttribute("inherits","OCNodeBase");
Element OCNodeArrowShape = doc.createElement("shape");
Element OcNodeArrowSize = doc.createElement("size");
Element OcNodeArrowLabel = doc.createElement("label");
Element OcNodeArrowicon = doc.createElement("icon");
Element OcNodeArrowHalign = doc.createElement("halign");
Element OCNodeArrowDown = doc.createElement("type");
OCNodeArrowDown.setAttribute("name","OCNodeArrowDown");
OCNodeArrowDown.setAttribute("inherits","OCNodeArrowUp");
Element OCNodeArrowDownLabel = doc.createElement("label");
Element OcNodeArrowDownIcon = doc.createElement("icon");
Element NodeGraph = doc.createElement("Graph");
Element OCGraph = doc.createElement("type");
OCGraph.setAttribute("name","OCGraph");
Element direction = doc.createElement("direction");
Element components = doc.createElement("components");
Element OCGraphLayouts = doc.createElement("layouts");
Element types = doc.createElement("types");
Element OCGraphlayout = doc.createElement("layout");
OCGraphlayout.setAttribute("type","TREE");
Element property1 = doc.createElement("property");
property1.setAttribute("name","STYLE");
property1.setAttribute("value","VARIABLE_SIZE");
Element property2 = doc.createElement("property");
property2.setAttribute("name","OFFS_X");
property2.setAttribute("value","50");
Element property3 = doc.createElement("property");
property3.setAttribute("name","OFFS_Y");
property3.setAttribute("value","30");
Element Graph = doc.createElement("Graph");
Graph.setAttribute("type","OCGraph");
Graph.setAttribute("version","1.0");
Element layouts = doc.createElement("layouts");
layouts.setAttribute("onLoad","TREE");
Element view = doc.createElement("view");
Element grid = doc.createElement("grid");
Text TextGrid = doc.createTextNode("80,80");
Element UserInterface = doc.createElement("userInterface");
UserInterface.setAttribute("version","1.0");
Element mode = doc.createElement("mode");
label.appendChild(typeLabel1);
typeLabel1.appendChild(colorLabel);
typeLabel1.appendChild(font1);
font1.appendChild(size1);
size1.appendChild(textSize1);
typeLabel1.appendChild(multiLine);
multiLine.appendChild(textMultiLine);
typeLabel1.appendChild(hAlign);
hAlign.appendChild(textHalign);
typeLabel1.appendChild(hAlignText);
hAlignText.appendChild(textHalignText);
typeLabel1.appendChild(border1);
border1.appendChild(insets1);
label.appendChild(typeLabel2);
typeLabel2.appendChild(colorLabel2);
typeLabel2.appendChild(fillColorLabel2);
typeLabel2.appendChild(font2);
font2.appendChild(style2);
style2.appendChild(textStyle2);
typeLabel2.appendChild(border2);
border2.appendChild(thickness);
thickness.appendChild(textThickness);
border2.appendChild(Side);
Side.appendChild(textSide);
label.appendChild(typeLabel4);
typeLabel4.appendChild(font4);
font4.appendChild(style4);
style4.appendChild(doc.createTextNode("BOLD"));
typeLabel4.appendChild(border4);
border4.appendChild(insets4);
label.appendChild(typeLabel3);
typeLabel3.appendChild(colorLabel3);
typeLabel3.appendChild(size3);
size3.appendChild(textSize3);
typeLabel3.appendChild(halign3);
halign3.appendChild(textHalign3);
typeLabel3.appendChild(multiLine3);
multiLine3.appendChild(textMultiLine3);
typeLabel3.appendChild(border3);
border3.appendChild(Thickness3);
Thickness3.appendChild(textThickness3);
border3.appendChild(insets3);
insets3.setAttribute("top","0");
border3.appendChild(Sides3);
Sides3.appendChild(textSides3);
typeRepository.appendChild(edgeT);
edgeT.appendChild(typeEdge);
typeEdge.appendChild(Shape);
Shape.appendChild(doc.createTextNode("BENT"));
typeEdge.appendChild(ThickNess);
ThickNess.appendChild(doc.createTextNode("1"));
typeEdge.appendChild(targetDeco);
typeRepository.appendChild(nodeT);
nodeT.appendChild(typeNode);
typeNode.appendChild(shape);
shape.appendChild(fillColor);
shape.appendChild(borderNode);
borderNode.appendChild(styleNode);
styleNode.appendChild(doc.createTextNode("RAISED"));
typeNode.appendChild(plugs);
typeNode.appendChild(socket);
nodeT.appendChild(OCNode);
OCNode.appendChild(OCNodeShape);
OCNodeShape.appendChild(OCNodeSize);
OCNodeSize.appendChild(doc.createTextNode("150,0"));
OCNode.appendChild(OClayout);
nodeT.appendChild(OCNodeArrowUp);
OCNodeArrowUp.appendChild(OCNodeArrowShape);
OCNodeArrowShape.appendChild(OcNodeArrowSize);
OcNodeArrowSize.appendChild(doc.createTextNode("22,21"));
OCNodeArrowUp.appendChild(OcNodeArrowLabel);
OcNodeArrowLabel.appendChild(OcNodeArrowicon);
OcNodeArrowicon.appendChild(doc.createTextNode("apps/orgchart/arrow-up.gif"));
OcNodeArrowLabel.appendChild(OcNodeArrowHalign);
OcNodeArrowHalign.appendChild(doc.createTextNode("CENTER"));
nodeT.appendChild(OCNodeArrowDown);
OCNodeArrowDown.appendChild(OCNodeArrowDownLabel);
OCNodeArrowDownLabel.appendChild(OcNodeArrowDownIcon);
OcNodeArrowDownIcon.appendChild(doc.createTextNode("apps/orgchart/arrow-down.gif"));
typeRepository.appendChild(NodeGraph);
NodeGraph.appendChild(OCGraph);
OCGraph.appendChild(direction);
direction.appendChild(doc.createTextNode("TOP_BOTTOM"));
OCGraph.appendChild(components);
components.appendChild(doc.createTextNode("OCNode"));
OCGraph.appendChild(OCGraphLayouts);
OCGraphLayouts.appendChild(types);
types.appendChild(doc.createTextNode("TREE"));
OCGraphLayouts.appendChild(OCGraphlayout);
OCGraphlayout.appendChild(property1);
OCGraphlayout.appendChild(property2);
OCGraphlayout.appendChild(property3);
SapJNETData.appendChild(UserInterface);
UserInterface.appendChild(mode);
mode.appendChild(doc.createTextNode("SELECTONLY"));
SapJNETData.appendChild(Graph);
Graph.appendChild(layouts);
Graph.appendChild(view);
view.appendChild(grid);
grid.appendChild(TextGrid);
for (int i=0; i<wdContext.nodeZhr_Rfc_Employees2().size(); i++) {
IPublicOrgTree.IEmpElement Emp = wdContext.nodeEmp().createEmpElement();
IPublicOrgTree.IZhr_Rfc_Employees2Element curEmp = wdContext.nodeZhr_Rfc_Employees2().getZhr_Rfc_Employees2ElementAt(i);
Element node = doc.createElement("node");
node.setAttribute("id",curEmp.getEmp_Pernr());
node.setAttribute("type","OCNode");
Element label1 = doc.createElement("label");
label1.setAttribute("type","OCLabelOrgUnit");
Text TextLabel1 = doc.createTextNode(curEmp.getEmp_Name());
Element label2 = doc.createElement("label");
label2.setAttribute("type","OCLabelChief");
Text TextLabel2 = doc.createTextNode(curEmp.getEmp_Pernr());
Graph.appendChild(node);
node.appendChild(label1);
label1.appendChild(TextLabel1);
node.appendChild(label2);
label2.appendChild(TextLabel2);
wdContext.nodeEmp().addElement(Emp);
for (int i=0; i<wdContext.nodeZhr_Rfc_Employees2().size()-1; i++) {
IPublicOrgTree.IEmpElement Emp = wdContext.nodeEmp().createEmpElement();
IPublicOrgTree.IZhr_Rfc_Employees2Element curEmp = wdContext.nodeZhr_Rfc_Employees2().getZhr_Rfc_Employees2ElementAt(i);
for (int j=i1; j<wdContext.nodeZhr_Rfc_Employees2().size(); j+)
if (wdContext.nodeZhr_Rfc_Employees2().getZhr_Rfc_Employees2ElementAt(i).getEmp_Pernr().equals(wdContext.nodeZhr_Rfc_Employees2().getZhr_Rfc_Employees2ElementAt(j).getEmp_Manager()))
Element edge = doc.createElement("edge");
edge.setAttribute("type","OCLink");
Element from = doc.createElement("from");
from.setAttribute("node",curEmp.getEmp_Pernr());
Element to = doc.createElement("to");
to.setAttribute("node",wdContext.nodeZhr_Rfc_Employees2().getZhr_Rfc_Employees2ElementAt(j).getEmp_Pernr());
Graph.appendChild(edge);
edge.appendChild(from);
edge.appendChild(to);
// typeLabel3.appendChild()
// Element font = doc.createElement("font");
// .appendChild(color);
// type1.appendChild(rgb1);
//create a comment and put it in the root element
// Comment comment = doc.createComment("Just a thought");
// type1.appendChild(comment);
//create child element, add an attribute, and add to root
// Element child = doc.createElement("child");
//child.setAttribute("name", "value");
//type.appendChild(child);
//add a text element to the child
//Output the XML
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-8");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(file);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
wdContext.currentContextElement().setXmlString(sw.toString());
} catch (DOMException e) {
wdComponentAPI.getMessageManager().reportException("2-"+e.getMessage(),true);
} catch (TransformerConfigurationException e) {
-
Second queston using powershell in SCOM as recovery
Hi guys,
In a previous question i needed some ideas about using powershell in a recovery.
Now i've implemented this in the XML, but it gives me this error as i import my managementpack back in SCOM 2012 R2 UR 2
Error, it gives the error on Microsoft.Windows.PowerShellWriteAction too:
If any management packs in the Import list are dependent on this management pack, the installation of the dependent management packs will fail.
Cannot resolve identifier Windows!Microsoft.Windows.PowerShellWriteAction in the context of management pack ANWB.Informatica.Powercenter0. Unknown alias: Windows.
<Recovery ID="MomUIGenaratedRecovery7187d8e283b44c9c9a115f06af5d3dcc" Accessibility="Public" Enabled="true" Target="Type603f92b7b83945598af55495615db953" Monitor="UIGeneratedMonitor0cd347f57f3949deb958cebb02d25555" ResetMonitor="false" ExecuteOnState="Error" Remotable="true" Timeout="300">
<Category>Custom</Category>
<WriteAction ID="MomUIGenaratedModule8ea82cdaccd8404b810409334cc50e47" TypeID="Windows!Microsoft.Windows.PowerShellWriteAction">
<ScriptName>SendSMS-XMLPOST.ps1</ScriptName>
<Arguments />
<ScriptBody>function SendSMS{
param([string]$url, [int]$customer, [string]$login, [string]$password, [string]$recipient, [string]$sender, [string]$message, [string]$reference)
$xml = New-Object XML
$messages = $xml.CreateElement("MESSAGES")Vladimir,
Thanks for your response.
Ofcourse i can. Here you got my XML. These are my changes to the XML:
In the typedefenitions -> moduletypes:
<ModuleTypes>
<!-- ABO ADDED code 18-07-2014 -->
<WriteActionModuleType ID="Microsoft.Windows.PowerShellWriteAction" Accessibility="Public" Batching="false">
<Configuration>
<IncludeSchemaTypes>
<SchemaType>Microsoft.Windows.PowerShellSchema</SchemaType>
</IncludeSchemaTypes>
<xsd:element name="ScriptName" type="NonNullString" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="ScriptBody" type="NonNullString" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="SnapIns" type="SnapInsType" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="Parameters" type="NamedParametersType" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="TimeoutSeconds" type="xsd:integer" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="StrictErrorHandling" type="xsd:boolean" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="SerializationDepth" type="xsd:integer" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
</Configuration>
<OverrideableParameters>
<OverrideableParameter ID="TimeoutSeconds" Selector="$Config/TimeoutSeconds$" ParameterType="int" />
</OverrideableParameters>
<ModuleImplementation Isolation="Any">
<Composite>
<MemberModules>
<WriteAction ID="PowerShellWriteAction" TypeID="Microsoft.Windows.PowerShellWriteActionBase">
<ScriptName>$Config/ScriptName$</ScriptName>
<ScriptBody>$Config/ScriptBody$</ScriptBody>
<SnapIns>$Config/SnapIns$</SnapIns>
<Parameters>$Config/Parameters$</Parameters>
<TimeoutSeconds>$Config/TimeoutSeconds$</TimeoutSeconds>
<OutputType>SerializedObjectData_OpsMgrSerialization</OutputType>
<StrictErrorHandling>$Config/StrictErrorHandling$</StrictErrorHandling>
<SerializationDepth>$Config/SerializationDepth$</SerializationDepth>
</WriteAction>
</MemberModules>
<Composition>
<Node ID="PowerShellWriteAction" />
</Composition>
</Composite>
</ModuleImplementation>
<OutputType>Microsoft.Windows.SerializedObjectData</OutputType>
<InputType>System!System.BaseData</InputType>
</WriteActionModuleType>
<WriteActionModuleType ID="Microsoft.Windows.PowerShellWriteActionBase" Accessibility="Internal" Batching="false">
<Configuration>
<IncludeSchemaTypes>
<SchemaType>Microsoft.Windows.PowerShellSchema</SchemaType>
</IncludeSchemaTypes>
<xsd:element name="ScriptName" type="NonNullString" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="ScriptBody" type="NonNullString" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="SnapIns" type="SnapInsType" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="Parameters" type="NamedParametersType" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="TimeoutSeconds" type="xsd:integer" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="OutputType" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="SerializedObjectData_OpsMgrSerialization" />
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="StrictErrorHandling" type="xsd:boolean" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<xsd:element name="SerializationDepth" type="xsd:integer" minOccurs="0" maxOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
</Configuration>
<ModuleImplementation Isolation="Any">
<Managed>
<Assembly>Microsoft.EnterpriseManagement.Modules.PowerShell, Culture="", PublicKeyToken="31bf3856ad364e35", Version="6.0.4900.0"</Assembly>
<Type>Microsoft.EnterpriseManagement.Modules.PowerShell.PowerShellProbeActionModule</Type>
</Managed>
</ModuleImplementation>
<OutputType>Microsoft.Windows.SerializedObjectData</OutputType>
<InputType>System!System.BaseData</InputType>
</WriteActionModuleType>
</ModuleTypes>
<!-- ABO ADDED code 18-07-2014 -->
And in the monitor recovery:
<!-- ABO ADDED code 18-07-2014 -->
<Recovery ID="MomUIGenaratedRecovery7187d8e283b44c9c9a115f06af5d3dcc" Accessibility="Public" Enabled="true" Target="MPAuthoring.PowerShellScript.ServiceTarget" Monitor="MPAuthoring.PowerShellScript.ServiceMonitor" ResetMonitor="false" ExecuteOnState="Warning" Remotable="true" Timeout="300">
<Category>Custom</Category>
<WriteAction ID="ServiceRestartScriptWriteAction" TypeID="Windows!Microsoft.Windows.PowerShellWriteAction">
<ScriptName>SendSMS-XMLPOST.ps1</ScriptName>
<Arguments />
<ScriptBody>function SendSMS{
param([string]$url, [int]$customer, [string]$login, [string]$password, [string]$recipient, [string]$sender, [string]$message, [string]$reference)
$xml = New-Object XML
$messages = $xml.CreateElement("MESSAGES")
$customerxml = $xml.CreateElement("CUSTOMER")
$customerxml.SetAttribute("ID", $customer)
$messages.AppendChild($customerxml)|Out-Null
$user = $xml.CreateElement("USER")
$user.SetAttribute("LOGIN", $login)
$user.SetAttribute("PASSWORD", $password)
$messages.AppendChild($user) |Out-Null
if (!($reference.Equals(''))) {
$refxml = $xml.CreateElement("REFERENCE")
$refxml.Innertext = $reference
$messages.AppendChild($refxml) |Out-Null
$tariff = $xml.CreateElement("TARIFF")
$tariff.InnerText = 0
$messages.AppendChild($tariff) |Out-Null
$msg = $xml.CreateElement("MSG")
$from = $xml.CreateElement("FROM")
$from.InnerText = $sender
$msg.AppendChild($from) |Out-Null
$to = $xml.CreateElement("TO")
$to.InnerText = $recipient
$msg.AppendChild($to) |Out-Null
$body = $xml.CreateElement("BODY")
$body.SetAttribute("TYPE", "TEXT")
$body.InnerText = $message
$msg.AppendChild($body) |Out-Null
$messages.AppendChild($msg) |Out-Null
$xml.AppendChild($messages) |Out-Null
Write-Output $xml.OuterXml
$webClient = New-Object net.WebClient
return ($webClient.UploadString($url, $xml.OuterXml))
# test
SendSMS -url 'https://sms.nl/' -recipient 0031123456789 -customer 1 -login 1 -password 'password' -sender 'Standby' -message 'Test' -reference '1234'</ScriptBody>
<!-- ABO ADDED code 18-07-2014 --> -
Here follows a series of questions regarding the misterious fuctionaly of org.w3c.xml and javax.xml.parsers packages that I couldn't answer.
I'd appreciate someone could clarify these aspects to me:
1) How is it possible to create a Document, and together with it any Node extended objects, if these ones are all interfaces?
2) How can methods like createElement, getElementByTagName (from class Document), appendChild (from class Node), etc work if nobody has ever implemented them?
3) Where is the abstract method newDocument() of class javax.xml.parsers.DocumentBuilder implemented?
If a method returns a reference declared of type interface that reference should refer to an object of a class that implemets that interface but here no class implements the interface Document. Furthermore the method newDocument is declared to be abstract, so how is it possible?The Sun JAXP stuff includes "reference
implementations". If you don't make any
special requests via properties or requesting
specific properties, you will get Sun's reference
implementation. For portability reasons, if
Sun's implementations do what you want,
then use them! I have a problem with that
because Shema Language namespaces don't
seem to be fully implemented (I'm still
digging into that).
The API's explain 2 ways to request alternate
implementations, via namespace/URL and by
capability. For the latter, there must be some
way to tell the builder that additional
implementations are available and what their
capabilities are. First method is probably far
easier. -
Applying an XSLT against results from XSU in Java Stored Procedure
Is there an easy way to have a Java Stored Procedure apply an XSLT against the results of an OracleXMLQuery? The only examples I can find are with regular Java code outside the database.
I'm running 9.2.0.2 on Windows 2000 Server.This is what I use:
(I have table called params where I have stored encodinf, XSL, and stuff like that)
DOMParser parser;
XMLDocument xml, xsldoc, outXML;
URL xslURL;
URL xmlURL;
Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rset= stmt.executeQuery("select xsl_varchar2,encoding,version,host,port,host_path,usrnm,passwrd from params");
rset.next();
String strXSL=rset.getString(1); //This is XSL transformation
String strEncoding=rset.getString(2);
String strVersion=rset.getString(3);
rset.close();
stmt.close();
parser = new DOMParser();
parser.setPreserveWhitespace(true);
StringReader rXSL= new StringReader(strXSL);
xslURL=createURL("test");
parser.parse(rXSL);
xsldoc=parser.getDocument();
OracleXMLQuery qry = new OracleXMLQuery(conn, "select * from somewhere");
xml=(XMLDocument) qry.getXMLDOM();
// instantiate a stylesheet
XSLStylesheet xsl = new XSLStylesheet(xsldoc, xslURL);
XSLProcessor processor = new XSLProcessor();
// display any warnings that may occur
processor.showWarnings(true);
processor.setErrorStream(System.err);
// Process XSL
DocumentFragment result = processor.processXSL(xsl, xml);
// create an output document to hold the result
outXML = new XMLDocument();
outXML.setVersion(strVersion);
outXML.setEncoding(strEncoding);
outXML.appendChild(result);
outXML is your XML. -
Generate Valid XML from pl/sql
Hi,
A new-bee here. I want to know how to generate a valid xml document. I have a schema which by the way includes two other schemas. This is the code I am using but I don't know how to make sure that I insert the child nodes in the right sequence. Any sample code that you guys can provide would be greatly appreciated.
FUNCTION GenerateOrderXML(
o_ErrorCode OUT NUMBER,
o_ErrorText OUT VARCHAR2,
i_AccountID IN document.documentid%TYPE,
i_OrderName IN VARCHAR2) RETURN XMLType
IS
v_Doc XMLDOM.DOMDocument;
v_MainNode XMLDOM.DOMNode;
v_RootElmt XMLDOM.DOMElement;
v_RootNode XMLDOM.DOMNode;
v_TmpCLOB CLOB := ' ';
CURSOR CURSOR_SERVOBJ
IS
SELECT XMLTAG, XMLVALUE FROM SERVICEOBJECT
WHERE SERVICEOBJECT.ID < 500
ORDER BY SEQUENCE;
-- Create xml root element
v_Doc := XMLDOM.newDOMDocument;
v_MainNode := XMLDOM.makeNode(v_Doc);
v_RootElmt := XMLDOM.createElement(v_Doc, 'OrderRequest');
v_RootNode := XMLDOM.appendChild(v_MainNode, XMLDOM.makeNode(v_RootElmt));
-- Add OrderName, OrderType
AddChild(v_Doc, v_RootNode, 'orderName', i_OrderName);
AddChild(v_Doc, v_RootNode, 'orderType', 'NA');
-- Add all attributes
FOR v_NameValue IN CURSOR_SERVOBJ
LOOP
AddChild(v_Doc, v_RootNode, v_NameValue.XMLTAG, v_NameValue.XMLVALUE);
END LOOP;
-- XMLDOM.writeToBuffer(v_Doc, v_Buffer);
XMLDOM.writeToClob(v_Doc, v_TmpCLOB);
o_ErrorCode := 0;
RETURN XMLType.createXML(v_TmpClob);
END;The r was a typo. The messge is correct.
Here is another problem I am having. I can't import a schema that includes another schema. When I try to register the third schema I get the following error. The first two register without any errors and when I run this
select schema_url from user_xml_schemas;
I see
http://www.bbc.com/XMLSchema/sfi.xsd
http://www.bbc.com/XMLSchema/ProductModel.xsd
So why is my third schema not importing? Can you point me to any good documentation/tutorials on XML DB.
Note: Thank you for your help so far.
ERROR at line 1:
ORA-31000: Resource 'ProductModel.xsd' is not an XDB schema document
ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 0
ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 26
ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 131
ORA-06512: at line 6
1st Schema Heading
<xsd:schema xmlns="http://www.bbc.com/XMLSchema/bfi.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.bbc.com/XMLSchema/bfi.xsd" elementFormDefault="qualified">
2nd Schema Heading
<xsd:schema xmlns="http://www.bbc.com/XMLSchema/ProductModel.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.bbc.com/XMLSchema/ProductModel.xsd" elementFormDefault="qualified">
3rd Schema Heading
<xsd:schema xmlns="http://www.bbc.com/XMLSchema/ResourceOrder.xsd" xmlns:qb="http://www.bbc.com/XMLSchema/ProductModel.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.bbc.com/XMLSchema/ResourceOrder.xsd" elementFormDefault="qualified">
<xsd:import namespace="http://www.bbc.com/XMLSchema/ProductModel.xsd" schemaLocation="ProductModel.xsd"/> -
How to get distinct values from a list and display in a ListView webpart.
Hi,
I have a requirement in which I need to pull unique/distinct values from a custom list and then display it via a listview webpart. Can any one suggest how this can be done.
If possible please share the CAMEL query to fetch distinct values from a custom list.
Thanks,
AnkitHi Ankit,
Is there any particular reason that the values need to be shown in a list view web part? Are you going to use that web part for filtering via web part connections?
I ask because the enterprise site collection features include the SharePoint List Filter web part, which may accomplish what you're looking for.
If you just need to display the values in a grid view, you might have more luck with the JavaScript Client Object Model. Try putting the following in a text file:
<style>
.CustomTableClass{display:table;table-layout:fixed}
.CustomRowClass{display:table-row;}
</style>
<div id="distinct_values_div" class="CustomTableClass">
<img src="/_layouts/loading.gif" />
</div>
<script language="JavaScript" type="text/JavaScript">
var siteUrl = '/sitecollection/web'; //use the actual subsite URL here
var listName = 'mylist'; // use the actual list name here
var field = "Title" // use the actual field you want to display here
var divToUpdate = document.getElementById("distinct_values_div");
var rowClass = "CustomRowClass";
ExecuteOrDelayUntilScriptLoaded(function(){
var clientContext = new SP.ClientContext(siteUrl);
var web = clientContext.get_web();
var lists = web.get_lists();
var list = lists.getByTitle(listName);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query></Query><RowLimit>500</RowLimit></View>');
this.collListItem = list.getItems(camlQuery);
clientContext.load(collListItem,"Include ("+field+")");
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));
},"sp.js");
function onQueryFailed(sender, args){
divToUpdate.innerHTML = 'Unable to retrieve values: '+args.get_message());
function onQuerySucceeded(sender, args){
var allValues = [];
var listItemEnumerator = collListItem.getEnumerator();
divToUpdate.innerHTML = "";
while(listItemEnumerator.moveNext()){
var listItem = listItemEnumerator.get_current();
if(!containsString(allValues,listItem.get_item(field)){
var value = listItem.get_item(field);
allValues.push(value);
var newDiv = document.createElement("div");
newDiv.className = rowClass;
newDiv.innerHTML = value;
divToUpdate.appendChild(newDiv);
function containsString(strArray, text){
var contains = false;
for (var i=0; i<strArray.length; i++){
if(strArray[i]==text){contains = true; break;}
return contains;
</script>
Upload the text file to a library on the site, then add a content editor web part to a page where you want the distinct values to appear. In the content editor web part's properties, edit the Content Link so that it links directly to the text file. This
will cause the JavaScript to run on the page. -
I've discovered some very strange behaviour in Excel which seems to be contrary to that documented in the Open Office XML specification (OOXML). I couldn't find a way to report bugs against Excel, so I thought I'd try to explain the issue here.
In short it seems that Excel is removing, and incorrectly re-indexing the metadata I programatically associate with cells.
First, a summary of the relevant parts of the specification:
From OOXML 18.9: There are two types of metadata: "cell metadata" and "value metadata".
Cell metadata follows the cell as it moves. Value metadata follows the value through formulae etc.
From OOXML 18.3.1.4: The c (cell) element has cm and vm attributes which are both documented as "The zero-based index of the [cell|value] metadata...in the Metadata Part"
From OOXML 18.9.17: The valueMetadata is "a collection of block element that each define the value metadata for a particular cell". "Cells in the workbook index into this collection".
The valueMetadata contains bk elements which in turn contain rc (metadata record) elements
From OOXML 18.9.15: rc elements have t (type index) and v (value index) attributes. t is a 1-based index into metadataTypes and v is a 0-based index into the futureMetadata element which matches the name of the metadata type.
Here's an example of what this might look like:
<c vm="0"> <!-- vm points to the first bk inside valueMetadata below -->
<x:valueMetadata>
<x:bk>
<x:rc t="1" v="0" /> <!-- t points to the first metadataType below. v points to the first bk in the futureMetadata below (whose name matches the metadataType to which t points) -->
</x:bk>
</x:valueMetadata>
<x:metadataTypes>
<x:metadataType name="MyMetaType" ... /> <!-- name dictates which futureMetadata valueMetadata's v attribute indexes into -->
</x:metadataTypes>
<x:futureMetadata name="MyMetaType" ...>
<x:bk>
<x:extLst>
<x:ext xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main" uri="http://example.com/extension" p5:value="test value" xmlns:p5="http://example.com/extension" />
</x:extLst>
</x:bk>
</x:futureMetadata>
The Problem
From what I can tell, for values of n > 2, if you associate n cells with metadata, Excel will drop the last piece of metadata, and the one at index 1, and it will do so silently. The indices are then 0..n-3, and the association for all but the first (0
index) will be wrong. This renders the future metadata totally useless.
For n == 1, Excel just removes the last piece of metadata (index 1). If we try 1-based indexes for the vm attribute on the c element, we get different behaviour. This may not be relevant as it is contrary to the specification, but the slightly better behaviour
might indicate an off-by-one error:
n
Deleted Indices (0-based) when using 0-based indices
Deleted Indices (0-based) when using 1-based indices
1
0
None
2
1
1
3
1,2
1
4
1,3
1
5
1,4
1
6
1,5
1
Demonstrating the Problem
I have some example code[1] that demonstrates the problem. You will need a file called test.xlsx with cells A1..C2 populated.
Compile the source as AddMetadata.exe then run with the test file as the only parameter:
> AddMetadata.exe test.xlsx
You can look at test.xlsx in Excel, Visual Studio (with the Open XML Package Editor Power Tool for Visual Studio 2010) or the Open XML SDK 2.0 Productivity Tool for Microsoft Office. Looking at the file before and after running AddMetadata.exe you should
be able to reproduce the behaviour documented above.
Summary
It would be good to know if this is really an Excel bug or whether we're doing something wrong / unsupported. Any insight would be very much appreciated.
[1] The Example code:
namespace AddMetadata
using System;
using System.Linq;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
public class Program
// The cells to associate with metadata
private readonly static CellSpec[] CellSpecs = new[]
new CellSpec{ Sheet = "Sheet1", Column = "A", Row = 1 },
new CellSpec{ Sheet = "Sheet1", Column = "B", Row = 1 },
new CellSpec{ Sheet = "Sheet1", Column = "C", Row = 1 },
new CellSpec{ Sheet = "Sheet1", Column = "A", Row = 2 },
new CellSpec{ Sheet = "Sheet1", Column = "B", Row = 2 },
new CellSpec{ Sheet = "Sheet1", Column = "C", Row = 2 },
private static readonly uint NumCells = (uint)CellSpecs.Length;
private const string SPREADSHEET_ML_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
private const string METADATA_TYPE_NAME = "MyMetaType";
private const string EXTENSION_URI = "http://example.com/extension";
public static void Main(string[] args)
if (args.Length != 1)
Console.Out.WriteLine("AddMetadata <doc.xslx>");
Console.Out.WriteLine(" Adds metadata to the specified document to demonstate some strange Excel behaviour");
Environment.Exit(1);
try
var doc = SpreadsheetDocument.Open(args[0], true);
StripMetadata(doc);
AddMetadata(doc);
AddMetadataType(doc);
AddFutureMetadata(doc);
AddMetadataRecords(doc);
AssociateCellsWithMetadata(doc);
doc.WorkbookPart.Workbook.Save();
doc.Close();
catch(Exception e)
Console.Out.WriteLine(e);
/// <summary>
/// Strip any existing metadata.
/// </summary>
/// <param name="doc">The document</param>
private static void StripMetadata(SpreadsheetDocument doc)
var wbPart = doc.WorkbookPart;
var cellMetadataPart = wbPart.GetPartsOfType<CellMetadataPart>().FirstOrDefault();
wbPart.DeletePart(cellMetadataPart);
/// <summary>
/// Add basic metadata part structure.
/// </summary>
/// <param name="doc">The document</param>
private static void AddMetadata(SpreadsheetDocument doc)
doc.WorkbookPart.AddNewPart<CellMetadataPart>();
doc.WorkbookPart.CellMetadataPart.Metadata = new Metadata { MetadataTypes = new MetadataTypes() };
/// <summary>
/// Add the metadata type used by all the metadata we're adding
/// </summary>
/// <param name="doc"></param>
private static void AddMetadataType(SpreadsheetDocument doc)
var metadata = doc.WorkbookPart.CellMetadataPart.Metadata;
var metadataType = new MetadataType
Name = METADATA_TYPE_NAME,
Assign = false,
CellMeta = false,
ClearContents = false,
ClearAll = false,
ClearComments = true,
ClearFormats = true,
Coerce = false,
Copy = true,
Delete = false,
Edit = true,
Merge = true,
MinSupportedVersion = 0U,
PasteAll = true,
PasteBorders = false,
PasteColWidths = false,
PasteComments = false,
PasteDataValidation = false,
PasteFormats = false,
PasteFormulas = false,
PasteNumberFormats = false,
PasteValues = true,
RowColumnShift = true,
SplitAll = false,
SplitFirst = false
metadata.MetadataTypes.AppendChild(metadataType);
/// <summary>
/// Add future metadata blocks which contain the actual metadata for each cell.
/// They are referenced by the metadata records.
/// </summary>
/// <param name="doc">The document</param>
private static void AddFutureMetadata(SpreadsheetDocument doc)
var metadata = doc.WorkbookPart.CellMetadataPart.Metadata;
var futureMetadata = metadata.AppendChild(new FutureMetadata());
futureMetadata.Name = METADATA_TYPE_NAME;
futureMetadata.Count = NumCells;
// Future metadata area
for (var i = 0; i < NumCells; i++)
// The metadata for each cell will be single FutureMetadataBlock containing an extension list with a single extension.
FutureMetadataBlock futureMetadataBlock = futureMetadata.AppendChild(new FutureMetadataBlock());
ExtensionList extLst = futureMetadataBlock.AppendChild(new ExtensionList());
Extension ext = extLst.AppendChild(new Extension());
ext.Uri = EXTENSION_URI;
ext.AddNamespaceDeclaration("x", SPREADSHEET_ML_NS);
ext.SetAttribute(new OpenXmlAttribute("value", ext.Uri, string.Format("test value {0}", i)));
/// <summary>
/// Add metadata records which point to each future metadata block.
/// They are in turn referenced by the cells.
/// </summary>
/// <param name="doc">The document</param>
private static void AddMetadataRecords(SpreadsheetDocument doc)
var metadata = doc.WorkbookPart.CellMetadataPart.Metadata;
// Value metadata area
ValueMetadata valueMetadata = metadata.AppendChild(new ValueMetadata());
for (uint i = 0; i < NumCells; i++)
// Type is 1-indexed, index into future metadata is 0-indexed
var metadataBlock = valueMetadata.AppendChild(new MetadataBlock());
var metadataRecord = metadataBlock.AppendChild(new MetadataRecord());
metadataRecord.Val = i;
metadataRecord.TypeIndex = (uint)1;
/// <summary>
/// Associate existing cells with existing metadata.
/// </summary>
/// <param name="doc">The document</param>
private static void AssociateCellsWithMetadata(SpreadsheetDocument doc)
for (uint i = 0; i < CellSpecs.Length; i++)
var cellSpec = CellSpecs[i];
var cell = GetCell(doc, cellSpec.Sheet, cellSpec.Column, cellSpec.Row);
if (cell == null)
throw new ArgumentException(string.Format("Cell {0} not found in row {1} of sheet {2}", cellSpec.Column, cellSpec.Row, cellSpec.Sheet));
cell.ValueMetaIndex = i;
/// <summary>
/// Get a cell given the document, sheet name, column name and row index.
/// </summary>
/// <param name="doc">The document</param>
/// <param name="sheetName">The sheet name</param>
/// <param name="columnName">The column name</param>
/// <param name="rowIndex">The row index</param>
/// <returns>The cell</returns>
private static Cell GetCell(SpreadsheetDocument doc, String sheetName, String columnName, uint rowIndex)
var row = GetRow(doc, sheetName, rowIndex);
if (row == null)
throw new ArgumentException(string.Format("Row '{0}' not found", rowIndex));
return row.Elements<Cell>().Where(c => c.CellReference.Value.StartsWith(columnName)).FirstOrDefault();
/// <summary>
/// Get a worksheet part by sheet name.
/// </summary>
/// <param name="document">The document</param>
/// <param name="name">The sheet name</param>
/// <returns>The worksheet part</returns>
private static WorksheetPart GetWorksheetPartByName(SpreadsheetDocument document, string name)
// Get Sheet by name from Sheets in Workbook
var sheet = document.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where(x => x.Name == name).FirstOrDefault();
// Lookup WorksheetPart by Id
return sheet == null ? null : (WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id.Value);
/// <summary>
/// Get a row given the document, sheet name and row index.
/// </summary>
/// <param name="doc">The document</param>
/// <param name="sheetName">The sheet name</param>
/// <param name="rowIndex">The row index</param>
/// <returns>The row</returns>
private static Row GetRow(SpreadsheetDocument doc, String sheetName, uint rowIndex)
var worksheetPart = GetWorksheetPartByName(doc, sheetName);
if (worksheetPart == null)
throw new ArgumentException(string.Format("Sheet '{0}' not found", sheetName));
return worksheetPart.Worksheet.GetFirstChild<SheetData>().Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
struct CellSpec
public string Sheet;
public string Column;
public uint Row;If you create a metadatatype with a single metdata block, and you reference that in your vm/cm cell attribute using a *one* based index, Excel seems to see the link and it honors it when saving the spreadsheet.
So, I ended up with something like:
<c ... cm="1"/> (I'm dealing with cell metadata, but the concept is equivalente to value metadata)
<metadataTypes count="1">
<metadataType name="MyMetaType" .../>
</metadataTypes>
<futureMetadata count="1" name="MyMetaType">
<bk>
<extLst><ext
uri="http://example" xmlns:x="http://example"><x:val>87</x:val></ext></extLst>
</bk>
</futureMetadata>
<cellMetadata count="1">
<bk><rc
t="1" v="0"/></bk> <!-- this is what gets referenced as cm=1 on the cell -->
</cellMetadata>
Hope this helps. -
Reading text from server socket stream
I have a basic cd input program i've been trying to figure out the following problem for a while now, the user enters the artist and title etc and then a DOM (XML) file is created in memory this is then sent to the server. The server then echos back the results which is later printed on a html page by reading the replys from the server line by line.
The server must be run it listens for clients connecting the clients connect and send DOM documents through the following jsp code.
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<%@page import="javax.xml.parsers.*"%>
<%@page import="org.w3c.dom.*"%>
<%@page import="org.apache.xml.serialize.*"%>
<%!
public static final String serverHost = "cdserver";
public static final int serverPort = 10151;
%>
<hr />
<pre>
<%
Socket mySocket = null; // socket object
PrintWriter sockOut = null; // to send data to the socket
BufferedReader sockIn = null; // to receive data from the socket
try {
// #1 add line that creates a client socket
mySocket = new Socket(serverHost, serverPort);
// #2 add lines that create input and output streams
// attached to the socket you just created
sockOut = new PrintWriter(mySocket.getOutputStream(), true);
sockIn = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
} catch (UnknownHostException e) {
throw e; // This time the JSP can handle the exception, not us
} catch (IOException e) {
throw e; // This time the JSP can handle the exception, not us
String cdTitle, cdArtist, track1Title, track1Time, track1Rating;
// Retrieve the HTML form field values
cdTitle = request.getParameter("cdtitle");
cdArtist = request.getParameter("cdartist");
track1Title = request.getParameter("track1title");
track1Time = request.getParameter("track1time");
track1Rating = request.getParameter("track1rating");
// Create a new DOM factory, and from that a new DOM builder object
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// Note that we are creating a new (empty) document
Document document = builder.newDocument();
// The root element of our document wil be <cd>
// It gets stored as the child node of the whole document (it is the root)
Element rootElement = document.createElement("cd");
document.appendChild(rootElement);
// Create an element for the CD title called <title>
Element cdTitleElement = document.createElement("title");
// Add a text code under the <title> element with the value that
// the user entered into the title field of the web form (cdTitle)
cdTitleElement.appendChild(document.createTextNode(cdTitle));
// Place the <title> element underneath the <cd> element in the tree
rootElement.appendChild(cdTitleElement);
// Create an <artist> element with the form data, place underneath <cd>
Element cdArtistElement = document.createElement("artist");
cdArtistElement.appendChild(document.createTextNode(cdArtist));
rootElement.appendChild(cdArtistElement);
// Create a <tracklist> element and place it underneath <cd> in the tree
// Note that it has no text node associated with it (it not a leaf node)
Element trackListElement = document.createElement("tracklist");
rootElement.appendChild(trackListElement);
// In this example we only have one track, so it is not necessary to
// use a loop (in fact it is quite silly)
// But the code below is included to demonstrate how you could loop
// through and add a set of different tracks one by one if you
// needed to (although you would need to have the track data already
// stored in an array or a java.util.Vector or similar
int numTracks = 1;
for (int i=0; i<numTracks; i++) {
String trackNum = Integer.toString(i+1);
Element trackElement = document.createElement("track");
trackElement.setAttribute("id", trackNum);
trackListElement.appendChild(trackElement);
// Track title element called <title>, placed underneath <track>
Element trackTitleElement = document.createElement("title");
trackTitleElement.appendChild(document.createTextNode(track1Title));
trackElement.appendChild(trackTitleElement);
// Track time element called <time>, placed underneath <track>
Element trackTimeElement = document.createElement("time");
trackTimeElement.appendChild(document.createTextNode(track1Time));
trackElement.appendChild(trackTimeElement);
// Track rating element called <rating>, placed underneath <track>
Element trackRatingElement = document.createElement("rating");
trackRatingElement.appendChild(document.createTextNode(track1Rating));
trackElement.appendChild(trackRatingElement);
OutputFormat format = new OutputFormat();
format.setIndenting(true);
// Create a new XMLSerializer that will be used to write out the XML
// This time we will serialize it to the socket
// #3 change this line so that it serializes to the socket,
// not to the "out" object
XMLSerializer serializer = new XMLSerializer(writer, format);
serializer.serialize(document);
// Print out a message to indicate the end of the data, and
// flush the stream so all the data gets sent now
sockOut.println("<!--QUIT-->");
sockOut.flush();
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
#4 add a while loop that reads text from the
server socket input stream, line by line, and prints
it out to the web page, using out.println(...);
Note that because the reply from the server will contain
XML, you will need to call upon the toHTMLString() method
defined below to escape the < and > symbols so that they
will display correctly in the web browser.
Also note that as you receive the reply back from the
server, you should look out for the special <!--QUIT-->
string that will indicate when there is no more data
to receive.
while ((fromServer = sockIn.readLine()) != null) {
out.println(sockIn.readLine());
// If the reply from the server said "QUIT", exit from the
// while loop by using a break statement.
if (fromServer.equals("QUIT")) {
out.println("Connection closed - good bye ...");
// Print the text from the server out to the user's screen
out.println("Reply from Server: " + fromServer);
// Now read a line of text from the keyboard (typed by user)
fromUser = stdIn.readLine();
// If it wasn't null, print it out to the screen, and also
// print a copy of it out to the socket
if (fromUser != null) {
out.println("Client: " + fromUser);
sockOut.println(fromUser);
// Close all the streams we have open, and then close the socket
sockOut.close();
sockIn.close();
mySocket.close();
%>
I'm suppose to modify the commented sections labled with #.
#1,2 are correct but i have doubts on the 3rd and 4th modification.
for #3 i changed so i serializes to the socket not to the "out" object:
from
XMLSerializer serializer = new XMLSerializer(out, format);
to
XMLSerializer serializer = new XMLSerializer(writer, format);
with "out" it prints out some of the results entered but it just hangs i'm thinking it might be the while loop that i added in #4. If i changed it to serialize the socket XMLSerializer serializer = new XMLSerializer(writer, format); it doesn't print out nothing at all; just a blank screen where it hangs.
I can post the rest of the code (server thats in java and cdinput.html) but since i want to keep my post short and if required i'll post it later on i also omitted some of the code where it creates the DOM textnodes etc to keep my post short.On your previous thread, why did you say the server was using http POST and application/xml content type when it quite obviously isn't, but a direct socket communication that abuses XML comments for message end delimiters?
The comments imply you need to wait for "<!--QUIT-->" on a line by itself, but your loop is waiting for "QUIT".
Pete -
OBIEE integrated to Mapviewer , need advice from expert people in my codes
<!--[if !mso]>
<style>
v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style>
<![endif]--><!--[if gte mso 9]><xml>
Normal
0
false
false
false
MicrosoftInternetExplorer4
</xml><![endif]--><!--[if gte mso 9]><xml>
</xml><![endif]--><!--[if !mso]>
<object
classid="clsid:38481807-CA0E-42D2-BF39-B33AF135CC4D" id=ieooui>
</object>
<style>
st1\:*{behavior:url(#ieooui) }
</style>
<![endif]-->
<!--[if gte mso 10]>
<style>
/* Style Definitions */
table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;}
</style>
<![endif]-->
Based on Example : [http://www.oracle.com/technology/products/mapviewer/pdf/mapviewer_obiee.pdf|blocked::http://www.oracle.com/technology/products/mapviewer/pdf/mapviewer_obiee.pdf]
*1- Using OBIEE , I create report with two fields and it's filter on
field Region:*
Region , Population
<!--[if !mso]>
<style>
v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style>
<![endif]--><!--[if gte mso 9]><xml>
Normal
0
false
false
false
MicrosoftInternetExplorer4
</xml><![endif]--><!--[if gte mso 9]><xml>
</xml><![endif]-->
<!--[if gte mso 10]>
<style>
/* Style Definitions */
table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;}
</style>
<![endif]-->
On OBIEE Answers: Statistic Text , I wrote this codes :
<!-div id must match arg in js call at bottom of code listing -->
<div id="EPAmapNode1"></div>
<script>
function readCookie(name) {
//this pulls authentication out of header
//which replaces needing to pass user/pwd
to authenticate (i.e. like SSO or trusted sign on)
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca;
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
return null;
function obiee_mapint_doTheDeed(nodeId) {
var container = document.getElementById(nodeId);
var sid = null;
var x = container;
do {
if (x.nodeName == 'TD' || x.nodeName == 'DIV') {
sid = x.getAttribute('sid');
if (sid != null && sid != '')
break;
x = x.parentNode;
while (x != null);
if (sid != null && sid != '') {
// create the iframe for content
var nid = readCookie('nQuireID')
if (nid) {
var iframe = document.createElement('iframe');
iframe.src =
'http://192.168.100.143:8991/yusufMap-ViewController-context-root/BIMapPage.html?sid='
+ encodeURIComponent(sid) + '&nqid=' + nid;
// following nsdp is subsequently called
from Mapviewer page
// passing sid and nqid to get results to
serve as nsdp data as xml
// ps["xml_url"] = "http://"+document.location.host+"/mapviewer/_epa/obiee_nsdp_xml_direct.jsp?nqid="
+
// urlParamNQID + "&sid=" +
urlParamSID;
iframe.height = 260;
iframe.width = 600;
iframe.frameBorder = 0;
iframe.marginHeight = 1;
iframe.marginWidth = 1;
container.appendChild(iframe);
obiee_mapint_doTheDeed('EPAmapNode1');
// js fn, EPAmapNode1 is id for this map in
dashbd
</script>
*2-Source code of
custom JSP to convert Answers Filtered XML into NSDP XML: obiee_nsdp_xml_direct.jsp*
<%@ page
language="java" session="true"
isThreadSafe="true" contentType="text/html; charset=UTF-8"
%>
<%@ page
import="javax.xml.parsers.*"%>
<%@ page
import="java.net.*"%>
<%@ page
import="java.io.*"%>
<%@ page
import="org.w3c.dom.*"%>
<%
Sample jsp code file to demonstrate one way to convert Answers xml to
MapViewer's NSDP xml
set the character encoding to UTF-8 prior to accessing
data in the request
request.setCharacterEncoding("UTF-8");
%>
<%
// RETRIEVE THE QUERY
STRING PARAMETERS
String userName =
request.getParameter("uid");
String userPassword =
request.getParameter("password");
String thesid =
request.getParameter("sid");
String nq_id =
request.getParameter("nqid");
if (userName == null) {
userName =
"mvdemo";
if (userPassword == null)
userPassword =
"mvdemo";
Document domDoc = null;
String fieldName = null;
String urlString =
"http://192.168.100.143:9704/analytics/saw.dll?Go&searchid=" +
thesid + "&format=xml&NQId=" + nq_id;
if (thesid != null) {
DocumentBuilderFactory
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db =
dbf.newDocumentBuilder();
URL url = new URL(urlString);
URLConnection
URLconnection = url.openConnection();
HttpURLConnection
httpConnection = (HttpURLConnection)URLconnection;
int responseCode =
httpConnection.getResponseCode();
if ( responseCode ==
HttpURLConnection.HTTP_OK) {
InputStream in =
httpConnection.getInputStream();
System.out.println("thesid=
" + thesid);
System.out.println("nq_id="
+ nq_id);
System.out.println("server
host=" + request.getRemoteHost());
System.out.println("server
addr=" + request.getRemoteAddr());
domDoc = db.parse(in);
} else {
System.out.println(
"HTTP connection response != HTTP_OK" );
out.println("<nsdp_xml>");
out.println("<table>");
//Iterate
through metadata object and create the ndsp_xml header
NodeList rowDef =
domDoc.getElementsByTagName("element");
out.println("<tr>");
out.println("<th>Column
1</th><th>Column 2</th>");
out.println("</tr>");
//Iterate
through rows & items and create the ndsp_xml body
NodeList rows =
domDoc.getElementsByTagName("R");
if (rows != null) {
for (int i = 0; i <
rows.getLength(); i++) {
out.println("<tr>");
Node row = rows.item(i);
if (row == null ||
row.getNodeType() == Node.TEXT_NODE) {
continue;
NodeList items =
row.getChildNodes();
if (items == null) {
continue;
for (int y = 0; y < 2;
y++) {
Node item =
items.item(y);
if (item == null ||
item.getChildNodes() == null)
continue;
if (item.getChildNodes()
== null
||
item.getChildNodes().item(0) == null
|| item.getNodeType()
== Node.TEXT_NODE)
continue;
out.println("<td>"
+
item.getChildNodes().item(0).getNodeValue()
+ "</td>");
out.println("</tr>");
} else {
out.println("No
rows.");
out.println("</table>");
out.println("</nsdp_xml>");
%>
*3- Where the source Code of map I created on HTML : BIMapPage.html*
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html;
charset=windows-1252"></meta>
<title>BI Map
Page</title>
<script
language="Javascript" src="oraclemaps.js"></script>
<script
language="Javascript">
var dynStatesFOI;
function show_map(){
var map;
var homeCenter,
homeZoomLevel;
var baseURL =
"http://192.168.100.143:9704/mapviewer";
map = new
MVMapView(document.getElementById("map"), baseURL);
var mapSRID = 82364;
var mapCenterLon = 538940.5;
var mapCenterLat = 2690457.4;
homeZoomLevel = 1;
homeCenter =
MVSdoGeometry.createPoint(mapCenterLon, mapCenterLat, mapSRID);
map.addMapTileLayer(new MVMapTileLayer("tcg_gis.ksa_map"));
map.setCenter(homeCenter, false);
map.setZoomLevel(homeZoomLevel);
map.setHomeMap(homeCenter, homeZoomLevel);
map.addNavigationPanel("East");
map.addScaleBar();
dynStatesFOI = new
MVThemeBasedFOI('dynStatesFOI','tcg_gis.KSA_POP2');
dynStatesFOI.setRenderingStyle("C.COUNTIES");
setupNsdp(dynStatesFOI);
setupDynamicStyles(dynStatesFOI,250000,
500000, 750000);
map.addThemeBasedFOI(dynStatesFOI);
map.display();
function setupNsdp(dynStatesFOI)
var nsdpInfo = new
MVNSDP("defaultNSDP");
nsdpInfo.setTheme("KSA_POP2"); //the base theme
nsdpInfo.setKeyColumn("REGION_NAME");
//'match' column in the base table of the theme
nsdpInfo.setRenderStyle("C.COUNTIES"); //default style;
var ps = new Object();
{color:#ff0000}
ps["xml_url"] ="http://192.168.100.143/mapviewer/obiee_nsdp_xml_direct.jsp?nqid=" + urlParamNQID
+ "&sid=" + urlParamSID;{color} *{color:#800000}// <== Error line {color}*
nsdpInfo.setParameters(ps);
dynStatesFOI.setNSDP(nsdpInfo);
//setups the dynamically created advanced
style to
//be used by the theme-based FOI.
function setupDynamicStyles(dynStt,val1, val2, val3)
var buckets = new
Array(4);
buckets[0] = new
MVNumericRangedBucket(100000, val1, "C.COLOR_BLUE",
"range1");
buckets[1] = new
MVNumericRangedBucket(val1, val2, "C.COLOR_GREEN", "range2");
buckets[2] = new
MVNumericRangedBucket(val2, val3, "C.COLOR_RED", "range3");
buckets[3] = new
MVNumericRangedBucket(val3, null, "C.COLOR_BROWN",
"range4");
var bseries = new
MVBucketSeries("SCHEME_CUSTOM");
bseries.setBuckets(buckets);
var bucketSty = new
MVBucketStyle("region_colors", bseries);
dynStt.addStyle(bucketSty);
dynStt.setRenderingStyle("region_colors");
</script>
</head>
<body
onload="javascript:show_map();">
Welcome to our Site
Kingdom of Saudi Arabia
Map
<div
id="map"
style="width:550.0px; height:500.0px; overflow:auto;
border-color:rgb(0,0,0);"/>
</body>
</html>
{color:#ff0000}
The
highlighted line above from function setupNSDP is code line for: NSDP xml
source to call jsp that invokes java class to convert Answers filtered XML (OBIEE)
into NSDP XML.
Where
its invoke two parameters : 1- urlParamNQID , 2- urlParamSID
ps["xml_url"] =
"http://192.168.100.143/mapviewer/obiee_nsdp_xml_direct.jsp?nqid="
+ urlParamNQID + "&sid=" + urlParamSID;
The
error when we run this code is: URLParamNQID is not defined ???
does any of you can read what i wrote in my source codes and let me know what i missed in my html map code : BIMapPage.html and where or how i can get two parameters values URLParamNQID
and {color}*{color:#ff0000}urlParamSID{color}*{color:#ff0000}?{color}yes i checked this site, but i still couldn't reach the answer of my challenge, in how to specify urlParamNQID and urlParamSID , how or where i can get value of these parameters or what should i pass there !?
-
How can I call a component method from OCAP ?
I'll try to invoke Cold Fusion Component from Xlet (OCAP App), specifically I wan to invoke a query from Component(CFC) method.
Somebody knows how to... or any idea or comments.
Thank you so much!Actually, as long as the servlet returns valid javascript, you can indeed "call it" from the client. It will initiate a request and return the result to the browser.
This example uses Perl, but it could be easily modified to go to a servlet instead.
Note that it is only supported in DOM browsers (IE6+/NN6+/etc)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title> Test server-side JS </title>
</head>
<body>
<script type="text/javascript">
function checkIt(variable, value)
var newScript = "cgi-bin/validateJS.cgi?"+variable+"="+value;
var body = document.getElementsByTagName('body').item(0)
var scriptTag = document.getElementById('loadScript');
if(scriptTag) body.removeChild(scriptTag);
script = document.createElement('script');
script.src = newScript;
script.type = 'text/javascript';
script.id = 'loadScript';
body.appendChild(script)
</script>
<p>Test.</p>
<form id="f1" action="">
<input type="text" name="t1" id="t1" onChange="checkIt(this.name, this.value)">
</body>
</html>
validateJS.cgi
#!/opt/x11r6/bin/perl
use CGI qw(:all);
my @valArray = split(/=/,$ENV{QUERY_STRING});
print "Content-type: text/javascript\n\n";
# myPass is the password
$myPass = "foobar";
if ("$valArray[1]" eq "$myPass")
print "alert(\"Success!!\")";
else
print "alert(\"Failure!!\")"; -
How can I call a servlet method from a javascript function
I want to call l a servlet method from a javascript function.
Does any one have an example of code.
Thinks in advanceActually, as long as the servlet returns valid javascript, you can indeed "call it" from the client. It will initiate a request and return the result to the browser.
This example uses Perl, but it could be easily modified to go to a servlet instead.
Note that it is only supported in DOM browsers (IE6+/NN6+/etc)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title> Test server-side JS </title>
</head>
<body>
<script type="text/javascript">
function checkIt(variable, value)
var newScript = "cgi-bin/validateJS.cgi?"+variable+"="+value;
var body = document.getElementsByTagName('body').item(0)
var scriptTag = document.getElementById('loadScript');
if(scriptTag) body.removeChild(scriptTag);
script = document.createElement('script');
script.src = newScript;
script.type = 'text/javascript';
script.id = 'loadScript';
body.appendChild(script)
</script>
<p>Test.</p>
<form id="f1" action="">
<input type="text" name="t1" id="t1" onChange="checkIt(this.name, this.value)">
</body>
</html>
validateJS.cgi
#!/opt/x11r6/bin/perl
use CGI qw(:all);
my @valArray = split(/=/,$ENV{QUERY_STRING});
print "Content-type: text/javascript\n\n";
# myPass is the password
$myPass = "foobar";
if ("$valArray[1]" eq "$myPass")
print "alert(\"Success!!\")";
else
print "alert(\"Failure!!\")"; -
How can I call a stateful webservice from a user-defined XPath function?
I'm calling a stateful webservice from a BPEL process using a PartnerLink which implements Custom Header Handler classes to handle the session state, storing the cookie as a property of the PartnerLink.
I'd also like to call this same stateful webservice, in the same session, from a user-defined XPath function enabling me to call this from an XSL Transformation.
Is this in any way possible? Can I access the cookie and attach it to the webservice call made by the user-defined XPath function?Actually, as long as the servlet returns valid javascript, you can indeed "call it" from the client. It will initiate a request and return the result to the browser.
This example uses Perl, but it could be easily modified to go to a servlet instead.
Note that it is only supported in DOM browsers (IE6+/NN6+/etc)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title> Test server-side JS </title>
</head>
<body>
<script type="text/javascript">
function checkIt(variable, value)
var newScript = "cgi-bin/validateJS.cgi?"+variable+"="+value;
var body = document.getElementsByTagName('body').item(0)
var scriptTag = document.getElementById('loadScript');
if(scriptTag) body.removeChild(scriptTag);
script = document.createElement('script');
script.src = newScript;
script.type = 'text/javascript';
script.id = 'loadScript';
body.appendChild(script)
</script>
<p>Test.</p>
<form id="f1" action="">
<input type="text" name="t1" id="t1" onChange="checkIt(this.name, this.value)">
</body>
</html>
validateJS.cgi
#!/opt/x11r6/bin/perl
use CGI qw(:all);
my @valArray = split(/=/,$ENV{QUERY_STRING});
print "Content-type: text/javascript\n\n";
# myPass is the password
$myPass = "foobar";
if ("$valArray[1]" eq "$myPass")
print "alert(\"Success!!\")";
else
print "alert(\"Failure!!\")";
Maybe you are looking for
-
Fun with Formatting/Formulas
I am trying to 'change' a Crystal Report into XML Publisher and am running into some issues. When I create the RTF template in Word (using Template Builder 5.6.2), I am losing the formatting on the first line. This template is using a 'standard' word
-
How do you install "Twixtor" plug in for FCP
Hello, I think I have installed it properly, I'm not to sure... In FCP i click on "EFFECTS/Video Filters/RE: Vision Plug-in/ and I see Twixtor 4 TWixtor 4.5 pro Twixor 4.5 vector but when i click it nothing happens... shouldn't a box pop in the viwer
-
Can I change my SIM card to use it in South Korea?
Hi, I'm planning to stay in South Korea for 3 months this summer and I was wondering if I could buy a new SIM card in Korea and put it into my current Verizon phone that I'm using in the States(It is Galaxy S4). Global plan seems to be expensive so I
-
Windows 8.1 Store error 0x80070002
Hi all. First of all, I will link to this thread http://answers.microsoft.com/en-us/windows/forum/windows8_1-windows_update/windows-81-store-error-0x80070002-comprehensive/2b0ed3e1-1835-4517-97dd-0a7abb6ef74c?page=3 where I have started fixing my err
-
How to analyze the String input??
The program should accept integers but not the sentences for example the user enters "Hi how are you" the program should say"Sorry, please enter the integers" if the user enters "123454545" the program should work normally The main aim is to differen