Table_not_available when using JAVA SAP RFC_READ_TABLE - java

There are three different tables (OPTIONS, FIELDS and DATA) in import parameter "QUERY_TABLE" = "LTAP".
I created a java program to display column FIELDNAME from the table FIELDS with helping function RFC_READ_TABLE.
It always appears Error com.sap.conn.jco.AbapException: (126) TABLE_NOT_AVAILABLE: TABLE_NOT_AVAILABLE Message 300 of class DA type E, when I call the method step2WorkWithTable().
Can anybody explain the error? And how to fix it?
My codes:
import java.util.Properties;
import com.sap.conn.jco.AbapException;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.ext.DestinationDataProvider;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;
public class RFC_Read_Table {
public static void main(String[] args) throws JCoException
{
System.out.println("Step1: connect SAP without Pool");
step1Connect();
System.out.println("");
System.out.println("Step2: call RFC_Read_Table ");
step2WorkWithTable();
System.out.println("--------------------------------");
System.out.println("finished");
}
static {
String DESTINATION_NAME1 = "mySAPSystem";
Properties connectProperties = new Properties();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "ABC");
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "33");
connectProperties.setProperty(DestinationDataProvider.JCO_SAPROUTER, "/A/123/");
connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "100");
connectProperties.setProperty(DestinationDataProvider.JCO_USER, "UserID");
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "Passwort");
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "de");
createDestinationDataFile(DESTINATION_NAME1, connectProperties);
}
private static void createDestinationDataFile(String destinationName, Properties connectProperties) {
File destCfg = new File(destinationName+".jcoDestination");
try
{
FileOutputStream fos = new FileOutputStream(destCfg, false);
connectProperties.store(fos, "for tests only !");
fos.close();
}
catch (Exception e)
{
throw new RuntimeException("Unable to create the destination files", e);
}
}
public static void step1Connect() throws JCoException
{
try {
JCoDestination destination = JCoDestinationManager.getDestination("mySAPSystem");
System.out.println("connected");
destination.ping();
} catch (JCoException e) {
e.printStackTrace();
System.out.println("not connected");
}
}
public static void step2WorkWithTable() throws JCoException
{
JCoDestination destination = JCoDestinationManager.getDestination("mySAPSystem");
JCoFunction function = destination.getRepository().getFunction("RFC_READ_TABLE");
if (function == null)
throw new RuntimeException("RFC_Read_Table not found in SAP.");
try
{
function.execute(destination);
}
catch(AbapException e)
{
System.out.println(e.toString());
return;
}
function.getImportParameterList().setValue("QUERY_TABLE","LTAP");
JCoTable codes = function.getTableParameterList().getTable("FIELDS");
codes.appendRow();
for (int i = 0; i < codes.getNumRows(); i++)
{
codes.setRow(i);
System.out.println(codes.getString("FIELDNAME"));
}
codes.firstRow();
for (int i = 0; i < codes.getNumRows(); i++, codes.nextRow())
{
function = destination.getRepository().getFunction("RFC_READ_TABLE");
if (function == null)
throw new RuntimeException("RFC_READ_TABLE not found in SAP.");
function.getImportParameterList().setValue("FIELDNAMEID", codes.getString("FIELDNAME"));
try
{
function.execute(destination);
}
catch (AbapException e)
{
System.out.println(e.toString());
return;
}
JCoStructure detail = function.getExportParameterList().getStructure("FIELDS");
System.out.println(detail.getString("FIELDNAME"));
}
}
}

There is nothing wrong with your JCo code. The error message comes from the SAP system. So you need to check in the SAP system, what that error code means. This can be done in transaction SE91. You enter message class = "DA" and message number = "300" and click display.
I did this for you, and the result is:
"No active nametab exists for &"
where '&' needs to be replaced by the input, which is "LTAP" in this case. So we have "No active nametab exists for LTAP".
This error basically means: the database table "LTAP" exists on the database, but has not yet been activated in the ABAP DDIC. (Perhaps because it still contains a syntax error, or a required data element/domain is missing, etc.)
Solution: go to transaction SE11 and try to activate the table. This will probably give you an error message about what is wrong with this table. Fix all the syntax errors, activate it, and then you can use it.
Note: if LTAP is a standard table delivered by SAP, this error probably means that something went wrong when installing a transport/hotpackage from SAP that contained modifications to this table. In this case you should better contact SAP support to get the table back into a "consistent" state again.

I see you are connecting to an ABAP system using JCoDestinationManager. It means your are using the properties from mySAPSystem destination. Please check if the mySAPSystem connects to a proper ABAP system.
What are these lines are needed for
Properties connectProperties = new Properties();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "ABC");
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "33");
connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "100");
connectProperties.setProperty(DestinationDataProvider.JCO_USER, "UserID");
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "Passwort");
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "de");
I don't see them to be used anywhere in your program. It seems their are not applied to your connection...

Related

Unable to attach file to issue in jira via rest api Java

I want to attach multiple files to issue. I'm able to create issue successfully however i am facing problem in attaching documents after creating issue. I have referred to this link SOLVED: attach a file using REST from scriptrunner
I am getting 404 error even though issue exists and also user has all the permissions.
File fileToUpload = new File("D:\\dummy.txt");
InputStream in = null;
try {
in = new FileInputStream(fileToUpload);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
HttpResponse < String > response3 = Unirest
.post("https://.../rest/api/2/issue/test-85/attachments")
.basicAuth(username, password).field("file", in , "dummy.txt")
.asString();
System.out.println(response3.getStatus());
here test-85 is a issueKey value.
And i am using open-unirest-java-3.3.06.jar. Is the way i am attaching documents is correct?
I am not sure how open-unirest manages its fields, maybe it tries to put them as json field, rather than post content.
I've been using Rcarz's Jira client. It's a little bit outdated but it still works.
Maybe looking at its code will help you, or you can just use it directly.
The Issue class:
public JSON addAttachment(File file) throws JiraException {
try {
return restclient.post(getRestUri(key) + "/attachments", file);
} catch (Exception ex) {
throw new JiraException("Failed add attachment to issue " + key, ex);
}
}
And in RestClient class:
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
public JSON post(String path, File file) throws RestException, IOException, URISyntaxException {
return request(new HttpPost(buildURI(path)), file);
}
private JSON request(HttpEntityEnclosingRequestBase req, File file) throws RestException, IOException {
if (file != null) {
File fileUpload = file;
req.setHeader("X-Atlassian-Token", "nocheck");
MultipartEntity ent = new MultipartEntity();
ent.addPart("file", new FileBody(fileUpload));
req.setEntity(ent);
}
return request(req);
}
So I'm not sure why you're getting a 404, Jira is sometime fuzzy and not really clear about its error, try printing the full error, or checking Jira's log if you can. Maybe it's just the "X-Atlassian-Token", "nocheck", try adding it.

(opendj-ldap-sdk-2.6.0) bind method parameter - password char [ ]

I'm using opendj-ldap-sdk-2.6.0 jar library to search LDAP entry.
I am following the guide.
(https://backstage.forgerock.com/docs/opendj/2.6/dev-guide/#chap-using-the-sdk)
source code :
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.SearchScope;
import org.forgerock.opendj.ldap.responses.SearchResultEntry;
import org.forgerock.opendj.ldap.responses.SearchResultReference;
import org.forgerock.opendj.ldif.ConnectionEntryReader;
import org.forgerock.opendj.ldif.LDIFEntryWriter;
public class Test {
public static void main(String[] args) {
final LDIFEntryWriter writer = new LDIFEntryWriter(System.out);
Connection connection = null;
try {
final LDAPConnectionFactory factory = new LDAPConnectionFactory("localhost",389);
connection = factory.getConnection();
connection.bind("cn = Directory Mangager", password );
// password is just an example of the password.
final ConnectionEntryReader reader = connection.search("dc=example,dc=com", SearchScope.WHOLE_SUBTREE,"(uid=bjensen)","*");
while (reader.hasNext()) {
if(reader.isEntry()) {
final SearchResultEntry entry = reader.readEntry();
writer.writeComment("Search result entry:" + entry.getName().toString());
writer.writeEntry(entry);
} else {
final SearchResultReference ref = reader.readReference();
writer.writeComment("Search result reference:" + ref.getURIs().toString());
}
}
writer.flush();
} catch (final Exception e) {
System.err.println(e.getMessage());
} finally {
if (connection !=null) {
connection.close();
}
}
}
connection.bind("cn = Directory Mangager", password );
I'm getting a red line at this line under password because the parameter has to be 'char []'.
I captured Bind method in the below.
If my password is 1234, how can I change that into char [] type?
You're missing a call from factory to obtain a connection.
connection = factory.getConnection();
connection.bind("cn = Directory Mangager", password );
I figured it out.
connection.bind("cn=Directory Manager", "yourpassword".toCharArray() );
You can use toCharArray()
Also, as Ludovic Poitou mentioned above, you need to use
connection = factory.getConnection(); with the bind method.
The guide says if you are not using anonymous search, use the bind method, but you gotta use them both. (I misunderstood the guide)

Freemarker templates unable to gain access to images - Java Spring Boot

I am trying to gain access for images on an email template. I've tried following this guide.
Spring: refering the resources/static folder and this Spring 4 - addResourceHandlers not resolving the static resources
I am storing the templates in this location
my-project\complete\src\main\resources\templates
http://localhost:8080/static/templates/forgotemail/images/bottompodmiddleb.jpg
^ I want to gain access to this image -- I have a reactjs build and I am unsure if the reactjs routing is interfering with this.
I have access to this image for example.
http://localhost:8080/static/media/-bach.4f9c4b25.jpg
I create a configuration class -but I am unsure if I need to invoke it or what.
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//#Configuration
#ComponentScan("Application")
public class Configuration extends WebMvcConfigurerAdapter {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// I tried these many combinations separately.
ResourceHandlerRegistration resourceRegistration = registry
.addResourceHandler("resources/**");
resourceRegistration.addResourceLocations("/resources/**");
registry.addResourceHandler("/templates/**").addResourceLocations("/templates/**");
//registry.addResourceHandler("/img/**").addResourceLocations("/img/**");
//registry.addResourceHandler("/js/**").addResourceLocations("/js/**");
registry.addResourceHandler("/resources/**")
.addResourceLocations("classpath:/resources/");
// do the classpath works with the directory under webapp?
}
}
here is the code that launches the email. "fmConfiguration.getTemplate("email-template.html")" appears to get access to the html email.
public void sendEmail(JSONObject model, JavaMailSender mailSender, Configuration fmConfiguration) throws Exception{
System.out.println("type>>>"+model);
System.out.println("mailSender"+ mailSender);
if(mailSender != null){
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
System.out.println("mimeMessage >>>"+ mimeMessage);
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setSubject("Hi");
mimeMessageHelper.setFrom("test2#gmail.com");
mimeMessageHelper.setTo("test#gmail.com");
//Map < String, Object > model = new HashMap < String, Object > ();
model.put("firstName", "Yashwant");
model.put("lastName", "Chavan");
model.put("imgPath", "resources/static/images/");
mimeMessageHelper.setText(geContentFromTemplate(fmConfiguration, model), true);
mailSender.send(mimeMessageHelper.getMimeMessage());
} catch (MessagingException e) {
System.out.println("ERROR - mimeMessage>>>");
e.printStackTrace();
}
}
}
public String geContentFromTemplate(Configuration fmConfiguration, Map < String, Object > model) {
StringBuffer content = new StringBuffer();
try {
content.append(FreeMarkerTemplateUtils
.processTemplateIntoString(fmConfiguration.getTemplate("email-template.html"), model));
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
I also had same kind of issue of not able to insert the images into the freemarker template.
I followed the example mentioned here
Now able to add the images with this approach.

Fatal Exception re WAS AdminClient

I'm attempting to monitor a Websphere 7 ennvironment using MBeans, but running into numerous problems. First, I receive the following exception when using the code posted below:
com.ibm.websphere.management.exception.ConnectorException: Could not
create RMI Connector to connect to host localhost at port 2809
Here is the code generating the exception:
import java.util.Properties;
import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.management.AdminClientFactory;
public class JustAdminClient {
private AdminClient adminClient;
private void initialize() throws Exception {
try {
// Initialize the AdminClient.
Properties adminProps = new Properties();
adminProps.setProperty("type", AdminClient.CONNECTOR_TYPE_RMI);
adminProps.setProperty(AdminClient.CONNECTOR_SECURITY_ENABLED, "false");
adminProps.setProperty(AdminClient.CONNECTOR_HOST, "localhost");
adminProps.setProperty(AdminClient.CONNECTOR_PORT, "2809");
adminClient = AdminClientFactory.createAdminClient(adminProps);
} catch (Exception ex) {
ex.printStackTrace(System.out);
throw ex;
}
} // end method
/**
* #param args
*/
public static void main(String[] args) {
JustAdminClient adClient = new JustAdminClient();
try {
adClient.initialize();
} catch (Exception e) {
e.printStackTrace();
}
} // end main
} // end class
Second, I'm running WAS standalone with security disabled. Do I need to configure any self-signed certs?
My security.xml shows:
<security:Security xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI"
xmlns:orb.securityprotocol="http://www.ibm.com/websphere/appserver/schemas/5.0/orb.securityprotocol.xmi"
xmlns:security="http://www.ibm.com/websphere/appserver/schemas/5.0/security.xmi" xmi:id="Security_1"
useLocalSecurityServer="true" useDomainQualifiedUserNames="false"
issuePermissionWarning="true" activeProtocol="BOTH"
enforceJava2Security="false" enforceFineGrainedJCASecurity="false"
appEnabled="true" dynamicallyUpdateSSLConfig="true"
allowBasicAuth="true" activeAuthMechanism="LTPA_1"
activeUserRegistry="LocalOSUserRegistry" enabled="false" cacheTimeout="600"
defaultSSLSettings="SSLConfig_RXCW510MONNode01_1" adminPreferredAuthMech="RSAToken_1">
per the link: http://www-01.ibm.com/support/docview.wss?uid=swg21295051
Note, I can contact port 2809 two ways, via WSadamin and a Java prog containing the following:
private void connect(String host,String port) throws Exception
{
String jndiPath="/WsnAdminNameService#JMXConnector";
JMXServiceURL url = new JMXServiceURL("service:jmx:iiop://"+host+"/jndi/corbaname:iiop:"+host+":"+port+jndiPath);
System.out.println("URL = " + url);
//JMXServiceURL url = new JMXServiceURL("service:jmx:iiop://192.168.0.175:9100/jndi/JMXConnector");
Hashtable h = new Hashtable();
//Specify the user ID and password for the server if security is enabled on server.
//Establish the JMX connection.
System.out.println("Before JMXConnector");
JMXConnector jmxc = JMXConnectorFactory.connect(url, h);
//Get the MBean server connection instance.
System.out.println("Before getMBeanServerConnection");
mbsc = jmxc.getMBeanServerConnection();
System.out.println("Connected to Application Server");
} // end method
Any ideas? I'm lost and apologize for the long thread, but better to see the info upfront.
Resolved my problem using the follwoing example code snippet and notations. Note, pay particular attention to thrown exception and messages re: mssing classes; i.e. focusing on the message "could not create" message may mislead you
requires the following jar files:
%WAS_HOME%\runtimes\com.ibm.jaxws.thinclient_7.0.0.jar
%WAS_HOME%\plugins\com.ibm.ws.runtime.jar
%WAS_HOME%\plugins\deploytool\itp\com.ibm.websphere.v7_7.0.0.v20080817\wasJars\com.ibm.ws.admin.core.jar
%WAS_HOME%\runtimes\com.ibm.ws.admin.client_7.0.0.jar requires
CONNECTOR_TYPE_SOAP. CONNECTOR_TYPE_RMI fails to connect; maybe a jar issue based on the stack trace messages
public class JMXAdminClientSimple {
`private AdminClient adminClient;
private ObjectName nodeagent = null;
public void initialize() throws Exception {
try {
// Initialize the AdminClient.
Properties props = new Properties();
props.setProperty(AdminClient.CONNECTOR_HOST, "localhost");
props.setProperty(AdminClient.CONNECTOR_PORT, "8880");
props.setProperty(AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP);
props.setProperty(AdminClient.CONNECTOR_SECURITY_ENABLED, "false");
props.setProperty(AdminClient.USERNAME, "");
props.setProperty(AdminClient.PASSWORD, "");
adminClient = AdminClientFactory.createAdminClient(props);
} catch (Exception ex) {
ex.printStackTrace(System.out);
throw ex;
}
}`
To use the AdminClient API with security disabled on a Sun/Oracle JRE, you need the following JARs in the classpath:
runtimes/com.ibm.ws.admin.client_7.0.0.jar
runtimes/com.ibm.ws.ejb.thinclient_7.0.0.jar
runtimes/com.ibm.ws.orb_7.0.0.jar
With these JARs, RMI should also work.

Java running in Oracle - the imported jars

I am trying to get a small java class to load into Oracle 11g so I can run it and call it from PL/SQL. I coded and compiled the class on my local machine in eclipse and it compiles fine. I packaged it up into a jar (with the other jar files it depends on in the jar). They I tried loading my jar into Oracle 11g. Everything loads in, unfortunately when it loads my custom java class, it stays invalid and when I try to compile it within Oracle it says it can't find references to the classes (the ones I had packaged in my jar with my class).
Is there some other sort of setting I need to configure?
Here is what my custom classes code looks like:
import com.flashline.registry.openapi.base.OpenAPIException;
import com.flashline.registry.openapi.entity.*;
import com.flashline.registry.openapi.service.v300.FlashlineRegistry;
import com.flashline.registry.openapi.service.v300.FlashlineRegistryServiceLocator;
import javax.xml.rpc.ServiceException;
import java.net.URL;
import java.rmi.RemoteException;
import org.apache.log4j.Logger;
import java.net.MalformedURLException;
public class AssetExtractor {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
static Logger LOG;
static AuthToken authToken = null;
static FlashlineRegistry repository = null;
static URL repoURL;
public static FlashlineRegistry getRepository()
{
if(repository == null)
try
{
try{
repoURL = new URL("https://myserver/oer/services/FlashlineRegistry");
}catch(MalformedURLException mue)
{
LOG.error(mue);
}
repository = (new FlashlineRegistryServiceLocator()).getFlashlineRegistry(repoURL);
LOG.debug((new StringBuilder()).append("Created repository at URL=").append(repoURL.toString()).toString());
}
catch(ServiceException e)
{
LOG.error(e, e);
}
return repository;
}
public static AuthToken getAuthToken()
{
if(authToken == null)
try
{
authToken = getRepository().authTokenCreate("user", "password");
LOG.debug("Created auth token.");
}
catch(OpenAPIException e)
{
LOG.error(e, e);
}
catch(RemoteException e)
{
LOG.error(e, e);
}
else
try
{
getRepository().authTokenValidate(authToken);
}
catch(OpenAPIException e)
{
LOG.info("Auth token was invalid. Recreating auth token");
authToken = null;
return getAuthToken();
}
catch(RemoteException re)
{
LOG.error("Remote exception occured during creation of suth token after determined to be invalid", re);
re.printStackTrace();
authToken = null;
}
return authToken;
}
public static String getAssetXML(String strAssetID)
{
String strAsset = null;
try
{
strAsset = getRepository().assetReadXml(getAuthToken(), Long.parseLong(strAssetID));
}
catch(OpenAPIException e)
{
e.printStackTrace();
}
catch(RemoteException e)
{
e.printStackTrace();
}
return strAsset;
}
}
And all the *.jar files for the imports are inside my AssetExtractor.jar
The command I've been using to load the jar into oracle is:
loadjava -v -f -resolve -resolver "((* OER) (* PUBLIC))" -user oer/***** AssetExtractor.jar
Any ideas would be helpful!
So it appears that if I do the following it solves nearly all my problems:
Edit the Oracle users' .profile to SET and EXPORT the CLASSPATH, PATH, LD_LIBRARY_PATH, ORACLE_HOME, JAVA_HOME with the correct paths
SQLPlus as sys as sysdba
EXEC dbms_java.grant_permission( 'OER', 'SYS:java.util.PropertyPermission', 'java.class.path', 'write' );
OS Commandline as oracle user:
loadjava –v –grant PUBLIC <jar> -user oer/****** for all jars
SQLPlus as OER user
DECLARE
v_classpath VARCHAR2(4000);
v_path VARCHAR2(4000);
BEGIN
v_classpath := DBMS_JAVA.set_property('java.class.path', '/opt/oracle/102/jdk/lib:/mnt/hgfs/vmshare/rex_lib/aler-axis- 1.2.1.jar:/mnt/hgfs/vmshare/rex_lib/aler-axis-jaxrpc-1.2.1.jar:/mnt/hgfs/vmshare/rex_lib/client.rex- 11.1.1.5.0.jar:/mnt/hgfs/vmshare/rex_lib/commons-httpclient-3.0rc2- flashline.jar:/mnt/hgfs/vmshare/rex_lib/log4j-1.2.8.jar');
v_path := DBMS_JAVA.set_property('java.path', '/opt/oracle/102/jdk/bin');
END;
/
alter java source "AssetExtractor" compile;
show errors
The only outstanding issue is that for some reason it still can't locate/resolve some of the Oracle OER classes (which should all be in the client.rex*.jar, I opened and saw them there. If I can solve this part then I'm good to go.

Categories

Resources