How to write conditional logic using ant-contrib - ant

I am a beginner in ANT.
What am I doing wrong? ant-contrib-1.0b3 , is available. I would like to call the default target as follows:
<target name="build">
<if>
<equals arg1="${config.name}" arg2="foo" />
<then>
<depends="get-all-war,..." />
</then>
<elseif>
<equals arg1="${config.name}" arg2="mark" />
<then>
<depends="zip-wars, ..." />
</then>
</elseif>
<else>
<depends="get-all-war, zip-wars, docs, deleteAll" />
</else>
</if>

you need to use antcall to execute other targets.
<target name="build">
<if>
<equals arg1="${config.name}" arg2="foo" />
<then>
<antcall target="get-all-war" />
<antcall target="..." />
</then>
<elseif>
<equals arg1="${config.name}" arg2="mark" />
<then>
<antcall target="zip-wars" />
<antcall target="..." />
</then>
</elseif>
<else>
<antcall target="get-all-war" />
<antcall target="zip-wars" />
<antcall target="docs" />
<antcall target="deleteAll" />
</else>
</if>

You can do the same thing smartly using macros. If your targets get-all-war, zip-wars, docs, deleteAll take more time you can run them in parallel like this :
<target name="build">
<if>
<equals arg1="${config.name}" arg2="foo" />
<then>
<mGetAllWar/>
</then>
<elseif>
<equals arg1="${config.name}" arg2="mark" />
<then>
<mZipWars />
</then>
</elseif>
<else>
<mRestAllTargets/>
</else>
</if>
<mGetAllWar>
<parallel>
<antcall name="target1">
<antcall name="target2">
...
</parallel>
</mGetAllWar>
<mZipWars >
<parallel>
<antcall name="target1">
<antcall name="target2">
...
</parallel>
</mZipWars >
<mRestAllTargets>
<parallel>
<antcall name="target1">
<antcall name="target2">
...
</parallel>
</mRestAllTargets>

Related

XmlValidate in ant with namespace

How can i validate these xml and xsd file with xmlvalidate task with Ant . i have tried but didn't get solution for it .can i get a solution
<property name="doc.xsd" location="${basedir}/test.xsd" />
<target name="FindDesc" >
<xmlvalidate file="ab.xml" lenient="yes" failonerror="yes" warn="yes">
<fileset dir="${basedir}" includes="ab.xsl" />
<attribute name="http://xml.org/sax/features/validation" value="true"/>
<attribute name="http://apache.org/xml/features/validation/schema" value="true"/>
<attribute name="http://xml.org/sax/features/namespaces" value="true"/>
<property name="http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation" value="${doc.xsd}" />
</xmlvalidate>
</target>
ab.xml file
<?xml version="1.0"?>
<books xmlns="http://www.example.org/Test" xmlns:xsi="http://www.w3.org/2001/XMLSchema" xsi:noNamespaceSchemaLocation="test.xsd">
<book id="bk001">
<author>Writer</author>
<title>The First Book</title>
<genre>Fiction</genre>
<price>44.95</price>
<pub_date>2000-10-01</pub_date>
<review>An amazing story of nothing.</review>
</book>
<book id="bk002">
<author>Poet</author>
<title>The Poet's First Poem</title>
<genre>Poem</genre>
<price>24.95</price>
<review>Least poetic poems.</review>
</book>
</books>
test.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" targetNamespace="http://www.example.org/Test"
>
<xsd:element name="books" >
<xsd:complexType >
<xsd:sequence>
<xsd:element name="book" maxOccurs="unbounded" minOccurs="0">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="author" type="xsd:string"/>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="genre" type="xsd:string"/>
<xsd:element name="price" type="xsd:float" />
<xsd:element name="pub_date" type="xsd:date" />
<xsd:element name="review" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>
i have tried to test xml with xsd schema with Ant Script i get its not working as mine i get error like this
cvc-elt.1: Cannot find the declaration of element 'books'.
and with these
TargetNamespace.2: Expecting no namespace, but the schema document has a target namespace of 'http://www.example.org/Test'.
xml with no namespace but i want to try to validate with namespace through ant script ..
what can i do if there is any error please give suggestion to test these xml and xsd file with ant script i have gone through xml validation and schema validation
we can use SchemaValidation its easy and fast way to validate the xml with xsd file
If there is one file we can go through this
<schemavalidate>
<schema namespace="<schema_nameSpace>">
file="abc.xml"/>
</schemavalidate>
If multiple file is there we can use fileset
<schemavalidate warn="true" failonerror="true" fullchecking="true">
<fileset dir="<Src_dir_for_Xml>">
<include name="*.xml" />
</fileset>
<schema namespace="<Your schema name space>" file="<schema_src_dir_For_schema" />
</schemavalidate>

NLog not logging the exception or any other text

Here is my Nlog.Config code.
<nlog>
<variable name="logFilePath" value="C:\NLog\IDG-${shortdate}.log" />
<targets>
<target name="logfile"
xsi:type="File"
fileName="${logFilePath}"
layout="${longdate} LEVEL=${level:upperCase=true}: ${message}"
keepFileOpen="true" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
<logger name="*" minlevel="Info" writeTo="logfile" />
<logger name="*" minlevel="Warn" writeTo="file"/>
</rules>
</nlog>
and am defining this in my class
private static Logger logger = LogManager.GetCurrentClassLogger();
and then I'm logging the error as:
catch (Exception ex)
{
logger.Error(ex.Message,"test");
}
Can anyone please suggest me if there is any better way to do this, I don't see the file logging in the destined folder.
It seems that you may not be referencing the config section correctly. Try changing your main config file to something like this and remove the Nlog.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<variable name="logFilePath" value="C:\temp\output.log" />
<targets>
<target name="logfile"
xsi:type="File"
fileName="${logFilePath}"
layout="${longdate} LEVEL=${level:upperCase=true}: ${message}"
keepFileOpen="true" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
<logger name="*" minlevel="Info" writeTo="logfile" />
<logger name="*" minlevel="Warn" writeTo="file"/>
</rules>
</nlog>
</configuration>

WSO2 ESB - Consume a OAuth2 Service

I'm tying to call an OAuth token service to retrieve the token.
Below is my proxy. This is a simple rest endpoint call which retrieves the token. For testing purpose I'm trying to log the token in the response.
<?xml version="1.0" encoding="UTF-8"?>
<proxy name="sla_proxy_svc_vo2" startOnLoad="true" trace="disable"
transports="http https" xmlns="http://ws.apache.org/ns/synapse">
<target>
<inSequence>
<log level="custom">
<property name="msg" value="*****INITIATING*****" />
</log>
<payloadFactory media-type="xml">
<format>
<soapenv:Envelope xmlns:echo="http://echo.services.core.carbon.wso2.org"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<nstxt:text xmlns:nstxt="http://ws.apache.org/commons/ns/payload">grant_type=client_credentials&client_id=G6Dk_3ZdrXOfPiuctufVq6GfTWoa&client_secret=jxA8NTkEClE5xGUvGvvhVTDyXM4a</nstxt:text>
</soapenv:Body>
</soapenv:Envelope>
</format>
<args />
</payloadFactory>
<log level="custom">
<property name="msg" value="*****BEFORE TOKEN SERVICE CALL*****" />
</log>
<log level="full" />
<property name="HTTP_METHOD" scope="axis2" type="STRING"
value="POST" />
<property name="messageType" scope="axis2" type="STRING"
value="text/plain" />
<property name="ContentType" scope="axis2" type="STRING"
value="text/plain" />
<property name="Accept" scope="axis2" type="STRING"
value="application/json" />
<send>
<endpoint>
<http format="rest" method="post" trace="disable"
uri-template="http://10.236.70.9:8281/token" />
</endpoint>
</send>
</inSequence>
<outSequence>
<log level="custom">
<property name="msg" value="******OUT SEQUENCE*******" />
</log>
<log level="full" />
<send />
</outSequence>
<faultSequence />
</target>
</proxy>
I'm getting the below response when I call.
DEBUG {org.apache.synapse.transport.http.wire} - << "HTTP/1.1 415 Unsupported Media Type[\r][\n]" {org.apache.synapse.transport.http.wire}
DEBUG {org.apache.synapse.transport.http.wire} - << "X-Frame-Options: DENY[\r][\n]" {org.apache.synapse.transport.http.wire}
DEBUG {org.apache.synapse.transport.http.wire} - << "X-XSS-Protection: 1; mode=block[\r][\n]" {org.apache.synapse.transport.http
Will be please if anyone can guide me of I'm doing anything wrong here.
I was able to call the service with the following payload.
<payloadFactory media-type="xml">
<format>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<root>
<grant_type>client_credentials</grant_type>
<client_id>G6Dk_3ZdrXOfPiuctufVq6GfTWoa</client_id>
<client_secret>jxA8NTkEClE5xGUvGvvhVTDyXM4a</client_secret>
</root>
</soapenv:Body>
</soapenv:Envelope>
</format>
<args />
</payloadFactory>
Also had to add the content type as below.
<property name="messageType" scope="axis2" type="STRING" value="application/x-www-form-urlencoded" />
<property name="ContentType" scope="axis2" type="STRING" value="application/x-www-form-urlencoded" />
This worked and retrieved the token.
Here is a template I'm using in a component to set the oAuth token, you could probably adapt it a bit for your case (sounds like you do not need grantType or user credentials)
<?xml version="1.0" encoding="UTF-8"?>
<template name="getToken" xmlns="http://ws.apache.org/ns/synapse">
<parameter name="tokenURL"/>
<parameter name="clientId"/>
<parameter name="clientSecret"/>
<parameter name="grantType"/>
<sequence>
<property description="Base64 crendetials" expression="base64Encode(fn:concat($func:clientId,':',$func:clientSecret))" name="credentials" scope="default" type="STRING"/>
<property description="Authentication" expression="fn:concat('Basic ', get-property('credentials'))" name="Authorization" scope="transport" type="STRING"/>
<header name="Content-Type" scope="transport" value="application/x-www-form-urlencoded"/>
<property name="messageType" scope="axis2" type="STRING" value="application/x-www-form-urlencoded"/>
<property name="DISABLE_CHUNKING" scope="axis2" type="STRING" value="true"/>
<property expression="$func:tokenURL" name="uri.var.authUrl" scope="default" type="STRING"/>
<property expression="$func:grantType" name="uri.var.grantType" scope="default" type="STRING"/>
<call blocking="true">
<endpoint>
<http method="post" uri-template="{uri.var.authUrl}?grant_type={uri.var.grantType}"/>
</endpoint>
</call>
<property expression="json-eval($.access_token)" name="OAuth_Token" scope="default" type="STRING"/>
<property action="remove" description="Remove Headers" name="TRANSPORT_HEADERS" scope="axis2"/>
<property description="Authorization" expression="fn:concat('Bearer ',get-property('OAuth_Token'))" name="Authorization" scope="transport" type="STRING"/>
</sequence>
</template>

create an entry in local OData service

I am trying to create en entry in my local OData service like in this example
Using Postman I am making a POST request on https://localhost:8090/odata/titles with this JSON body
{
"#odata.type":"SAPSybaseOData.titles",
"title_id":"ZZ1234",
"title":"new book",
"type":"business",
"pub_id":"1390",
"price":1,
"advance":1,
"total_sales":1,
"notes":"note",
"pubdate":"/Date(581817600000)/",
"contract":true
}
the OData service response status code is 400 - Bad request with this XML body
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<code>30068</code>
<message xml:lang="en-US">An error occurred while parsing the request body.</message>
</error>
my OData service metadata is
<edmx:Edmx xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx" Version="1.0">
<edmx:DataServices xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:DataServiceVersion="1.0">
<Schema xmlns="http://schemas.microsoft.com/ado/2008/09/edm" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" Namespace="SAPSybaseOData">
<EntityType Name="titles">
<Key>
<PropertyRef Name="title_id" />
</Key>
<Property Name="title_id" Type="Edm.String" Nullable="false" MaxLength="6" Unicode="false" Collation="cp850" />
<Property Name="title" Type="Edm.String" Nullable="false" MaxLength="80" Unicode="false" Collation="cp850" />
<Property Name="type" Type="Edm.String" Nullable="false" MaxLength="12" Unicode="false" Collation="cp850" FixedLength="true" />
<Property Name="pub_id" Type="Edm.String" Nullable="true" MaxLength="4" Unicode="false" Collation="cp850" />
<Property Name="price" Type="Edm.Decimal" Nullable="true" Precision="14" Scale="4" />
<Property Name="advance" Type="Edm.Decimal" Nullable="true" Precision="14" Scale="4" />
<Property Name="total_sales" Type="Edm.Int32" Nullable="true" />
<Property Name="notes" Type="Edm.String" Nullable="true" MaxLength="200" Unicode="false" Collation="cp850" />
<Property Name="pubdate" Type="Edm.DateTime" Nullable="false" Precision="3" />
<Property Name="contract" Type="Edm.Boolean" Nullable="false" />
</EntityType>
<EntityContainer Name="SAPSybaseOData_Container" m:IsDefaultEntityContainer="true">
<EntitySet Name="titles" EntityType="SAPSybaseOData.titles" />
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
How can I create a new entry like in this example ?
Am I missing something ? How come the example is working fine and I get a parsing error ?

ant-how can i return value from macrodef?

I need to compare two string args, from which I used to get one arg as runtime input (e.g. platform=windows,ios,mac) and another one has list of values, defined under build.properties (e.g. project.supportedplatforms=windows,mac). If the condition matches, then it should return "true" else "fail" from one macrodef to some target.
<for list="${platform}" param="platformparam" trim="true">
<sequential>
<if>
<isItemExists retToProp="#{platformparam}" />
<then>
<antcall target="package.#{platformParam}" />
</then>
</if>
</sequential>
</for>
<macrodef name="isItemExists">
<attribute name="retToProp" />
<property name="itemtosearch" value="#{retToProp}" />
<for list="${project.supportedplatforms}" param="listparam" trim="true">
<if>
<equals arg1="#{listparam}" arg2="#{platformparam}" />
<then>
<!-- return true -->
</then>
<else>
<!-- return false -->
</else>
</if>
</for>
</macrodef>
When ${platforms} and ${project.supportedplatforms} having same value it should call the specified target. But in this snippets, the macrodef-for loop will executes for n times and at last what the value is assigned for #{returnproperty}, is going to throw for target "build", if it happens like this with valid input, it will not do my stuff, because for loop will execute in sequential manner. (e.g. platforms=windows,mac,android, project.supportedplatforms=ios,android,windows, if my list looks like this means, is there any possible way to get my result).
<for list="${platforms}" param="platformparam" trim="true">
<sequential>
<isItemExists returnProperty="returnProp" platforms="#{platformparam}" />
<if>
<equals arg1="${returnProp}" arg2="true" />
<then>
<antcall target="package.#{platformparam}" />
</then>
</if>
</sequential>
</for>
<macrodef name="isItemExists">
<attribute name="platform" />
<attribute name="returnProperty" />
<sequential>
<var name="#{returnProperty}" unset="true" />
<for list="${project.supportedplatforms}" param="listparam" trim="true">
<if>
<equals arg1="#{listparam}" arg2="#{platform}" />
<then>
<property name="#{returnProperty}" value="true" />
</then>
<else>
<property name="#{returnProperty}" value="false" />
</else>
</if>
</sequential>
</macrodef>
<target name="some-test-target">
<for list="${platform}" param="platformparam" trim="true">
<sequential>
<isItemExists platform="#{platformparam}" returnProperty="returnProp" />
<if>
<equals arg1="${returnProp}" arg2="true"/>
<then>
<antcall target="package.#{platformparam}"/>
</then>
</if>
</sequential>
</for>
</target>
Use sequential task for running for ant-contrib task like:
<macrodef name="isItemExists">
<attribute name="platform"/>
<attribute name="returnProperty"/>
<sequential>
<var name="#{returnProperty}" unset="true"/>
<for list="${project.supportedplatforms}" param="listparam" trim="true">
<sequential>
<if>
<equals arg1="#{listparam}" arg2="#{platform}"/>
<then>
<property name="#{returnProperty}" value="true"/>
</then>
<else>
<property name="#{returnProperty}" value="false"/>
</else>
</if>
</sequential>
</for>
</sequential>
</macrodef>
I have an example that returns the time from a call to <tstamp>
Hope this helps!
<macrodef name="gettime">
<attribute name="time-stamp" default=""/>
<sequential>
<tstamp>
<format property="time-stamp" pattern="yyyyMMdd_HHmmss" />
</tstamp>
</sequential>
</macrodef>
<target name="test-time">
<gettime/>
<echo message="${time-stamp}" />
</target>

Resources