Java Service Error - webMethods - webmethods

In a java service, without a function declaration, a function call is there and only compile time error comes. But the output is as expected with no run time errors. How is that possible? Can anyone please explain?
"The method functionName() is undefined" is the error it shows.
Below is the code.
public static final void documentToStringVals(IData pipeline)
throws ServiceException {
// pipeline
IDataCursor pipelineCursor = pipeline.getCursor();
String success = "false";
IData inputDoc = null;
String outputValue = "";
String headerYN = "N";
boolean headerValue = false;
String delimiter = ",";
String newline = System.getProperty("line.separator");
if (pipelineCursor.first("inputDocument") ) {
inputDoc = (IData) pipelineCursor.getValue();
}
else {
throw new ServiceException("inputDocument is a required parameter");
}
if (pipelineCursor.first("delimiter") ) {
delimiter = (String) pipelineCursor.getValue();
}
if (pipelineCursor.first("headerYN") ) {
headerYN = (String) pipelineCursor.getValue();
}
if (headerYN.equalsIgnoreCase("Y")) {
headerValue = true;
}
try {
outputValue = docValuesToString(inputDoc, headerValue, delimiter);
outputValue += newline;
success = "true";
}
catch (Exception e) {
System.out.println("Exception in getting string from document: " + e.getMessage());
pipelineCursor.insertAfter("errorMessage", e.getMessage());
}
pipelineCursor.insertAfter("success", success);
pipelineCursor.insertAfter("outputValue", outputValue);
pipelineCursor.destroy();
}

The code you posted has no reference to "functionName", so I suspect there's a reference to it either in the shared code section or in another Java service in the same folder. Given that all Java services in a folder get compiled into a single class, and therefore all those services need to be compiled together, this could cause the error message when you're compiling the service above.

Related

how to execute statements only after junit reports are generated by TESTNG?

I'm converting junit reports generated by testng to some other format.
I've written this code to do so:
#AfterTest
public void execute()
{
String junitReport = "TEST-"+this.getClass().getCanonicalName()+".xml";
TestManagerLogger obj = new TestManagerLogger();
obj.convertLog(junitReport);
}
But this doesn't work as reports are not generated before the execution of this method.
Is there any way by which this method can be called only after report generation?
My test Case :
#Test(dataProvider = "jobCount")
public void testJobCount(String Scenario, String URL,String methodType, String status) {
URL = URL.replaceFirst("ip", ip);
String logonToken=LogonUtility.logon();
String result= ResponseGenerator.response(URL, logonToken, methodType);
List<HashMap> valuesFromExcel = StringSplitter.getKeyValuePairs(status);// Returns hashmap containing key values ex: failed =0 , total =3
List<HashMap> valuesFromRest = new ArrayList<HashMap>();
Document doc = StringSplitter.convertStringToDocument(result);
javax.xml.xpath.XPath xPath = XPathFactory.newInstance().newXPath();
NodeList node,node1;
try{
node =(NodeList)xPath.evaluate("/feed/entry/content/attrs/attr[#name='status_type']", doc, XPathConstants.NODESET);
node1 = (NodeList) xPath.evaluate("/feed/entry/content/attrs/attr[#name='count']", doc, XPathConstants.NODESET);
HashMap<String,String> hm = new HashMap<String,String>();
for(int i=0;i<node.getLength();i++)
{
hm.put(node.item(i).getTextContent(),node1.item(i).getTextContent() );
}
valuesFromRest.add(hm);
if(valuesFromRest.equals(valuesFromExcel))
{
AssertJUnit.assertTrue(true);
}
else
{
AssertJUnit.assertTrue(false);
}
}catch(Exception e) {
e.printStackTrace();
}
}
Expected XML Report
<logfile>
<logrecord>
<case>scenario</case>
<etime>Execution time</etime>
</logrecord>
</logfile>
Scenario is passed as a parameter in testcase
What you should instead do is to implement your own reporter: http://testng.org/doc/documentation-main.html#logging-reporters
public class TestManagerReporter implements IReporter {
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
// print <logfile>
for (ISuite suite : suites) {
for (IInvokedMethod method : suite.getAllInvokedMethods()) {
if (method.isTestMethod()) {
ITestResult result = method.getTestResult();
if (result.getStatus() == SUCCESS) {
// print <logrecord>
// print <case>
// print result.getName()
// print </case>
// print <etime>
// print result.getEndMillis() - result.getStartMillis()
// print </etime>
// print </logrecord>
}
}
}
}
// print </logfile>
}
}

how to get parameter when mybatis exception

I'm sorry. I can't write English well.
this is my mybatis error message(e.getMessage())
### Error updating database. Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'name' at row 1
### The error may involve default.user-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO USER (name) VALUES (?)
### Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'name'
at row 1; SQL []; Data truncation: Data too long for column 'name' at row 1; nested exception is
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'name' at row 1
I want know parameter when Exception occur.
SQL: INSERT INTO USER (name) VALUES (?) >> I want get this question value.
i try this code
try {
sqlSessionTemplate.insert("namespace.id", parameter);
} catch (Exception e) {
if (e instanceof BadSqlGrammarException) {
logger.error("{}", e.getMessage());
} else if (e instanceof DataIntegrityViolationException) {
logger.error("{}", e.getMessage());
} else if (e instanceof MysqlDataTruncation) {
logger.error("{}", e.getMessage());
}
}
DataIntegrityViolationException, MysqlDataTruncation does not support get error paramters.
this is a sample, I want know get parameters(object) in Exception.
Can you give me some advice to solve this problem?Thanks.
Set up logging in MyBatis and set it to TRACE level. That way you will have your whole INSERT statement (with actually used parameters) written in the log file.
you can write a mybatis's plugin,as follow:
#Intercepts({ #Signature(type = ParameterHandler.class, method = "setParameters", args = { PreparedStatement.class }) })
public class SQLErrorContextInterceptor implements Interceptor {
private final ILogger logger = new LoggerImpl(this.getClass());
#Override
public Object intercept(Invocation invocation) throws Throwable {
invocation.proceed();
Object target=invocation.getTarget();
if( ! (target instanceof DefaultParameterHandler) ){
return null;
}
DefaultParameterHandler hander=(DefaultParameterHandler)target;
//obtains 5 fields from DefaultParameterHandler object
Class<?> clz =hander.getClass();
Field f = clz.getDeclaredField("mappedStatement");
f.setAccessible(true);
MappedStatement mappedStatement=(MappedStatement)f.get(hander);
Configuration configuration = mappedStatement.getConfiguration();
TypeHandlerRegistry typeHandlerRegistry=mappedStatement.getConfiguration().getTypeHandlerRegistry();
f=clz.getDeclaredField("boundSql");
f.setAccessible(true);
BoundSql boundSql=(BoundSql)f.get(hander);
Object parameterObject=hander.getParameterObject();
//used to stored parameters values order by sql parameters
List<Object> columnValues = new ArrayList<Object>();
// get parameters'value by for-each
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else {
value = metaObject == null ? null : metaObject.getValue(propertyName);
}
columnValues.add(value);
}
}
}
// overwrite sql's context in ErrorContext, and append parameters's value-str
ErrorContext.instance().sql(boundSql.getSql() + " parameters:" + this.getParameterValueString(columnValues));
return null;
}
private String getParameterValueString(List<Object> columnValues) {
List<Object> typeList = new ArrayList<Object>(columnValues.size());
for (Object value : columnValues) {
if (value == null) {
typeList.add("null");
} else {
typeList.add(value + "(" + value.getClass().getSimpleName() + ")");
}
}
final String parameters = typeList.toString();
return parameters.substring(1, parameters.length() - 1);
}
#Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
#Override
public void setProperties(Properties properties) {
}
}

MvvmCross: NotImplementedException calling EnsureFolderExists method of IMvxFileStore

I'm developing my first Windows Store App, using MvvmCross framework and I have a problem with images management. In particular I have the following simple ViewModel in my PCL project, and a Store project with a button bound with AddPictureCommand.
public class FirstViewModel : MvxViewModel
{
IMvxPictureChooserTask _pictureChooserTask;
IMvxFileStore _fileStore;
public FirstViewModel(IMvxPictureChooserTask pictureChooserTask, IMvxFileStore fileStore)
{
_pictureChooserTask = pictureChooserTask;
_fileStore = fileStore;
}
private byte[] _pictureBytes;
public byte[] PictureBytes
{
get { return _pictureBytes; }
set
{
if (_pictureBytes == value) return;
_pictureBytes = value;
RaisePropertyChanged(() => PictureBytes);
}
}
public ICommand AddPictureCommand
{
get { return new MvxCommand(() =>
{
_pictureChooserTask.ChoosePictureFromLibrary(400, 95, pictureAvailable, () => { });
}); }
}
private void pictureAvailable(Stream stream)
{
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
PictureBytes = memoryStream.ToArray();
GenerateImagePath();
}
private string GenerateImagePath()
{
if (PictureBytes == null) return null;
var RandomFileName = "Image" + Guid.NewGuid().ToString("N") + ".jpg";
_fileStore.EnsureFolderExists("Images");
var path = _fileStore.PathCombine("Images", RandomFileName);
_fileStore.WriteFile(path, PictureBytes);
return path;
}
}
The problem is that the method _fileStore.EnsureFolderExists("Images");
gives me the an "NotImplementedException" with message: "Need to implement this - doesn't seem obvious from the StorageFolder API".
Has anyone already seen it before?
Thank you
This not implemented exception is documented in the wiki - see https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#File
It should be fairly straightforward to implement these missing methods if they are required. Indeed I know of at least 2 users that have implemented these - but sadly they've not contributed them back.
to implement them, just
fork (copy) the code from https://github.com/MvvmCross/MvvmCross/blob/v3/Plugins/Cirrious/File/Cirrious.MvvmCross.Plugins.File.WindowsStore/MvxWindowsStoreBlockingFileStore.cs
implement the missing methods using the winrt StorageFolder apis
in your Store UI project, don't load the File plugin - so comment out or remove the File bootstrap class.
during setup, register your implementation with ioc using Mvx.RegisterType - e.g.:
protected override void InitializeFirstChance()
{
base.InitializeFirstChance();
Cirrious.CrossCore.Mvx.RegisterType<IMvxFileStore, MyFileStore>();
}
For more on using ioc, see https://github.com/MvvmCross/MvvmCross/wiki/Service-Location-and-Inversion-of-Control
For more on customising the setup sequence, see https://github.com/MvvmCross/MvvmCross/wiki/Customising-using-App-and-Setup
Following Stuart's suggestions I've implemented the following methods for Windows 8 Store App:
public bool FolderExists(string folderPath)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
}
catch (FileNotFoundException)
{
return false;
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in FolderExists - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
return true;
//throw new NotImplementedException("Need to implement this - See EnsureFolderExists");
}
public void EnsureFolderExists(string folderPath)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
}
catch (FileNotFoundException)
{
var localFolder = ToFullPath(string.Empty);
var storageFolder = StorageFolder.GetFolderFromPathAsync(localFolder).Await();
storageFolder.CreateFolderAsync(folderPath).Await();
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in EnsureFolderExists - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
//throw new NotImplementedException("Need to implement this - doesn't seem obvious from the StorageFolder API");
//var folder = StorageFolder.GetFolderFromPathAsync(ToFullPath(folderPath)).Await();
}
The third method we need to implement is DeleteFolder(string folderPath, bool recursive). Unfortunately StorageFolder method "DeleteFolder" doesn't have a "recursive" parameter. So I should implement DeleteFolder ignoring it:
public void DeleteFolder(string folderPath, bool recursive)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
storageFolder.DeleteAsync().Await();
}
catch (FileNotFoundException)
{
//Folder doesn't exist. Nothing to do
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in DeleteFolder - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
//throw new NotImplementedException("Need to implement this - See EnsureFolderExists");
}
or I should check if the folder is empty before to delete it if "recursive" equals false.
Better implementations are welcomed.

EWS signature updation error

public void updateSignature(ExchangeService exchange, String signature) {
try {
FolderId f = new FolderId(WellKnownFolderName.Root);
UserConfiguration user = UserConfiguration.bind(exchange,
"OWA.UserOptions", f, UserConfigurationProperties.All);
if (user.getDictionary().containsKey("signaturetext"))
user.getDictionary().setElements("signaturetext", signature);
else
user.getDictionary().addElement("signaturetext", signature);
user.update();
} catch (Exception e) {
e.printStackTrace();
}
}
I am getting a null pointer exception for user.update(); I am able to print the old signature in the console before setting the new one and also the new one after setting it in the dictionary. But, I am not able to update the changes permanently. Thanks in advance
.
in the others code it's using root.parentFolderId not root.
maybe it's that problem:
attached the code
static void SetSigniture(ExchangeService service) throws Exception {
Folder Root = Folder.bind(service, WellKnownFolderName.Root);
UserConfiguration OWAConfig = UserConfiguration.bind(service, "OWA.UserOptions", Root.getParentFolderId(), UserConfigurationProperties.All);
String hsHtmlSigniture = "<img src='http://www.baidu.com/img/baidu_jgylogo3.gif' />";
String stTextSig = "Text sig";
System.out.println(OWAConfig.getDictionary().getElements("timezone"));;
if (OWAConfig.getDictionary().containsKey("signaturehtml")) {
OWAConfig.getDictionary().setElements("signaturehtml", new Object());
} else {
OWAConfig.getDictionary().addElement("signaturehtml", hsHtmlSigniture);
}
if (OWAConfig.getDictionary().containsKey("signaturetext")) {
OWAConfig.getDictionary().setElements("signaturetext", stTextSig);
} else {
OWAConfig.getDictionary().addElement("signaturetext", stTextSig);
}
OWAConfig.update();
}

System.Net.WebException: The request failed with HTTP status 400: Bad Request. calling a webservice dynamically

Iam calling a web service through my web service dynamically. I stored serviceName, MethodToCall, and array of parameters in my database table and execute these two methods to call a dynamic service url with .asmx extention and its method without adding its reference in my app. It works fine.
Following code is here.
public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
{
String Result = String.Empty;
//Specify service Url without ?wsdl suffix.
//Reference urls for code help
///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
//http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
//String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
String WSUrl = strURL;
//Specify service name
String WSName = ServiceName;
//Specify method name to be called
String WSMethodName = MethodToCall;
//Parameters passed to the method
String[] WSMethodArguments = Params;
//WSMethodArguments[0] = "20500";
//Create and Call Service Wrapper
Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);
if (WSResults != null)
{
//Decode Results
if (WSResults is DataSet)
{
Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
}
else if (WSResults is Boolean)
{
bool BooleanResult = (Boolean)WSResults;
if(BooleanResult)
Result += "Result: \r\n" + "Success";
else
Result += "Result: \r\n" + "Failure";
}
else if (WSResults.GetType().IsArray)
{
Object[] oa = (Object[])WSResults;
//Retrieve a property value withour reflection...
PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
foreach (Object oae in oa)
{
Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
}
}
else
{
Result += ("Result: \r\n" + WSResults.ToString());
}
}
return Result;
}
public Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
Uri objURI = new Uri(webServiceAsmxUrl);
//bool isProxy = client.Proxy.IsBypassed(objURI);
//objURI = client.Proxy.GetProxy(objURI);
//-Connect To the web service
// System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
//string wsdlContents = client.DownloadString(ccc);
string wsdlContents = client.DownloadString(ccc);
XmlDocument wsdlDoc = new XmlDocument();
wsdlDoc.InnerXml = wsdlContents;
System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));
//Read the WSDL file describing a service.
// System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);
//Load the DOM
//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);
//--Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);
//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
if (warning == 0)
{
//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};
//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
//--Check For Errors
if (results.Errors.Count > 0)
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}
//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
Now the problem arraize when i have two different client servers. and calling a service from one server to the service deployed on other server. Follwing two kind of error log occurs. Cant find the exact reson for cope up this problem.
System.Net.WebException: The request failed with HTTP status 400: Bad Request.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)
and
System.Net.Sockets.SocketException (0x80004005):
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.17.13.7:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
Please Carry Out Following Steps :
1) First of all try to access your service by adding reference of it.
It it works fine then we can say that there is no problem related to accessibility and permission.
2) If its not work then there is a problem with connection.
-->So Check Configuration in your service and try to set timeout for your web service.
(http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7-
333579a9f0fe/webservice-client-timeout)
3)Now try after setting the timeout.
it operation completes successfully after above change that means now you can check with your web client method(dymamic calling).
4) If still problem persists then this might be network latency issue. Check the n/w latency between your client and server.
it will helps you.