I am trying to make a connection with the sap systems and I have all the connection properties which are required in order to do so.
I am trying my best but I am facing some issues I have no idea how to resolve.
All I need is a simple code example by which I will be able to integrate my java app with the sap systems.
I have gone through some websites but could not find a solution for making the connection with the sap system.
I am trying with the below code but i do not know that what to write inside createDataFile method.
import com.sap.conn.jco.ext.DestinationDataProvider;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoDestinationManager;
import java.util.Properties;
public class TestMySAP {
public static void main(String[] args) {
// This will create a file called mySAPSystem.jcoDestination
String DESTINATION_NAME1 = "mySAPSystem";
Properties connectProperties = new Properties();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "10.129.19.151"); //host
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "00"); //system number
connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "442"); //client number
connectProperties.setProperty(DestinationDataProvider.JCO_USER, "MPOSRFC");
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "123456");
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "en");
createDataFile(DESTINATION_NAME1, connectProperties);
// This will use that destination file to connect to SAP
try {
JCoDestination destination = JCoDestinationManager.getDestination("mySAPSystem");
System.out.println("Attributes:");
System.out.println(destination.getAttributes());
System.out.println();
destination.ping();
} catch (JCoException e){
e.printStackTrace();
}
}
}
Related to the second part of your question in the comments, for BAPI functions you can try the following snippet:
public static void getCompanyCodes throws JCoException {
JCoDestination destination = JCoDestinationManager.getDestination(DESTINATION_NAME1);
JCoFunction function = destination.getRepository().getFunction("BAPI_COMPANYCODE_GETLIST");
if (function == null)
throw new RuntimeException("Function not found in SAP.");
try {
function.execute(destination);
} catch (AbapException e) {
System.out.println(e.toString());
return;
}
JCoStructure returnStructure = function.getExportParameterList().getStructure("RETURN");
if (!(returnStructure.getString("TYPE").equals("") || returnStructure.getString("TYPE").equals("S"))) {
throw new RuntimeException(returnStructure.getString("MESSAGE"));
}
JCoTable codes = function.getTableParameterList().getTable("COMPANYCODE_LIST");
for (int i = 0; i < codes.getNumRows(); i++) {
codes.setRow(i);
System.out.println(codes.getString("COMP_CODE") + '\t' + codes.getString("COMP_NAME"));
}
}
You can find a list of BAPI functions here: http://www.sapnet.ru/m/list_BAPI.html
Related
I have a problem in a class I wrote. The purpose of the class is to add/remove/update for the applicationResource.properties files which the <spring:message code="key" /> uses to provide bilingual support to the website. Manually interacting with the properties files works fine, but I had a greater need and so I built in a way to allow changes to be done from the database. This has given me a very dynamic and flexible system that I can work from.
However, there is a problem. At some point after even a single change using this, the French characters end up getting changed. Such as Déconnexion becoming Déconnexion. When looked at in notepad++ its first Déconnexion and then corrupted to D\u00C3\u00A9connexion. This example was part of the original properties file.
The original (not temp) properties files have the text file encoding set to other: UTF-8. The Project properties text file encoding is set to inherited from container (Cp1252). I tried changing to Other: UTF-8 with no change.
So my question(s) is, what is causing the corruption to my French characters and how can I fix it? I have provided the complete class below.
Update: After the assistance from StephaneM in her answer I was able to track down exactly what is causing the corruption, but have not fixed it yet. The loadProperties() function in the AR Class. As soon as the temp AP files are loaded the French characters are corrupted. This makes me suspect the original process which creates the temp AP files is using a different encoding. So I will have to track it down.
package pojo;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
/*
* Purpose of this class is to handle all the ApplicationResource(_fr).properties interactions
* so that there is one unified location handling this, instead of code duplication.
*/
public class AR{
public final String en_path = "/ApplicationResources.properties";
public final String fr_path = "/ApplicationResources_fr.properties";
private Properties en_prop = null;
private Properties fr_prop = null;
public AR()
{
loadProperties();
}
private void loadProperties()
{
InputStream en_is = null;
InputStream fr_is = null;
try {
this.en_prop = new Properties();
this.fr_prop = new Properties();
en_is = this.getClass().getResourceAsStream(en_path);
fr_is = this.getClass().getResourceAsStream(fr_path);
en_prop.load(en_is);
fr_prop.load(fr_is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean keyExist(String mykey, String mypath) //deprecated due to better code/method
{
Properties test_prop = null;
InputStream is = null;
try {
test_prop = new Properties();
is = this.getClass().getResourceAsStream(mypath);
test_prop.load(is);
Set<Object> keys = test_prop.keySet();
for(Object k:keys) {
String key = (String)k;
//System.out.print(key + " ");
if(key.equals(mykey))
{
return true;
}
}
//System.out.println(" ");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public boolean en_keyExist(String mykey)
{
//searches english file
loadProperties();
return en_prop.containsKey(mykey);
//return keyExist(mykey, en_path); //original method
}
public boolean fr_keyExist(String mykey)
{
//searches french file
loadProperties();
return fr_prop.containsKey(mykey);
//return keyExist(mykey, fr_path); //original method
}
public boolean en_fr_keyExist(String mykey)
{
//searches both english and french files
loadProperties();
return (en_prop.containsKey(mykey) && fr_prop.containsKey(mykey));
//return (keyExist(mykey, en_path) && keyExist(mykey, fr_path)); //original method
}
public String en_returnProperty(String mykey)
{
//returns null if key does not exist
loadProperties();
return this.en_prop.getProperty(mykey);
}
public String fr_returnProperty(String mykey)
{
//returns null if key does not exist
loadProperties();
return this.fr_prop.getProperty(mykey);
}
public void appendProperty(Properties new_en_prop,Properties new_fr_prop)
{
//note: during a test, setProperty (used in populating the properties) does not allow duplicates, it overwrites.
//So, load the existing properties, and for each new property add it
loadProperties();
for(Object key : new_en_prop.keySet())
{
en_prop.setProperty((String)key, new_en_prop.getProperty((String)key));
}
try (OutputStream en_os = new FileOutputStream(getClass().getResource(en_path).getFile(),false);)
{
en_prop.store(en_os, null);
} catch (IOException e) {
e.printStackTrace();
}
for(Object key : new_fr_prop.keySet())
{
fr_prop.setProperty((String)key, new_fr_prop.getProperty((String)key));
}
try (OutputStream fr_os = new FileOutputStream(getClass().getResource(fr_path).getFile(),false);)
{
fr_prop.store(fr_os, null);
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean appendProperty(String mykey, String en_val, String fr_val) //appears to have timing error due to only saving last value
//due to timing error this function is only suitable for single additions
//due to the timing error, tried returning boolean to have it finished but was not successful
//setting the class variables to static did not solve the timing issue
{
loadProperties();
en_prop.setProperty(mykey, en_val);
try (OutputStream en_os = new FileOutputStream(getClass().getResource(en_path).getFile(),false);)
{
en_prop.store(en_os, null);
} catch (IOException e) {
e.printStackTrace();
}
fr_prop.setProperty(mykey, fr_val);
try (OutputStream fr_os = new FileOutputStream(getClass().getResource(fr_path).getFile(),false);)
{
fr_prop.store(fr_os, null);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public void en_setProperty(String mykey, String en_val)
//suspected timing issue, use only for singular changes
{
loadProperties();
en_prop.setProperty(mykey, en_val);
try (OutputStream en_os = new FileOutputStream(getClass().getResource(en_path).getFile(),false);)
{
en_prop.store(en_os, null);
} catch (IOException e) {
e.printStackTrace();
}
}
public void fr_setProperty(String mykey, String fr_val)
//suspected timing issue, use only for singular changes
{
loadProperties();
fr_prop.setProperty(mykey, fr_val);
try (OutputStream fr_os = new FileOutputStream(getClass().getResource(fr_path).getFile(),false);)
{
fr_prop.store(fr_os, null);
} catch (IOException e) {
e.printStackTrace();
}
}
public void compareResources()
{
Properties new_en = new Properties();
Properties new_fr = new Properties();
for(Object key : en_prop.keySet())
{
new_en.setProperty((String)key, en_prop.getProperty((String)key));
}
for(Object key : fr_prop.keySet())
{
new_fr.setProperty((String)key, fr_prop.getProperty((String)key));
}
Properties temp = (Properties) new_en.clone();
for(Object key : temp.keySet())
{
if(new_fr.containsKey((String) key))
{
new_fr.remove(key);
new_en.remove(key);
}
}
for(Object key : new_en.keySet())
{
System.out.println("English only key: " + ((String)key));
}
for(Object key : new_fr.keySet())
{
System.out.println("French only key: " + ((String)key));
}
}
}
Sample use case for the class, taken directly from application, but with some editing so only the relevant parts are here
AR testing = new AR();
Properties en_prop = new Properties();
Properties fr_prop = new Properties();
final String test_prod_cur = "{call BILINGUAL_VALUES(?)}";
ResultSet rs = null;
try (
Connection connection = jdbcTemplate.getDataSource().getConnection();
CallableStatement callableStatement = connection.prepareCall(test_prod_cur);
)
{
callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
callableStatement.executeUpdate();
rs = (ResultSet) callableStatement.getObject(1);
while (rs.next())
{
String thead = rs.getString(1);
en_prop.setProperty(keyheader+thead, rs.getString(2));
fr_prop.setProperty(keyheader+thead, rs.getString(3));
//testing.appendProperty(keyheader+thead, rs.getString(2), rs.getString(3)); //has a timing issue, ends up only appending final value
}
}
catch (SQLException e)
{
System.out.println("SQLException - bilingual values");
System.out.println(e.getMessage());
}
testing.appendProperty(en_prop, fr_prop);
Regarding this question: "what is causing the corruption to my French characters and how can I fix it?", the answer is in the documentation ( Properties.store() ):
public void store(OutputStream out,
String comments)
throws IOException
Writes this property list (key and element pairs) in this Properties
table to the output stream in a format suitable for loading into a
Properties table using the load(InputStream) method.
Properties from the defaults table of this Properties table (if any)
are not written out by this method.
This method outputs the comments, properties keys and values in the
same format as specified in store(Writer), with the following
differences:
The stream is written using the ISO 8859-1 character encoding.
Characters not in Latin-1 in the comments are written as \uxxxx for their appropriate unicode hexadecimal value xxxx.
Characters less than \u0020 and characters greater than \u007E in property keys or values are written as \uxxxx for the appropriate hexadecimal value xxxx.
I am not the only person who has faced this issue, I managed to find another question and it was one of the answers that lead me to my solution. I have to thank another site for letting me know what to include.
There are only four added or changed lines, I will list them, and then give a complete function.
import java.io.Reader;
Reader reader = new InputStreamReader(fr_is, "UTF-8");
fr_prop.load(reader); //instead of fr_prop.load(fr_is);
reader.close();
The complete function
import java.io.Reader;
private void loadProperties()
{
InputStream en_is = null;
InputStream fr_is = null;
try {
this.en_prop = new Properties();
this.fr_prop = new Properties();
en_is = this.getClass().getResourceAsStream(en_path);
fr_is = this.getClass().getResourceAsStream(fr_path);
Reader reader = new InputStreamReader(fr_is, "UTF-8");
en_prop.load(en_is);
fr_prop.load(reader);
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
By introducing the reader and using that, it has cleared up French character corruption.
I should mention that I changed every file property I could find over to UTF-8 before I did the above changes and got it working. This site gives you the changes I made. This was a nice page that helped me confirm the encodings.
I would like to monitor the used java heap size of a jboss service running on windows during serveral days. I first try to use perfmon from windows but I didn't get the value I expected. I can hook jvisualvm to this this service using jmx (server:port), I can also use jconsole or jmc (java mission control). Indeed I cannot use flight recording due to the jvm version.
With jcmd or jstat, I cannot see the process I'm interested in. As I'm new in Java, could someone suggest an application or script which would allow me to catpure those value and push them to a text file for example. I could code something in .Net as well if a library would exist.
Thanks
Below java code records the Java Heap usage (2 mins once by default) to a text file. You can change the code as per your needs. Change the private String jmxUrl = ... as per your environment.
package com.heap.monitor;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.management.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.management.*;
import javax.management.remote.*;
public class HeapMonitor extends Thread {
private JMXServiceURL jmxService = null;
private JMXConnector jmxConnector = null;
protected MBeanServerConnection beanServerConn = null;
private long frequency = 2 * 60 * 1000L; // 2 mins only collects Heap metrics
private String jmxUrl = "service:jmx:rmi:///jndi/rmi://192.168.8.252:12222/jmxrmi";
private String userName = "none";
private String passWord = "none";
public static void main(String[] args) throws InterruptedException {
HeapMonitor heapMonitor = new HeapMonitor();
heapMonitor.join();
}
public HeapMonitor() {
this.start();
}
public void run() {
boolean flag = true;
while(flag) {
try {
beanServerConn = connectToJVM(jmxUrl, userName, passWord);
if(beanServerConn!=null) {
MemoryMXBean mxbean = (MemoryMXBean) ManagementFactory.newPlatformMXBeanProxy(beanServerConn, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
try
{
MemoryUsage heapUsage = mxbean.getHeapMemoryUsage();
long used = heapUsage.getUsed();
long max = heapUsage.getMax();
long commited = heapUsage.getCommitted();
long init = heapUsage.getInit();
StringBuffer buffer = new StringBuffer();
Date date = new Date();
buffer.append(date).append(" - ");
buffer.append(init).append(" ").append(commited).append(" ").append(max).append(" ").append(used);
//System.out.println(buffer.toString());
appendStrToFile("heap.txt" , buffer.toString());
}
catch(Exception ee) {
ee.printStackTrace();
}
}
}
catch(Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(frequency);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
protected MBeanServerConnection connectToJVM(String jvmURL, String user, String pass)
{
beanServerConn = null ;
try
{
jmxService = new JMXServiceURL(jvmURL);
Map environment = new HashMap();
int jmxconnect_timeout = 30000;
environment.put("jmx.remote.x.request.waiting.timeout", Long.toString(jmxconnect_timeout));
if(user.equalsIgnoreCase("none")|| (pass.equalsIgnoreCase("none"))){
try{
jmxConnector = JMXConnectorFactory.connect(jmxService,environment);
beanServerConn = jmxConnector.getMBeanServerConnection();
}
catch(IOException ioe){
}
}
else
{
String [] credentials={user,pass};
environment.put(JMXConnector.CREDENTIALS, credentials);
try{
jmxConnector = JMXConnectorFactory.connect(jmxService,environment);
beanServerConn = jmxConnector.getMBeanServerConnection();
}
catch(IOException ioe){
}
}
beanServerConn = jmxConnector.getMBeanServerConnection();
if(beanServerConn == null)
{
System.out.println("Connection to JVM is not established for jvmURL : " + jvmURL);
closeJVMConn();
}
}
catch(Exception ex)
{
System.out.println("Connection to JVM is not established for jvmURL : " + jvmURL);
closeJVMConn();
}
return beanServerConn;
}
public void closeJVMConn(){
try{
beanServerConn = null;
if(jmxConnector != null)
jmxConnector.close();
}
catch(Exception ex){
return;
}
}
public void appendStrToFile(String fileName, String str) {
try {
// Open given file in append mode.
BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
out.write(str);
out.newLine();
out.close();
}
catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
}
Using Jconsole, you can view and capture the Heap/Non-Heap Memory usage (also CPU, Threads, etc). In the Jconsole a small popup windows appears when Right Click Heap Memory Usage Graph as shown in the screenshot. You can save the data in the .csv format for the selected time range.
How can i access to my Asynchronous web service in java? I made this thing in Flex Builder, and it`s pretty easy: just add web service throw "Data -> Connect to Web Service -> Enter the URL of wsdl" and add this lines:
private function result(e:ResultEvent):void
{
trace(e.result.toString());
}
private function fault(e:FaultEvent):void
{
trace(e.toString());
}
var d:DomainAuth = new DomainAuth();
d.AuthFuncName(login, pass);
d.addEventListener(ResultEvent.RESULT, result);
d.addEventListener(FaultEvent.FAULT, fault);
How can i do this in Java using eclipse EE?
Basically you need to do a SOAP web service client in java if I understand you correctly.
JAX-WS can be your friend. The following code is from here
package simpleclient;
import javax.xml.ws.WebServiceRef;
import helloservice.endpoint.HelloService;
import helloservice.endpoint.Hello;
public class HelloClient {
#WebServiceRef(wsdlLocation="http://localhost:8080/
helloservice/hello?wsdl")
static HelloService service;
public static void main(String[] args) {
try {
HelloClient client = new HelloClient();
client.doTest(args);
} catch(Exception e) {
e.printStackTrace();
}
}
public void doTest(String[] args) {
try {
System.out.println("Retrieving the port from
the following service: " + service);
Hello port = service.getHelloPort();
System.out.println("Invoking the sayHello operation
on the port.");
String name;
if (args.length > 0) {
name = args[0];
} else {
name = "No Name";
}
String response = port.sayHello(name);
System.out.println(response);
} catch(Exception e) {
e.printStackTrace();
}
}
}
i have java class in which i have done database connection for SQL server and trying to retrieve data from table its working fine. but now i created web service in java for that class then its showing me ClassNotFoundException :net.sourceforge.jtds.jdbc.Driver i have import external jar as well.
Actually i need to show data from database to Android layout that's why i created web service which will helpful to retrieve data from database.
But when i am trying to retrieve data from database then Drivers are not loading.its showing above error.
i also tried like following :
//DatabaseConnetivityClass.java
public class DatabaseConnetivityClass
{
public static void main(String Args[])
{
new DatabaseConnetivityClass().getData();
}
public String getData()
{
String s = null;
try {
s = new MainConnection().getData();
} catch (SQLException e) {
e.printStackTrace();
}
return s;
}
}
MainConnection.java
public class MainConnection {
Connection con;
public MainConnection() {
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/databasename","username","password");
}
catch (Exception e) {
System.out.println("exp:"+e);
}
}
public String getData() throws SQLException {
StringBuffer sb = new StringBuffer();
Statement select = con.createStatement();
ResultSet result = select.executeQuery("SELECT * FROM Personal_Info");
while (result.next()) {
// process results one row at a time
String val = result.getString(1);
sb.append(val);
System.out.println("val = " + val);
}
select.close();
return sb.toString();
}}
i thought it will work but its giving the same error.
So please help me if anybody knows the solution
Okay, I'm trying to create a custom client for Minecraft (don't worry, my question has nothing to do with Minecraft in particular), and I added an abstract class to manage a configuration file using Java's built-in Properties system. I have a method that loads a properties file or creates it if it doesn't already exist. This method is called at the beginning of all my other methods (although it only does anything the first time its called).
The properties file gets created just fine when I run Minecraft the first time, but somehow when I run it the second time, the file gets blanked out. I'm not sure where or why or how I'm wiping the file clean, can someone please help me? Here's my code; the offending method is loadConfig():
package net.minecraft.src;
import java.util.*;
import java.util.regex.*;
import java.io.*;
/**
* Class for managing my custom client's properties
*
* #author oxguy3
*/
public abstract class OxProps
{
public static boolean configloaded = false;
private static Properties props = new Properties();
private static String[] usernames;
public static void loadConfig() {
System.out.println("loadConfig() called");
if (!configloaded) {
System.out.println("loading config for the first time");
File cfile = new File("oxconfig.properties");
boolean configisnew;
if (!cfile.exists()) {
System.out.println("cfile failed exists(), creating blank file");
try {
configisnew = cfile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
configisnew=true;
}
} else {
System.out.println("cfile passed exists(), proceding");
configisnew=false;
}
FileInputStream cin = null;
FileOutputStream cout = null;
try {
cin = new FileInputStream(cfile);
cout = new FileOutputStream(cfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (!configisnew) { //if the config already existed
System.out.println("config already existed");
try {
props.load(cin);
} catch (IOException e) {
e.printStackTrace();
}
} else { //if it doesn't exist, and therefore needs to be created
System.out.println("creating new config");
props.setProperty("names", "oxguy3, Player");
props.setProperty("cloak_url", "http://s3.amazonaws.com/MinecraftCloaks/akronman1.png");
try {
props.store(cout, "OXGUY3'S CUSTOM CLIENT\n\ncloak_url is the URL to get custom cloaks from\nnames are the usernames to give cloaks to\n");
cout.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
String names = props.getProperty("names");
System.out.println("names: "+names);
try {
usernames = Pattern.compile(", ").split(names);
} catch (NullPointerException npe) {
npe.printStackTrace();
}
System.out.println("usernames: "+Arrays.toString(usernames));
configloaded=true;
}
}
public static boolean checkUsername(String username) {
loadConfig();
System.out.println("Checking username...");
for (int i=0; i<usernames.length; i++) {
System.out.println("comparing "+username+" with config value "+usernames[i]);
if (username.startsWith(usernames[i])){
System.out.println("we got a match!");
return true;
}
}
System.out.println("no match found");
return false;
}
public static String getCloakUrl() {
loadConfig();
return props.getProperty("cloak_url", "http://s3.amazonaws.com/MinecraftCloaks/akronman1.png");
}
}
If it's too hard to read here, it's also on Pastebin: http://pastebin.com/9UscXWap
Thanks!
You are unconditionally creating new FileOutputStream(cfile). This will overwrite the existing file with an empty one. You should only invoke the FileOutputStream constructor when writing a new config file.
if (configloaded)
return;
File cfile = new File("oxconfig.properties");
try {
if (cfile.createNewFile()) {
try {
FileOutputStream cout = new FileOutputStream(cfile);
props.setProperty("names", "oxguy3, Player");
props.setProperty("cloak_url", "http://...");
...
cout.flush();
} finally {
cout.close();
}
} else {
FileInputStream cin = new FileInputStream(cfile);
try {
props.load(cin);
} finally {
cin.close();
}
}
configloaded=true;
} catch(IOException ex) {
e.printStackTrace();
}