I'm wondering if it's possible to use ADO Errors in Java.
I'm looking at some ASP code that uses ADO for Errors, I believe I've converted it to JAVA.
Is it possible to even do or is there better error handling in Java?
I'm familiar with using a try catch block, but I'm not sure how to incorporate all the errors into one.
There are about 10 different errors, I cut them out for this question and just left a few errors for this question
Snippet of ASP Code:
If Err.number <> 0 Then
Response.Write("<!-- ADO Errors Begin -->" & vbCrLf)
For each objError in con_duns_sdo2.Errors
Response.Write("<!-- ADO Error.Number = " & objError.Number & "-->" & vbCrLf)
Response.Write("<!-- ADO Error.Description = " & objError.Description & "-->" & vbCrLf)
Next
Response.Write("<!-- ADO Errors End -->" & vbCrLf)
Response.Write("<!-- VBScript Errors Begin -->" & vbCrLf)
Snippet of Java that I'm trying to convert:
for (objError : con_currency_sdo) {
if (con_currency_sdo.Errors == "true") {
System.out.println("ADO Error.Number" + objError.Number + "\r\n");
System.out.println("ADO Error.Description" + objError.Description + "\r\n");
}else{
System.out.println("ADO Errors End" + "\r\n");
System.out.println("VBScript Errors Begin" + "\r\n");
}
}
According to Microsoft, ADO.NET is a set of classes that expose data access services for .NET Framework programmers. ADO.NET provides a rich set of components for creating distributed, data-sharing applications. It is an integral part of the .NET Framework, providing access to relational, XML, and application data. ADO.NET supports a variety of development needs, including the creation of front-end database clients and middle-tier business objects used by applications, tools, languages, or Internet browsers.
Given that, the answer is no. Java does not and cannot natively integrate with any .NET Framework (there are third-party commercial libraries that enable it, but they're typically non-trivial to work with). Instead Java uses JDBC to perform database operations in a vendor neutral cross-platform way.
Related
I am building an Android application in Android studio with Java. I want to use Speech to text and Text to speech and some Machine Learning based python programs that I had already written.
Is it possible to do this? What is the technology stack that I need to accomplish this?
I came across various solutions like using sl4A, Jython, QPython and running the python code on the server.I have also gone through the following but I haven't found a solution yet
Execute python script from android App in Java
How to execute Python script from Java code in Android
Execute python script from android App in Java
Please explain with an example. As an example if I want to use the following python code (Speech to Text conversion using Google Speech recognition API) to run in my android app:
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as src:
print("speak....")
audio = r.listen(src, 2)
print("over")
try:
print("you said: "+r.recognize_google(audio))
except:
print("cannot recognize")
What steps am I supposed to follow? What is the best way to achieve it?
Thank you in advance.
EDIT 1: Can it be achieved using azure services?
I've been using JEP as a bridge between java and python, I've never actually tried this on android apps, only webapps. (in the FAQS of the project they state that it could work)
private RunOutputModel run(RunInputModel model, String path) throws Exception {
RunOutputModel retVal = new RunOutputModel();
try (SharedInterpreter jep = new SharedInterpreter()) {
jep.eval("import sys");
jep.eval("sys.path.append('" + path + "')");
jep.eval("import master_main");
jep.set("well", model.getWell());
jep.set("startDate", model.getStartDate());
jep.set("endDate", model.getEndDate());
//other vars
jep.eval("objClass = master_main.master()");
jep.eval("x = objClass.main(path, well, startDate, endDate,/*vars*/)");
Object result1 = jep.getValue("x");
//manager result
}
} catch (Exception e) {
retVal.setStatus(e.getMessage());
Utils.log("error", e.getMessage(), path);
}
return retVal;
}
And here's python:
class master:
def __init__(self):
self.SETVARIABLES = ''
def main(self, path, well, startDate, endDate):
#stuff
By searching I've found this, they even have project examples of mixed source code app (both python and java).
I want to use Protractor on Java and not on Node.js. Is it possible to use Protractor with Java or Python? We do not want to add another technology for testing and want to use existing technologies.
Unfortunately you don't have much of a choice in the matter, as Protractor is a JavaScript Testing framework for AngularJS, it is distributed via Node.js.
We do not want to add another technology for testing and want to use existing technologies.
Protractor is customized for angularJS applications. So if your application was created using AngularJS, Protractor will help as it has inbuilt support for AngularJS page load and actions.
If your application is not built on top of Angular, you can use Selenium WebDriver on top of any other languages you prefer.
Selenium provides users with documentation on using Python as a medium to write tests, read more about this here.
Protractor is a JS library so you can't run it in Java and testing Angular apps without Protractor is difficult because your tests code needs to wait for Angular processes to complete before interactions like clicking occur.
Fortunately, Angular has made it easy to identify when it's done processing.
There is a JS function that takes a callback and will notify you once the Angular is ready.
angular.getTestability("body").whenStable(callback);
NOTE: That this works with Angular 1.4.8. Some other versions of Angular have a different method that is similar.
You can invoke the testability method from your Java test code using the following simple method or something similar.
private void waitForAngular() {
final String script = "var callback = arguments[arguments.length - 1];\n" +
"var rootSelector = \'body\';\n" +
"var el = document.querySelector(rootSelector);\n" +
"\n" +
"try {\n" +
" if (angular) {\n" +
" window.angular.getTestability(el).whenStable(callback);\n" +
" }\n" +
" else {\n" +
" callback();\n" +
" }\n" +
"} catch (err) {\n" +
" callback(err.message);\n" +
"}";
((JavascriptExecutor) driver).executeAsyncScript(script, new Object[0]);
}
Call waitForAngular() before interacting with the driver with a method like click.
You may want a different rootSelector from 'body' and you may want to throw an error if angular doesn't exist but this works well for my needs.
Protractor provides other selectors which may make testing an Angular app easier but personally I use ID and Class selectors so I don't need them.
There is already a library in Java for automating Angular stuffs. Its built based on Protractor called "ngWebDriver"
As of 2017, I have found these Protractor libraries for Java:
jProtractor - Development is somewhat inactive but I have tested it to work. Click here for more details.
ngWebDriver - Developed by Paul Hammant (co-creator of Selenium). Currently in active development with good documentation.
Code Snippet:
<input type="text" ng-model="startBalance" placeholder="Enter your current balance" class="ng-pristine ng-valid">
// jProtractor
WebElement startBalanceField = driver.findElement(NgBy.model("startBalance"));
// ngWebDriver
WebElement startBalanceField = driver.findElement(ByAngular.model("startBalance"));
To add something to Tom's answer above, you can even test non-angular based apps/websites with Protractor. But there is still no way, you can write Protractor tests using Java or Python as Protractor's core is built on Javascript(node.js) and is purely Javascript. Hope it helps.
The best way to use protractor is , have protractor tests separately written in javascript, and call those tests from java/python when ever required. Thats what we are currently doing!
Hi i formulated a linear programing problem using java
and i want to send it to be solved by lpsolve without the need to create each constraint seperatlly.
i want to send the entire block (which if i insert it to the ide works well) and get a result
so basically instead of using something like
problem.strAddConstraint("", LpSolve.EQ, 9);
problem.strAddConstraint("", LpSolve.LE, 5);
i want to just send as one string
min: 0*x11 + 0*x12 + 0*x13
x11 + x12 + x13= 9;
x12 + x12<5;
can it be done if so how?
LpSolve supports LP files as well as MPS files. Everything is thoroughly detailed in the API documentation (see http://lpsolve.sourceforge.net/5.5/).
You can do your job like this in java :
lp = LpSolve.readLP("model.lp", NORMAL, "test model");
LpSolve.solve(lp)
What is sad with file based approaches is that you will not be able to use warm start features. I would not suggest you to use such approach if you want to optimize successive similar problems.
Cheers
a general question:
We are launching a new ITSM Toolsuite in our company called ServiceNow.
ServiceNow offers a lot of nice out-of-the-box Webservices.
Currenty we are implementing some interfaces to other interal systems and we use these Webservices to consume data of Servicenow.
How we did it in PHP:
<?php
$credentials = array('login'=>'user', 'password'=>'pass');
$client = new SoapClient("https://blah.com/incident.do?WSDL", $credentials);
$params = array('param1' => 'value1', 'param1' => 'value1');
$result = $client->__soapCall('getRecords', array('parameters' => $params));
// result array stored in $result->getRecordsResult
?>
And thats it! 5 minutes of work, Beautiful and simple - from my point of view.
Ok and now the same in Java:
I did some research and it seems everbody is using Apache Axis2 for consuming Webservices in Java. So I decided to go down that road.
Install Apache Axis
open cygwin or cmd and generate Classes from WSDL.. WTF? what for?
$ ./wsdl2java.sh -uri https://blah.com/incident.do?WSDL
copy generated classes to Java Project in Eclipse.
Use this classes:
ServiceNow_incidentStub proxy = new ServiceNow_incidentStub();
proxy._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
ServiceNow_incidentStub.GetRecords defectsGetRecords = new ServiceNow_incidentStub.GetRecords();
ServiceNow_incidentStub.GetRecordsResponse defectsResult = new ServiceNow_incidentStub.GetRecordsResponse();
proxy._getServiceClient().getOptions().setManageSession(true);
HttpTransportProperties.Authenticator basicAuthentication = new HttpTransportProperties.Authenticator();
basicAuthentication.setUsername("user");
basicAuthentication.setPassword("pass");
proxy._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, basicAuthentication);
defectsResult = proxy.getRecords(defectsGetRecords);
com.service_now.www.ServiceNow_incidentStub.GetRecordsResult_type0[] defects = defectsResult.getGetRecordsResult();
for (int j=0; j < defects.length; j++) {
// do something
}
Its working but I think this way is very complicated..
everytime something in the wsdl changes - i must recompile them with axis.
There is no way to configure something globally like Soap-endpoint or something like that.
Is there an easier way in Java to consume SOAP with a WSDL??
First off: I completely agree. I do quite a bit of work with Web Services and ServiceNow, and using Java and/Or .Net is quite different than using a scripted language (I usually use Perl for scripts). The inherent issue comes into the fact that a WSDL should not be changing that often, especially in production. The idea in Java and .Net is that you get these stub classes to get compile time error checking.
If your currently in a Ph1 and haven't deployed Prod yet, then you should really look into how often that WSDL will be changing. Then make your decision from there on which technology to use. The nice thing is that even if the WSDL changes, posting data to the instance - almost all of the fields are optional. So if a new field is added it's not a big deal. The issue comes in when data is returned (most of the time) because many times java and .net will throw an exception if the returned XML is not in the structure it is expecting.
One thing that many people do is setup Modules as CI's in the CMDB and maintain their ServiceNow instance through the Change Request module. That way your java application will be a downstream CI to whatever module/table you are querying, and when a CR is put in to modify that table, it will be known immediately that there will be an impact on your internal application as well.
Unfortunately you are right though, that is a trade off with the different languages and from my experience there is very little we can do to change that.
One thing I forgot to add, another option for you is to use the JSON service instead. That will allow you to make raw requests to the SNC instance then use a JSON parser to parse that data for you "on the fly" so to speak. It takes away the compile time checking but also takes away many of the flaws of the SOAP system.
IF you are using maven, try using this plugin.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>axistools-maven-plugin</artifactId>
<version>1.4</version>
<configuration>
<urls>
<url>https://blah.com/incident.do?WSDL</url>
</urls>
<packageSpace>your.destination.package</packageSpace>
<serverSide>true</serverSide>
<outputDirectory>src/main/java</outputDirectory>
</configuration>
<executions>
<execution>
<goals><goal>wsdl2java</goal></goals>
</execution>
</executions>
</plugin>
I was also trying to access ServiceNow from Java using Eclipse, and it seemed to me that the Axis2 approach was overly restrictive given how ServiceNow designed their API, so I wrote my own package to generate SOAP calls dynamically using JDOM. Here is an example of what the code looks like:
Instance instance = new Instance("https://blah.service-now.com", "username", "password");
GlideFilter filter = new GlideFilter("category=network^active=true");
GlideRecordIterator iter = instance.table("incident").
bulkFetcher().setFilter(filter).getAllRecords().iterator();
while (iter.hasNext()) {
GlideRecord rec = iter.next();
System.out.println(
rec.getField("number") + " " + rec.getField("short_description"));
}
A couple of things about this code:
I use run-time validation rather than build-time validation. If you mistakenly type getField("shortdescription") the code throws an InvalidFieldNameException.
Queries are not bound by ServiceNow's normal 250 record limit because the BulkFetcher loops internally making as many Web Service calls as necessary to retrieve all the data.
The package source code is at https://sourceforge.net/projects/servicenowpump/
I consume lots of Soap services with PHP in the company I work for, and I would always suggest generating classes for the request and response data structure. Otherwise you will easily get lost - PHP does not preserve any remains of the original XML structure, it will all be converted to arrays and stdClass objects.
Getting classes created from the WSDL description is not that easy in PHP, as there are only a few scripts that do this - and they all have their shortcomings when it comes to WSDL files that make use of the more obscure parts of the SOAP standard. After that, you somehow have to make these classes available to your PHP script. If this is hard for you, it is a sign of a not too well organized code base. With the autoloading feature it works like a charm.
But yes, this step is entirely optional for PHP. If using only one Soap service, it'll probably make no difference.
I want to grab a hardware ID with a java webapplet. Is this doable? If not, is there any web language I can do this with to help with a more secure authentication?
You can use any one approach as described below:
Use Signed Java Applet to load some JNI compatible shared library and get your job done.
public NativeHelloApplet() {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
System.load(System.getProperty("user.home") +"/libhello.so");
displayHelloWorld();
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
});
}
Use VB Script embedded in your web-page. Here is a sample:
Use the Win32_SystemEnclosure class, and the properties SerialNumber and SMBIOSAssetTag.
strComputer = "." Set objWMIService =
GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\"
_
& strComputer & "\root\cimv2") Set colSMBIOS = objWMIService.ExecQuery _
("Select * from Win32_SystemEnclosure") For Each
objSMBIOS in colSMBIOS
Wscript.Echo "Part Number: " & objSMBIOS.PartNumber
Wscript.Echo "Serial Number: " _
& objSMBIOS.SerialNumber
Wscript.Echo "Asset Tag: " _
& objSMBIOS.SMBIOSAssetTag Next
Design plug-in for every browser of your interest and collect data using them. MS uses this for Authenticated Software checking with FireFox.
Feel comfortable to let me know if you want to know more. That case, I shall write on my blog at http://puspendu.wordpress.com/
You can get a general idea of What Applets Can and Cannot Do, including access to certain system properties. In particular, unsigned applets "cannot load native libraries," which would probably be required for any kind of hardware identification.
If not, is there any web language I can do this with to help with a more secure authentication?
The issue is not strength of authentication. Rather it is whether a web language running in the user's browser should allow remote web services to access the user's hardware, files, etc. The answer is an emphatic "NO IT SHOULD NOT" ... unless the user implicitly grants permission by either installing a trusted plugin or a certificate.