I have a Java code which needs a proxy value to run. That proxy value changes with the environment. So I'd like to make it as variable which I can pass from shell, so the java code remains environment agnostic. Here's the snippet of the java code. As you can see I am trying to make the web-proxyapp.xxxxx-dns.com and port number as a variable that I can pass from shell or the Java code picks it up automatically from Linux environment variables.
import io.restassured.response.Response;
import step_definitions.StepDefinitions;
private Response getCyaraResponse(String cyaraService) {
try {
RestAssured.useRelaxedHTTPSValidation();
RestAssured.proxy("web-proxyapp.xxxxx-dns.com", 3128);
log.debug("Get URL: " + baseUrl + accountNum + cyaraService);
Response actualResponse = given().headers("Authorization", keyToken)
.get(baseUrl + accountNum + cyaraService);
return actualResponse;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I am not an expert in Java so would appreciate any suggestions. Thanks in advance.
Related
I'm wondering how I can write test, that will run in sonar, that will test the following method?
It seems almost impossible as sonar won't be able to actually get an azure subscription, so that will all have to be mocked.
Any help or pointers would be appreciated.
public AzureMetricRecords getVmMetrics(String azureSubscriptionId, String workspace, String vm, String metric, AggregationType aggregationType) {
Azure azure = getAzure(azureSubscriptionId);
String vmId = "/subscriptions/" + azureSubscriptionId + "/resourceGroups/" + workspace + "-" + vm +
"/providers/Microsoft.Compute/virtualMachines/" + vm;
VirtualMachine azureVm = azure.virtualMachines().getByResourceGroup(workspace + "-" + vm, vm);
if (azureVm != null) {
Map<String,MetricDefinition> metricsIndex = new HashMap<>();
List<MetricDefinition> definitions = azure.metricDefinitions().listByResource(vmId);
for (MetricDefinition d : definitions) {
metricsIndex.put(d.name().value(), d);
}
if (!metricsIndex.containsKey(metric)) {
throw new ValidationException("metric not found");
}
return getMetrics(DateTime.now(), metricsIndex.get(metric), aggregationType);
} else {
LOGGER.warn("getVmMetrics: Vm NOT found");
AzureMetricRecords metricRecords = new AzureMetricRecords();
metricRecords.setMetric(metric);
metricRecords.setAggregation(aggregationType.name());
return metricRecords;
}
}
When you can not get a real object for your test, you use mocks (or stubs).
In your example, as I can see, you have to mock getAzure() method, so it returns a mock of Azure type. This mock, in order, has to provide proper implementations for this
azure.virtualMachines().getByResourceGroup(workspace + "-" + vm, vm);
and this
azure.metricDefinitions().listByResource(vmId);
methods.
For mocking you can use Mockito framework, which provides a usefull API for creating and mocking objects and methods (using code or annotations).
I'm trying to connect to SAP ECC 6.0 using JCo. I'm following this tutorial. However, there is a Note saying:
For this example the destination configuration is stored in a file that is called by the program. In practice you should avoid this for security reasons.
And that is reasonable and understood. But, there is no explenation how to set up secure destination provider.
I found solution in this thread that created custom implementation of DestinationDataProvider and that works on my local machine. But when I deploy it on Portal I get an error saying that there is already registered DestinationDataProvider.
So my question is:
How to store destination data in SAP Java EE application?
Here is my code to further clarify what I'm trying to do.
public static void main(String... args) throws JCoException {
CustomDestinationProviderMap provider = new CustomDestinationProviderMap();
com.sap.conn.jco.ext.Environment.registerDestinationDataProvider(provider);
Properties connectProperties = new Properties();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "host.sap.my.domain.com");
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "00");
connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "100");
connectProperties.setProperty(DestinationDataProvider.JCO_USER, "user");
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "password");
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "en");
provider.addDestination(DESTINATION_NAME1, connectProperties);
connect();
}
public static void connect() throws JCoException {
String FUNCTION_NAME = "BAPI_EMPLOYEE_GETDATA";
JCoDestination destination = JCoDestinationManager.getDestination(DESTINATION_NAME1);
JCoContext.begin(destination);
JCoFunction function = destination.getRepository().getFunction(FUNCTION_NAME);
if (function == null) {
throw new RuntimeException(FUNCTION_NAME + " not found in SAP.");
}
//function.getImportParameterList().setValue("EMPLOYEE_ID", "48");
function.getImportParameterList().setValue("FSTNAME_M", "ANAKIN");
function.getImportParameterList().setValue("LASTNAME_M", "SKYWALKER");
try {
function.execute(destination);
} catch (AbapException e) {
System.out.println(e.toString());
return;
}
JCoTable table = function.getTableParameterList().getTable("PERSONAL_DATA");
for (int i = 0; i < table.getNumRows(); i++) {
table.setRow(i);
System.out.println(table.getString("PERNO") + '\t' + table.getString("FIRSTNAME") + '\t' + table.getString("LAST_NAME")
+'\t' + table.getString("BIRTHDATE")+'\t' + table.getString("GENDER"));
}
JCoContext.end(destination);
}
Ok, so I got this up and going and thought I'd share my research.
You need to add your own destination in Portal. To achieve that you need to go to NetWeaver Administrator, located at: host:port/nwa. So it'll be something like sapportal.your.domain.com:50000/nwa.
Then you go to Configuration-> Infrastructure-> Destinations and add your destination there. You can leave empty most of the fields like Message Server. The important part is Destination name as it is how you will retrieve it and destination type which should be set to RFC Destination in my case. Try pinging your newly created destination to check if its up and going.
Finally you should be able to get destination by simply calling: JCoDestination destination = JCoDestinationManager.getDestination(DESTINATION_NAME); as it is added to your Portal environment and managed from there.
Take a look at the CustomDestinationDataProvider in the JCo examples of the Jco connector download. The important parts are:
static class MyDestinationDataProvider implements DestinationDataProvider
...
com.sap.conn.jco.ext.Environment.registerDestinationDataProvider(new MyDestinationDataProvider());
Then you can simply do:
instance = JCoDestinationManager.getDestination(DESTINATION_NAME);
Btw. you may also want to check out http://hibersap.org/ as they provide nice ways to store the config as well.
I have a Java program that calls an Applescript file to run, and returns information back to Java. However, I need to also pass some arguments to the Applescript file. The relevant portion of the Java file:
public static void scriptRunner(String[] args) {
// Connect to the database.
ConnectionManager.getInstance().setDBType(DBType.MYSQL);
// Prepare the AppleScript file to be executed.
String homeFolder = System.getenv("HOME");
File scriptFile = new File(homeFolder + "/Documents/Output--Test.applescript");
InputStream scriptStream = null;
try {
scriptStream = FileUtils.openInputStream(scriptFile);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Could not find the Output AppleScript file. Please notify Chris McGee", "File not found", JOptionPane.ERROR_MESSAGE);
ConnectionManager.getInstance().close();
System.exit(1);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(scriptStream));
// These two lines prepare the scripting engine, ready to run the script.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("AppleScript");
// Add the parameters to the engine so they will be passed to the script.
engine.put("javaOrderNum", args[0]);
engine.put("javaShipDate", args[1]);
engine.put("javaInitials", args[2]);
engine.put("javaOverruns", args[3]);
// Run the script and evaluate the result.
log.trace("Run the script and evaluate the result.");
Object result = null;
try {
result = engine.eval(bufferedReader); // Run the script and place the result into an abstract object.
} catch (ScriptException e) {
JOptionPane.showMessageDialog(null, "Either an error occurred with the Output script or the user cancelled it.", "Script error / cancel", JOptionPane.INFORMATION_MESSAGE);
ConnectionManager.getInstance().close();
System.exit(1);
}
log.debug(result); // Check that we received the correct information back from the script.
log.debug("");
.
.
.
Sadly, the engine.put lines, as suggested from a forum I read during my searches to get this problem solved, don't seem to work. The AppleScript file:
-- Get variables passed in
set jOrderNum to item 1 of arguments
set jShipDate to item 2 of arguments
set jInitials to item 3 of arguments
set jOverruns to item 4 of arguments
-- Set the correct folder variable
if (folderExists(POSIX path of "/Volumes/Users/Scripts/")) then
set server_prefix to "/Volumes/Users/Scripts/"
else if (folderExists(POSIX path of "/centralserver/Users/Scripts/")) then
set server_prefix to "/centralserver/Users/Scripts/"
else
display alert "Please connect to the central server, then try again.
If you have already done so, please let Chris McGee know."
end if
with timeout of (30 * 60) seconds
tell application "Adobe InDesign CS6"
set myJavaScript to server_prefix & "sky-artdept/Test/Output.jsx"
set myResult to do script myJavaScript with arguments {jOrderNum, jShipDate, jInitials, jOverruns} language javascript
return myResult
end tell
end timeout
on folderExists(posixPath)
return ((do shell script "if test -e " & quoted form of posixPath & "; then
echo 1;
else
echo 0;
fi") as integer) as boolean
end folderExists
I am given an error that the variable arguments is not defined. What can I try next?
I can't help with the javascript running the applescript. But, you applescript code is missing a declaration. You're asking for "item 1 of arguments" but you never define the variable arguments.
When the script is not inside any handler, it is implicit that it is inside a run() handler. And, since you're needing to pass arguments on run, you should try wrapping your script, minus the on folderExists() handler, inside a run handler that includes the arguments declaration.
on run(arguments)
-- Get variables passed in
set jOrderNum to item 1 of arguments
set jShipDate to item 2 of arguments
…
end timeout
end run
on folderExists(posixPath)
…
end folderExists
I have a class which takes in various system parameters and prints them out:
public class Test_Class {
public static void main(String[] args){
String fooA = System.getProperty("fooA");
String fooB = System.getProperty("fooB");
String fooC = System.getProperty("fooC");
System.out.println("System Properties:\n"+fooA+"\n"+foob+"\n"+fooC+"\n");
}
}
Then, using IntelliJ, pass in the VM Parameters as such:
-DfooA="StringA" -DfooB="StringB" -DfooC="String C"
Upon running my program I get the following output:
System Properties:
StringA
StringB
String C
Now, if I run the same program through a UNIX server by running the following command:
java -DfooA="StringA" -DfooB="StringB" -DfooC="String C" com.foo.fooUtil.Test_Class
I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: C
I have tried a bunch of different ways to pass in fooC, such as -DfooC=\"String C\", -DfooC='String C', -DfooC=\'String C\', basically any idea that came to mind. I have done some research and have been unable to find any solid solution.
For reference, I found the following link online where another person seems to have the same issue but, unfortunately, none of the suggestions work.
http://www.unix.com/shell-programming-scripting/157761-issue-spaces-java-command-line-options.html
How can I pass in a System Parameter with spaces in UNIX? Thank you.
Here is my approach: Why not use a .properties file for storing the system properties instead of passing them through command line? You can access the properties using:
Properties properties = new Properties();
try {
properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
...
}
And you may iterate as:
for(String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
Hope that helps!!!
I am trying to connect Java code to mySQL. Here is the error that I got. I dont understand why no driver is found since I have put the connector jar at the classpath.
Class Not Found Exception:
No suitable driver found for jdbc:mysql://localhost/hpdata?user=root&password=12
3456
Exception in thread "main" java.lang.NullPointerException
at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.open(FeatureSpe
cRDB.java:122)
at edu.indiana.iucbrf.feature.featurespec.FeatureSpecRDB.<init>(FeatureS
pecRDB.java:66)
at edu.indiana.iucbrf.domain.componentfactory.RDBComponentFactory.constr
uctProblemFeatureSpecCollection(RDBComponentFactory.java:112)
at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:239)
at edu.indiana.iucbrf.domain.Domain.<init>(Domain.java:197)
at edu.indiana.iucbrf.examples.honeypotRDBTemplate.HDomainRDB.<in
it>(HDomainRDB.java:56)
at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.set
upDomain(HSystemRDB.java:198)
at edu.indiana.iucbrf.examples.hRDBTemplate.HSystemRDB.<in
it>(HSystemRDB.java:131)
at edu.indiana.iucbrf.examples.hRDBTemplate.HTestClassRDB.
main(HTestClassRDB.java:65)
Here is my code :
private static void flush() {
Class.forName("com.mysql.jdbc.Driver").newInstance();
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hpdata?user=root&password=123456");
} catch (Exception e) {
System.out.println("Class Not Found Exception:");
System.out.println(e.getMessage());
}
try {
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
String serverName = "localhost";
String mydatabase = "hpdata";
String url = "jdbc:mysql :// " + serverName + "/" + mydatabase;
String username = "root";
String password = "123456";
connection = DriverManager.getConnection(url, username, password);
} catch(Exception e) {
// appropriate action
}
Try loading the driver before using it by incorporating this line.
Class.forName("com.mysql.jdbc.Driver")
Make sure mysql-connector-java-<version-number>-bin.jar is in your classpath. If you don't have it, you can download it here.
You're assuming that you've set CLASSPATH properly. Please explain how you're doing that so we can tell you whether it's correct or not.
If you've set an environment variable named CLASSPATH, that's almost certainly wrong.
It makes a difference if your app is for the web or desktop. Please tell us which is true for you.
UPDATE:
The right way to set CLASSPATH for a desktop app is to use the -classpath option on the JVM when you run:
java -classpath .;<paths-to-your-JARs-separated-by-semi-colons>;<paths-to-the-root-of-package-trees> foo.YourCode
After setting CLASSPATH please copy mysql-connector-java-5.1.16-bin into these folders:
C:\Program Files\Java\jdk1.6.0_18\jre\lib\ext
and
C:\Program Files\Java\jre6\lib\ext