Calling a Java Web Service from a .Net Project - Handling arrays - java

I am trying to call some web services written in Java from my asp.net code. I don't know Java.
There are several methods each with multiple properties. These methods are then passed to one controlling method. The problem occurs with how to handle arrays. I cannot seem to get the syntax quite right.
For example, there can be from 1 to n locations. Each location has multiple properties.
I can build one location ok. But how do I build an array of locations? I tried several approaches. Here is the closest I’ve gotten. It complies but crashes on the third to the last line below. I’ve removed the code that is not relevant to explaining the problem.
The error says: Object reference not set to an instance of an object.
WebReferenceMERegistration.getMERegistration _myMERegistration =
new WebReferenceMERegistration.getMERegistration();
WebReferenceMERegistration.Locations _myLocation =
new WebReferenceMERegistration.Locations();
WebReferenceMERegistration.Locations[] _myLocations = null;
_myLocation.AddressLine1 = txtEmployerAddress1.Text;
_myLocation.AddressLine2 = txtEmployerAddress2.Text;
// more properties set here
_myLocations[0] = _myLocation;
_myMERegistration.Locations = _myLocations;
_Results = _myRegistrationService.getMERegistration(_myMERegistration);

int length = ...;
WebReferenceMERegistration.Locations[] _myLocations =
new WebReferenceMERegistration.Locations[length];

Related

Trouble splitting an array in #PostConstruct Method of my Kafka SpringBoot Application

I'm creating a Kafka Springboot listener that tracks the state of an object. I have the kafka portion working and am able to listen to the topics. I am using a Tree map to map a string key that is the topic to an object. The topic name actually contains some information that I want to use to initialize the object. My question is this ( I apologize, I'm not very familiar with SpringBoot).
In my Post Construct method, I have a string array that is coming in called locoTopics. I've verified that strings are coming in and they are of the form "ignore.ignore.mark.id". The issue I'm running into is that when I try to split the string in the Post Construct method it appears to return null even though the string definitely contains the "." expression. I say it appears, because the program appears to jump forward and skip several lines of code. To be precise, when I debug. It appears to go from the "String [] locoArray = locoTopics[i].split("\.");" line to my Object constructor immediately and skip all the steps in between. Then it appears to jump in and out of the loop. I'm very confused why this is. Is this something related to SpringBoot that is happening or am I missing something in my code? Any help would be greatly appreciated.
public class InitTrackerReceiver {
// instance variables
Map mapr = new TreeMap<String, Locomotive>();
String[] locoTopics;
public List<String> m_failureCodes;
// Moved Functionality to get loco ids into separate class, Locomotive IDs now
// gets locoids
#Autowired
public LocomotiveIDs locomotiveIDs;
//This is where loco objects will be instantiated
#PostConstruct
public void initializeLocomotives() {
// grab loco topic strings and separate into a string array
locoTopics = locomotiveIDs.getLocoString();
// Go through the loco topics from application.properties and create a Loco
// object with that string as identifier
for (int i = 0; i < locoTopics.length; i++) {
String [] locoArray = locoTopics[i].split("\\.");
String markString = locoArray[2];
String scacString = "name";
String idString = locoArray[3];
mapr.put(locoTopics[i], new Locomotive(locoTopics[i], markString, scacString, idString));
}
}
#Value("#{'${failure.init.messagefields}'.split(',')}")
List<String> typesToFail;
I figured I'd go ahead and follow up with the answer. I have no clue how this happened, but the code that was in Eclipse that was in the debugger was not the same code that was running. I don't know if this was a bug in EGIT or Eclipse. It became apparent when I ran a Maven clean and my project would no longer launch. Whenever I tried to debug, it would launch and say that it couldn't find the main class, which was my Spring application launch class. I did a Maven Build and that seemed to get everything in sync. Then the code started working as expected.

Not able to reference Java class from my report in BIRT

I am very new to BIRT. I am wokring on a BIRT project where I am trying to reference Java class inside script 'open' section but am unable to do so.
I do not get any errors but I am not able to see any data in my dataset preview.
Script - open
count = 0;
// create instance of
// the GetStockHistory class
gsh = new Packages.de.vogella.birt.stocks.daomock.StockDaoMock(); //cause of error somehow
//Load the List
stock = gsh.getStockValues("Java");
Script-Fetch
if(count < stock.size()){
row["columnDate"] = stock.get(count).getDate();
row["columnOpen"] = stock.get(count).getOpen();
row["columnHigh"] = stock.get(count).getHigh();
row["columnLow"] = stock.get(count).getLow();
row["columnClose"] = stock.get(count).getClose();
row["columnVolume"] = stock.get(count).getVolume();
count++;
return true;
}
return false;
StockDaoMock is a class which returns a dummy list of values.
Referring this blog BIRT sample app
Can anyone please help me here and let me know what am I doing wrong ?
Why can't I see any data in preview dataset. Is there a specific way in which I need to make reference to java classes because I am sure the error is somewhere in that part only. If I remove the reference part and just hardcode a string, then it is working fine and I can see it in the preview. Things mess up as soon as I refer a java class by importing it.
BIRT-4.8
EDIT---
even this inside my Script 'open' doesn't work
importPackage(Packages.de.vogella.birt.stocks.daomock);
gsh = new StockDaoMock();
BIRT does not use the java sources directly. You have to generate a JAR from your classes and add that JAR to your BIRT class path (Window / Preferences / Report Design / Classpath).

Using training made with python API as input to LabelImage module in java API?

I have a problem with java tensorflow API. I have run the training using the python tensorflow API, generating the files output_graph.pb and output_labels.txt. Now for some reason I want to use those files as input to the LabelImage module in java tensorflow API. I thought everything would have worked fine since that module wants exactly one .pb and one .txt. Nevertheless, when I run the module, I get this error:
2017-04-26 10:12:56.711402: W tensorflow/core/framework/op_def_util.cc:332] Op BatchNormWithGlobalNormalization is deprecated. It will cease to work in GraphDef version 9. Use tf.nn.batch_normalization().
Exception in thread "main" java.lang.IllegalArgumentException: No Operation named [input] in the Graph
at org.tensorflow.Session$Runner.operationByName(Session.java:343)
at org.tensorflow.Session$Runner.feed(Session.java:137)
at org.tensorflow.Session$Runner.feed(Session.java:126)
at it.zero11.LabelImage.executeInceptionGraph(LabelImage.java:115)
at it.zero11.LabelImage.main(LabelImage.java:68)
I would be very grateful if you help me finding where the problem is. Furthermore I want to ask you if there is a way to run the training from java tensorflow API, because that would make things easier.
To be more precise:
As a matter of fact, I do not use self-written code, at least for the relevant steps. All I have done is doing the training with this module, https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retraining/retrain.py, feeding it with the directory that contains the images divided among subdirectories according to their description. In particular, I think these are the lines that generate the outputs:
output_graph_def = graph_util.convert_variables_to_constants(
sess, graph.as_graph_def(), [FLAGS.final_tensor_name])
with gfile.FastGFile(FLAGS.output_graph, 'wb') as f:
f.write(output_graph_def.SerializeToString())
with gfile.FastGFile(FLAGS.output_labels, 'w') as f:
f.write('\n'.join(image_lists.keys()) + '\n')
Then, I give the outputs (one some_graph.pb and one some_labels.txt) as input to this java module: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/java/src/main/java/org/tensorflow/examples/LabelImage.java, replacing the default inputs. The error I get is the one reported above.
The model used by default in LabelImage.java is different that the model that is being retrained, so the names of inputs and output nodes do not align. Note that TensorFlow models are graphs and the arguments to feed() and fetch() are names of nodes in the graph. So you need to know the names appropriate for your model.
Looking at retrain.py, it seems that it has a node that takes the raw contents of a JPEG file as input (the node DecodeJpeg/contents) and produces the set of labels in the node final_result.
If that's the case, then you'd do something like the following in Java (and you don't need the bit that constructs a graph to normalize the image since that seems to be a part of the retrained model, so replace LabelImage.java:64 with something like:
try (Tensor image = Tensor.create(imageBytes);
Graph g = new Graph()) {
g.importGraphDef(graphDef);
try (Session s = new Session(g);
// Note the change to the name of the node and the fact
// that it is being provided the raw imageBytes as input
Tensor result = s.runner().feed("DecodeJpeg/contents", image).fetch("final_result").run().get(0)) {
final long[] rshape = result.shape();
if (result.numDimensions() != 2 || rshape[0] != 1) {
throw new RuntimeException(
String.format(
"Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s",
Arrays.toString(rshape)));
}
int nlabels = (int) rshape[1];
float[] probabilities = result.copyTo(new float[1][nlabels])[0];
// At this point nlabels = number of classes in your retrained model
DoSomethingWith(probabilities);
}
}
Hope that helps.
Regarding the "No operation" error, I was able to resolve that by using input and output layer names "Mul" and "final_result", respectively. See:
https://github.com/tensorflow/tensorflow/issues/2883

UFT/QTP: Count child objects in Java Internal Frame

I need to compare a string with all values of my text fields that are inside in a Java Internal Frame.
I already tried to use this code:
Dim getElement
Set getElement = Description.Create
getElement("class description").value = "text box"
'I tried different class names: "OracleTextField", "JavaEdit"
'getElement("micclass").value = "OracleTextField"
'getElement("micclass").value = "JavaEdit"
Set obj = Browser("xxxx").JavaApplet("Main").JavaInternalFrame("yyyy").ChildObjects(getElement)
total = obj.Count
' For loop goes here
total returns 0 all the time.
Can you tell me what I'm doing wrong?
If you need something more let me know.
I tried the following line and it works. Now i have total number of text fields available in Java internal frame.
getElement("to_class").value = "JavaEdit"
Following QTP documentation didn't help, but if you check your object properties inside your Object Repository you'll find all properties of each object. Instead of "micclass" try to use your property name. Mine was "to_class" with value "JavaEdit".
QTP Documentation explains why we should use "micclass" and differences between "micclass" and "Class Name". However none of them worked for me. I used "to_class" property and it works fine!
I'm working with UFT v12.02

How to add parameters to test cases in Test Plan using Java?

I've tried various things and googled multiple hours but couldn't find a solution to my problem.
I'm using the Quality Center OTA API via Com4j to let my programm communicate with QC.
It works pretty good, but now I've stumbed upon this problem:
I want to add new parameters to a test case in "Test Plan" using my programm.
If I used VB it would work somehow like this:
Dim supportParamTest As ISupportTestParameters
Set supportParamTest = TDConnection.TestFactory.Item(5)
Set testParamsFactory = supportParamTest.TestParameterFactory
Set parameter = testParamsFactory.AddItem(Null)
parameter.Name = name
parameter.Description = desc
parameter.Post
Set AddTestParameter = parameter
The important part is the call of AddItem() on the TestParameterFactory. It adds and returns a parameter that you then can give a name and description. In VB the AddItem-method is given Null as argument.
Using Java looks similar at first:
First I establish the connection and get the TestFactory (and the list of test cases).
QcConnect qc = new QcConnect(server, login, password, domain, project);
ITDConnection qcConnection = qc.getConnection();
ITestFactory qcTestFactory = qcConnection.testFactory().queryInterface(ITestFactory.class);
IList qcTestList = qcTestFactory.newList("");
qcTestList contains all tests from Test Plan.
ITest test = qcTestList.item(1);
ISupportTestParameters testParam = test.queryInterface(ISupportTestParameters.class);
ITestParameterFactory paramFac = testParam.testParameterFactory().queryInterface(ITestParameterFactory.class);
No problem so far. All the "casts" are successful.
Now I want to call the addItem-method on the TestParameterFactory, just like in VB.
Com4jObject com = paramFac.addItem(null);
This doesn't work. The addItem()-method always returns null. I've tried various arguments like a random String, a random Integer, the test case's ID, etc. Nothing works.
How do I use this method correctly in Java?
Or in general: How do I add parameters to existing test cases in Test Plan using Java?
Quick note: Adding test cases to Test Plan works very similar to adding parameters to this test cases. You also use a factory and a addItem-method. In VB you give null as parameter, but in Java you use a String (that's interpreted as the name of the test). But as I said, that does not work in here.
I have finally found the answer to this:
Com4jObject obj = iTestParameterFactory.addItem(new Variant(Variant.Type.VT_NULL));
iTestParameter = obj.queryInterface(ITestParameter.class);
iTestParameter.name("AAB");
iTestParameter.defaultValue("BBB");
iTestParameter.description("CCC");
iTestParameter.post();
Regards.
What you want to pass to AddItem is DBNull and not null.
In VB it's the same, but in Java & .NET it's not.
Not sure how DBNull is exposed using Com4J.
Read more about this at this site.
//C# code snippet -> You have to use DBNull.Value instead of null
//Add new parameter and assign values
TestParameter newParam =(TestParameter)tParamFactory.AddItem(DBNull.Value);
newParam.Name = "ParamNew";
newParam.DefaultValue = "DefaultValue";
newParam.Description = "AnyDesc";
newParam.Post();

Categories

Resources