Call native function fflush & strprn from java
Hi,
I need to call a native function fflush and stdprn from java for printing a file.
How can i call this function?
Can any one help me with sample code.
Thanks,
rpalanivelu
Thanks your reply,
Actually my problem is need to take printout using dot matrix printer(text printer) with different font size.
So, i am using native method which is available in c.
in c program i am using fflush,stdprn and fprintf.
Here i've attached my sample program also.
#include <jni.h>
#include "NativePrint.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINE_LEN 100
JNIEXPORT jint JNICALL
Java_NativePrint_dotMatrixPrint(JNIEnv* env, jobject obj )
FILE *fp;
char filename[20];
char line[100]; /* A line read from the file */
int lineNumber = 0;
/* Print control codes */
char boldOn = 14;
char boldOff = 20;
char contentlenOn = 15;
char contentlenOff = 18;
printf("Printing from C3");
strcpy( filename , "sayHello.c" );
/* Open the file in read mode */
fp = fopen( filename , "r" );
/* Error in opening file, then exit */
if ( fp == NULL )
printf( "\nERROR: %s cannot be opened\n" , filename );
exit( 1 );
while ( fgets( line , 100 , fp ) != NULL )
lineNumber++; /* Line we are about to process next */
printf("%s",line);
/* If this is the first line */
if ( lineNumber == 1 )
/* then print it in bold */
//fprintf( stdprn , "%c" , boldOn );
fprintf( stdprn , "%c" , contentlenOn );
fprintf( stdprn , line );
fprintf( stdprn , "%c" , contentlenOff);
//fprintf( stdprn , "%c" , boldOff );
else
/* else print it in normal mode */
fprintf( stdprn , line );
fflush(stdprn);
return 0;
Similar Messages
-
Calling native Objective C code from Java Script
Hi,
I want to call native objective C code from Java script.
I know one way by using : webView:shouldStartLoadWithRequest:navigationType
Is there another way of doing same?
Thanks,
Ganesh Pisal
Vavni IncAre any of those threads calling java code? If yes then are you calling the Attach method?
-
Call stored function / stored procedure from JAVA/JPA and pass array
I fail calling a plsql function from java with jpa - it works perfect without the array but its not working with the array:
PLSQL Function:
function getHtml(pWhere VARCHAR2 DEFAULT NULL,
pColSort HTP.STRINGARRAY) return clob is
begin
errorhndl.Log(pMessage => 'called');
htp.prn('das ist der test
for i in 1 .. pColSort.count loop
htp.p('
pColSort['||i||']: '||pColSort(i));
end loop;
htp.prn('
<table> <tr> <td> max1.0 </td> <td> max2.0 </td> </tr>');
htp.prn('<tr> <td> max1.1 </td> <td> max2.1 </td> </tr> </table>');
htp.prn('test ende');
return htp.gHtpPClob;
exception
when others then
null;
end getHtml;
PLSQL TYPE: (in HTP package - self created - but could be anywhere else too)
type STRINGARRAY is table of varchar2(256) index by binary_integer;
JAVA DOA:
public class ShowReportDOAImpl implements ShowReportDOA {
private JdbcTemplate jdbcTemplate;
private SimpleJdbcCall procShowReport;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
procShowReport = new SimpleJdbcCall(this.jdbcTemplate)
.withCatalogName("Show_Report")
.withFunctionName("getHtml")
.withoutProcedureColumnMetaDataAccess()
.declareParameters(
new SqlParameter("pWhere", Types.VARCHAR),
new SqlParameter("pColSort", Types.ARRAY, "HTP.STRINGARRAY"),
new SqlOutParameter("RETURN", Types.CLOB)
public String readReport(Long id, ParameterHelper ph) {
String[] sortCol = {"max", "michi", "stefan"};
String pWhere = "fritz";
MapSqlParameterSource parms = new MapSqlParameterSource();
parms.addValue("pWhere", pWhere);
parms.addValue("pColSort", sortCol, Types.ARRAY, "HTP.STRINGARRAY");
parms.addValue("pColSort", Arrays.asList(sortCol), Types.ARRAY, "HTP.STRINGARRAY");
Clob clob = procShowReport.executeFunction(Clob.class, parms);
String clobString = "";
try {
System.out.println("length: "+new Long(clob.length()).intValue());
clobString = clob.getSubString(1, new Long(clob.length()).intValue());
} catch (SQLException e) {
e.printStackTrace();
return clobString;
EXCEPTION IS:
org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for SQL [{? = call SHOW_REPORT.GETHTML(?, ?)}]; SQL state [null]; error code [17059]; Konvertierung zu interner Darstellung nicht erfolgreich: [max, michi, stefan]; nested exception is java.sql.SQLException: Konvertierung zu interner Darstellung nicht erfolgreich: [max, michi, stefan]
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:969)
org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1003)
org.springframework.jdbc.core.simple.AbstractJdbcCall.executeCallInternal(AbstractJdbcCall.java:391)
org.springframework.jdbc.core.simple.AbstractJdbcCall.doExecute(AbstractJdbcCall.java:354)
org.springframework.jdbc.core.simple.SimpleJdbcCall.executeFunction(SimpleJdbcCall.java:154)
at.ontec.cat.config.doa.ShowReportDOAImpl.readReport(ShowReportDOAImpl.java:47)
at.ontec.cat.http.ShowReport.doGet(ShowReport.java:80)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause
java.sql.SQLException: Konvertierung zu interner Darstellung nicht erfolgreich: [max, michi, stefan]
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:124)
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:161)
oracle.jdbc.driver.DatabaseError.check_error(DatabaseError.java:860)
oracle.sql.ARRAY.toARRAY(ARRAY.java:209)
oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:7767)
oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7448)
oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:7836)
oracle.jdbc.driver.OracleCallableStatement.setObject(OracleCallableStatement.java:4586)
org.apache.commons.dbcp.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:166)
org.apache.commons.dbcp.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:166)
org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:356)
org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:216)
org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:127)
org.springframework.jdbc.core.CallableStatementCreatorFactory$CallableStatementCreatorImpl.createCallableStatement(CallableStatementCreatorFactory.java:212)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:947)
org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1003)
org.springframework.jdbc.core.simple.AbstractJdbcCall.executeCallInternal(AbstractJdbcCall.java:391)
org.springframework.jdbc.core.simple.AbstractJdbcCall.doExecute(AbstractJdbcCall.java:354)
org.springframework.jdbc.core.simple.SimpleJdbcCall.executeFunction(SimpleJdbcCall.java:154)
at.ontec.cat.config.doa.ShowReportDOAImpl.readReport(ShowReportDOAImpl.java:47)
at.ontec.cat.http.ShowReport.doGet(ShowReport.java:80)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
Please help!!
Please help!!user8374822 wrote:
PLSQL Function:
function getHtml(pWhere VARCHAR2 DEFAULT NULL,
pColSort HTP.STRINGARRAY) return clob is
begin
end getHtml;
PLSQL TYPE: (in HTP package - self created - but could be anywhere else too)
type STRINGARRAY is table of varchar2(256) index by binary_integer;
JAVA DOA:
new SqlParameter("pColSort", Types.ARRAY, "HTP.STRINGARRAY"),I don't know much (??) java and can't understand your error messages as they are not in english.
But I have a feeling that the error is because either
a) "Types.ARRAY" in Java world probably does not map to an index-by table in oracle or
b) the array must be created as a SQL TYPE and not as a package variable or
c) both of the above
You may want to try following approaches
1) Change the array type declaration to nested table i.e. use "type STRINGARRAY is table of varchar2(256)"
2) If the above does not work, then create a sql type (using CREATE TYPE statement) to create STRINGARRAY as a SQL type of varchar2(256)
Hope this helps. -
Call a function in servlet from java class.
Hi,
I am implementing a client/server technology by trying to convert a java desktop client into Browser based. As part of user authetication the only way I know that a username /password does not match is from the servers message as i dont have documentation of the backend servers database.
Here is a fucntion which receives lines form server.
public class ServerComm{
public synchronized void receiveMessage(String serverMessage){
if (serverMessage.equals("Login-Fail"))// Login-Fail is message from server if login fails
LoginHandler.loginFail()//Login Handler is a servlet
return
}The Login Handler servlet is as follows.
public class LoginHandler extends HttpServlet {
/** Initializes the servlet.
public void init(ServletConfig config) throws ServletException {
super.init(config);
/** Destroys the servlet.
public void destroy() {
/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
protected synchronized void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//some expressions.
//this is reached if login fails.
public static void loginFail(){
HttpServletResponse response;
//redirected to wronglogin web page.
response.sendRedirect("/mCVW/wronglogin.jsp");
/** Handles the HTTP <code>GET</code> method.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
/** Handles the HTTP <code>POST</code> method.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}Now there is problem in loginFail() method in LoginHandler servlet does not work with the type of response decleration . I need some assistance from any one to make this work or propose a better solution for determining the user authetication with the restriction i have.
Thank you.hmm...I haven't tried this before...but does this work by any chance?
In your ServerComm class, create new HttpServletRequest and Response objects and get a RequestDispatcher object from request.
Eg : if (serverMessage.equals("login-fail"){
HttpServletRequest request = new HttpServletRequest ();
HttpServletResponse response = new HttpServletResponse ();
request.setAttribute("function_id", "loginFail");
RequestDispatcher dispatcher = request.getRequestDispatcher("http://servername:port/ServletName");
//give the complete path of your servlet
dispatcher.forward(request, response);
and in your Servlet, get this function_id and if its loginFail, redirect it to wronlogin.jsp...
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
String function_id = request.getAttribute("function_id");
if(function_id.equalsIgnoreCase("loginFail"))
//forward to ur jsp
getServletConfig().getServletContext().getRequestDispatcher(wronlogin.jsp").forward(request, response);
} -
Calling a third Party dll from java using JNI
Hi
I want an immediate help from u all.
I have athird party c dll with .h and .lib file
I wont be able to cahnge any thing in those files.
I want to call the functions of that from my Java code.
Ist possible to call the dll without writing any c or c++ wrapper over it?if yes , how to do it?Hi,
You may use a generic wrapper like JNative.
Commercial wappers also exists.
--Marc (http://jnative.sf.net) -
How to run the Oracle Triggers,Functions and Procedures from java
Hi ,
I want to execute the Oracle's Triggers, Functions and Procedures from java as like executing the SQL commands by using Execute statements.
Or can we have some other option for doing this.
Plz help me ...you can use CallableStatement interface of JDBC to execute any DBMS triger,stored procedure ....
refer any of the JDBC book for extra help
hope you got it
Azeem Ahmed -
Calling native functions from java w/out DLL
If I invoke a JVM inside my c++ app and try to start up a class that calls a native function, do I still need a DLL for that? Or will it look to my header file and then look to my implementation somewhere in a c++ class?
For example:
WinMain() - Invokes JVM and loads "HelloWorld" java class, then calls its 'main' method.
HelloWorld.java - 'main' method calls "displayHello();" a native function.
HelloWorld.h - defines displayHello native interface
So it looks simply to the cpp implementation of the interface...I tried executing this but it isnt working...is it even possible?OK, I attempted what you posted by writing the following code... please look at because I get a 'main' not found error. I am trying to execute this from a win32 app...
Callbacks.java:
class Callbacks {
private native void nativeMethod(int depth);
private void callback(int depth) {
if (depth < 5) {
System.out.println("In Java, depth = " + depth + ", about to enter C");
nativeMethod(depth + 1);
System.out.println("In Java, depth = " + depth + ", back from C");
} else
System.out.println("In Java, depth = " + depth + ", limit exceeded");
public static void main(String args[]) {
Callbacks c = new Callbacks();
c.nativeMethod(0);
}InvokeJVM.cpp:
#include "InvokeJVM.h"
//Log any windows errors
void InvokeJVM::LogWin32Error(const char * pTitle){
PCHAR pBuffer;
LONG lError = GetLastError ( );
FormatMessage ( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
lError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(char *)&pBuffer,
0,
NULL );
//LogError ("Win32 error: %s %s\n",pBuffer,pTitle);
LocalFree ( pBuffer );
//Get a string returned from the windows registry
bool InvokeJVM::GetStringFromRegistry(HKEY key, const char *name, unsigned char *buf, int bufsize){
DWORD type, size;
if (RegQueryValueEx(key, name, 0, &type, 0, &size) == 0 && type == REG_SZ && (size < (unsigned int)bufsize)){
if (RegQueryValueEx(key, name, 0, 0, buf, &size) == 0){
return true;
return false;
//Get the path to the runtime environment
bool InvokeJVM::GetPublicJREHome(char *buf, int bufsize){
HKEY key, subkey;
char version[MAX_PATH];
/* Find the current version of the JRE */
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, JRE_KEY,0,KEY_READ,&key)!=0){
//LogError("Error opening registry key '" JRE_KEY "'\n");
return false;
if(!GetStringFromRegistry(key,"CurrentVersion",(unsigned char *)version, sizeof(version))){
//LogError("Failed reading value of registry key:\n\t"JRE_KEY "\\CurrentVersion\n");
RegCloseKey(key);
return false;
if(strcmp(version, DOTRELEASE)!= 0){
//LogError("Registry key '" JRE_KEY "\\CurrentVersion'\nhas value '%s', but '" DOTRELEASE "' is required.\n", version);
RegCloseKey(key);
return false;
/* Find directory where the current version is installed. */
if(RegOpenKeyEx(key,version,0,KEY_READ, &subkey)!= 0){
//LogError("Error opening registry key '"JRE_KEY "\\%s'\n", version);
RegCloseKey(key);
return false;
if(!GetStringFromRegistry(subkey, "JavaHome", (unsigned char *)buf, bufsize)){
//LogError("Failed reading value of registry key:\n\t"JRE_KEY "\\%s\\JavaHome\n", version);
RegCloseKey(key);
RegCloseKey(subkey);
return false;
RegCloseKey(key);
RegCloseKey(subkey);
return true;
//Native interface call to printf
jint JNICALL _vfprintf_(FILE *fp, const char *format, va_list args){
//LogError(format,args);
return 0;
//Native interface call if the VM exited
void JNICALL _exit_(jint code){
//LogError("VM exited");
exit(code);
//Native interface call if the VM aborted
void JNICALL _abort_(void){
//LogError("VM aborted");
abort();
//Load the Java Virtual Machine
void InvokeJVM::LoadJVM(char* dir){
HINSTANCE handle;
JavaVMOption options[5];
char JREHome[MAX_PATH];
char JVMPath[MAX_PATH];
char classpathOption[MAX_PATH];
char librarypathOption[MAX_PATH];
if(!GetPublicJREHome(JREHome, MAX_PATH)){
//LogError("Could not locate JRE");
abort();
strcpy(JVMPath,JREHome);
strcat(JVMPath,"\\jre\\bin\\client\\jvm.dll");
if ((handle=LoadLibrary(JVMPath))==0) {
//LogError("Error loading: %s", JVMPath);
abort();
CreateJavaVM_t pfnCreateJavaVM=(CreateJavaVM_t)GetProcAddress(handle,"JNI_CreateJavaVM");
if (pfnCreateJavaVM==0){
//LogError("Error: can't find JNI interfaces in: %s",JVMPath);
abort();
strcpy(classpathOption,"-Djava.class.path=");
strcat(classpathOption,dir);
strcat(classpathOption,";");
strcat(classpathOption,JREHome);
strcat(classpathOption,"\\lib");
strcat(classpathOption,";");
strcat(classpathOption,JREHome);
strcat(classpathOption,"\\lib\\comm.jar");
strcpy(librarypathOption,"-Djava.library.path=");
strcat(librarypathOption,JREHome);
strcat(librarypathOption,"\\lib");
OutputDebugString("classpath option=");
OutputDebugString(classpathOption);
OutputDebugString("\n");
OutputDebugString("librarypath option=");
OutputDebugString(librarypathOption);
OutputDebugString("\n");
options[0].optionString=classpathOption;
options[1].optionString=librarypathOption;
options[2].optionString="vfprintf";
options[2].extraInfo=_vfprintf_;
options[3].optionString="exit";
options[3].extraInfo=_exit_;
options[4].optionString="abort";
options[4].extraInfo=_abort_;
vmArgs.version = JNI_VERSION_1_2;
vmArgs.nOptions = 5;
vmArgs.options = options;
vmArgs.ignoreUnrecognized = false;
if(pfnCreateJavaVM(&jvm,(void**)&env, &vmArgs) != 0){
//LogError("Could not create VM");
abort();
}Winmain.cpp:
#define WIN32_MEAN_AND_LEAN
#define WIN32_EXTRA_LEAN
#include <windows.h>
#include "oglwindow.h" // the OpenGL window class
#include "vector.h"
#include "engine.h" // the engine's main class
#include "BrimstoneEngine.h"
#include "InvokeJVM.h"
JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *, jobject){
MessageBox(NULL, "Hello From Java!", "Error", MB_OK);
return;
JNIEXPORT void JNICALL Java_Callbacks_nativeMethod(JNIEnv *env, jobject obj, jint depth){
jclass cls = env->GetObjectClass(obj);
jmethodID mid = env->GetMethodID(cls, "callback", "(I)V");
if (mid == 0) {
return;
printf("In C, depth = %d, about to enter Java\n", depth);
env->CallVoidMethod(obj, mid, depth);
printf("In C, depth = %d, back from Java\n", depth);
JNINativeMethod methods[] = {"nativeMethod","()V", Java_Callbacks_nativeMethod};
WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, int nCmdShow){
InvokeJVM javaVirtualMachine;
int loopRet;
javaVirtualMachine.running = false;
CoInitialize(NULL);
if (!COGLWindow::RegisterWindow(hInst)){
MessageBox(NULL, "Failed to register window class", "Error", MB_OK);
return -1;
BrimstoneEngine *engine = NULL;
try{
char path[MAX_PATH];
char drive[MAX_PATH];
char file[MAX_PATH];
char dir[MAX_PATH];
char ext[MAX_PATH];
jclass cls, cls1;
jmethodID mid;
jobjectArray args;
jint err;
_splitpath(path,drive,dir,file,ext);
javaVirtualMachine.LoadJVM(dir);
if(javaVirtualMachine.env == NULL){
MessageBox(NULL, "Could not load VM", "Error", MB_OK);
abort();
if(GetModuleFileName(NULL, path, MAX_PATH) == 0){
javaVirtualMachine.LogWin32Error("Getting module filename");
abort();
cls = javaVirtualMachine.env->FindClass("Callbacks");
if(cls == NULL){
MessageBox(NULL, "Could not find class %s (or its superclass)", "Error", MB_OK);
exit(-1);
err = javaVirtualMachine.env->RegisterNatives(cls, methods, 1 );
mid = javaVirtualMachine.env->GetMethodID(cls, "main", "([Ljava/lang/String;)V");
if(mid == NULL){
MessageBox(NULL, "Could not find method 'main'", "Error", MB_OK);
exit(-1);
args = javaVirtualMachine.env->NewObjectArray(2-2, javaVirtualMachine.env->FindClass("java/lang/String"), NULL);
if(args==NULL){
MessageBox(NULL, "Could not create args array", "Error", MB_OK);
for(int arg=0; arg < 2;arg++) {
javaVirtualMachine.env->SetObjectArrayElement(args, arg, javaVirtualMachine.env->NewStringUTF(argv[arg+2]));
javaVirtualMachine.env->CallStaticVoidMethod(cls,mid,args);
javaVirtualMachine.jvm->DestroyJavaVM();
engine = new BrimstoneEngine("OpenGL Game", FALSE, 800, 600, 16);
loopRet = engine->EnterMessageLoop();
delete engine;
return loopRet;
catch(char *sz)
MessageBox(NULL, sz, 0, 0);
delete engine;
CoUninitialize();
return -1;
}any help is always appreciated -
Calling existing C/C++ dll from Java Prog
Hi,
From within the Java code I want to use the
functionality of an existing C API. The dll's of C are available. Is it possible to directly call the C Api using Jni or some other technique or do I need to implement a native method in C which would Use the existing C Api to get the values and Pass them to the Java prog.
Istikhar.Is it possible to directly call the C Api using Jni...Depends on what you mean. You can't call it directly from java. You can use JNI, including C/C++ to call it.
-
Calling Oracle Functions and Procedures in Java
I've looked online for a blurb on using Oracle SQL functions and
procedures in Java, but I haven't found anything. Can someone
either give me a quick crash course on this, or point me to the
best source of information for this?From the SQLJ FAQ.
http://otn.oracle.com/tech/java/sqlj_jdbc/htdocs/faq.html#sqljplsql
Within your SQLJ statements, you can use PL/SQL anonymous blocks
and call PL/SQL stored procedures and stored functions, as in the
following examples: Anonymous
block:
#sql {
DECLARE
n NUMBER;
BEGIN
n := 1;
WHILE n <= 100 LOOP
INSERT INTO emp (empno) VALUES(2000 +
n);
n := n + 1;
END LOOP;
END
Stored procedure call (returns the maximum
deadline as an output parameter into an output host expression):
#sql { CALL MAX_DEADLINE(:out maxDeadline) };
Stored function call (returns the maximum
deadline as a function return into a result expression):
#sql maxDeadline = { VALUES(GET_MAX_DEADLINE)
Of course, you can also use JDBC code to achieve the same - the
standard JDBC escape sequences for stored function and procedure
calls are supported, using for example:
"{? = CALL GET_MAX_DEADLINE}"
or:
"{call MAX_DEADLINE(?)}"
and for the rest of the details, get that JDBC crash course... -
Call JavaScript method in FXML from java controller
I have fxml like
<fx:root type="javafx.scene.Group" xmlns:fx="http://javafx.com/fxml">
<fx:script>
function applyState(oldState, newState)
</fx:script>
....and controller to it.
The idea is to move some view logic to fxml file.
So, when I need to change some view state, I want to call applyState from java code.
The question is how to do it.
What I have found:
We can get
fxmlLoader.getNamespace().get("applyState")and receive sun.org.mozilla.javascript.internal.InterpretedFunction.
NetBeans see this class. But while building the project i have an error
error: package sun.org.mozilla.javascript.internal does not exist
But this class really exists in rt.jar in JRE.
After that I have stopped digging into this.
I suspect that using internal API is not a good idea to call this InterpretedFunction.
Can somebody suggest how can I make such an invocation?
Edited by: 940811 on Nov 19, 2012 11:21 PMUntil JavaFX doesn't expose the ScriptEngine instance of FXMLLoader, there's no way to communicate (Java <-> Javascript) with the <fx:script>.
But, if you want to rely on a hack, you can do this:
private ScriptEngine extractScriptEngine(FXMLLoader loader) {
try {
Field fse = loader.getClass().getDeclaredField("scriptEngine");
fse.setAccessible(true);
return (ScriptEngine) fse.get(loader);
} catch (IllegalAccessException | NoSuchFieldException | SecurityException ex) {
Logger.getLogger(BrowserFXController.class.getName()).log(Level.SEVERE, null, ex);
return null;
} -
Calling a Visual C++ COM from java
Hi all, I have a problem very strange:
I have developed , using JNI, a java class wich interacts with a COM Interface.
When I use the java class that implements jni connection form the main method in my java app, it works fine, but when I try to access this class in a different class outside main, I obtain an error creating the Com instance. Anyone knows why?
//C++ Com initialize
BOOL CECardIdWorks::Initialize()
CUtilLog oUtilLog = CUtilLog();
try
// Get our instance of the PrintServer's IDataInput interface:
HRESULT hr = m_pDataInput.CreateInstance(__uuidof(PrintServer::DataInput2));
if (FAILED(hr))
oUtilLog.NuevoLog("CECardIdWorks","InitCard","Fallo en m_pDataInput.CreateInstance.");
return TRUE;
catch (_com_error& ce)
oUtilLog.NuevoLog("CECardIdWorks","Initialize","Excepcion , Initialize exception.");
LogComError(ce);
AfxMessageBox("Initialize Exception. Exit");
return FALSE;
}This is the C++ code part.
// extract of code in ECard.cpp
//class intance
CECardIdWorks* oECardIdWorks = new CECardIdWorks();
// Initialize
JNIEXPORT jint JNICALL Java_ECard_Initialize(JNIEnv *env, jobject obj)
CUtilLog oUtilLog = CUtilLog();
oUtilLog.NuevoLog("CECard","Java_ECard_Initialize","Begining Initialize.");
if (oECardIdWorks->Initialize())
return EC_SUCCESS;
else
return EC_ERROR_NOT_INITIALIZED;
// extract of code in ECardIdWorks.cpp
BOOL CECardIdWorks::Initialize()
CUtilLog oUtilLog = CUtilLog();
try
// Get our instance of the PrintServer's IDataInput interface:
HRESULT hr = m_pDataInput.CreateInstance(__uuidof(PrintServer::DataInput2));
if (FAILED(hr))
oUtilLog.NuevoLog("CECardIdWorks","InitCard","Fallo en m_pDataInput.CreateInstance.");
return TRUE;
catch (_com_error& ce)
oUtilLog.NuevoLog("CECardIdWorks","Initialize","Excepcion , Initialize exception.");
LogComError(ce);
AfxMessageBox("Initialize Exception. Exit");
return FALSE;
// extract of code in ECardIdWorks.h
class CECardIdWorks : public CWinApp
public:
// Print Server IDataInput
PrintServer::IDataInput2Ptr m_pDataInput;
DECLARE_MESSAGE_MAP()
// Extract of code from StdAfx.h
#import "D:\Archivos de programa\Datacard\ID Works\bin\PrintServer.DLL"This is the java code part
public class ECard {
// Load the dll that exports functions callable from java
static {System.loadLibrary("ECard");}
// Imported function declarations
public native int Initialize();
public void ECard()
public static void main(String [] args)
ECard t = new ECard();
int intResult=0;
// Initialize
intResult = t.Initialize();
System.out.println("->Initialize. Return value:" + intResult);
}My problem is that, if this code
ECard t = new ECard();
int intResult=0;
// Initialize
intResult = t.Initialize();
System.out.println("->Initialize. Return value:" + intResult);is outside main method, for example, in a method of another class, I get an error like this:
Com error 80004005
Source: PrintServer.IDataInput.2
Description: Error creating instance of card object
Please help me I�m desperate... -
Calling a COBOL stored proc from Java Servlet
I am trying to call a COBOL stored proc from a Java Servlet. The stored proc is stored on a DB2 database. I need to send 6 inputs to the COBOL stored proc and the output will be the return code of the stored proc. I'm not sure if I'm going about this the right way. This is how my code looks...
public int callStoredProc(CallableStatement cstmt,
Connection con,
String sYear,
String sReportNbr,
String sSystemCode,
String sUserId,
String sModuleNbr,
String sFormId){
int iParm1 = 0;
try{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
catch(ClassNotFoundException ex){
System.out.println("Failed to locate database driver: "
+ ex.toString());
return iParm1;
try{
cstmt = con.prepareCall("{? = CALL MKTPZ90C
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.setString(2, sYear);
cstmt.setString(3, sReportNbr);
cstmt.setString(4, sSystemCode);
cstmt.setString(5, sUserId);
cstmt.setString(6, sModuleNbr);
cstmt.setString(7, sFormId);
cstmt.execute();
iParm1 = cstmt.getInt(1);
CloseSQLStatement(cstmt);
catch(SQLException ex) {
CloseSQLStatement(cstmt);
System.out.println("SQL exception occurred:" +
ex.toString());
return iParm1;
return iParm1;
Could someone tell me if this is the right way to go about doing this?
Thanks!!!!!!I didn't see the code where you create the database connection (variable "con"). However, the answer to your question "Is this the right way...", for me, is "Anything that works is the right way." So try it. That's a first approximation, but once you have something that works you can start on improving it, if that becomes necessary.
-
Calling stored procedures in Sybase from java
Hi,
I am using the following stored procedure in Sybase
use xyzdb
go
-- drop procedure if it already exist
if object_id('up_name_select') is not null
begin
drop procedure up_name_select
end
go
create procedure up_name_select
@zid numeric(7,0),
@firstname char(40),
@lastname char(40)
as
select zid,
firstname,
lastname
from name
where zid = @zid or
(lastname like @lastname or firstname like @firstname)
go
-- update documentation records in object_docs
delete object_docs
from object_docs
where object_name = "up_name_select"
go
insert into object_docs values("up_name_select","Selects records from the name table based upon the values of the input parameters.")
go
-- update documentation records in column_docs
delete column_docs
from column_docs
where object_name = "up_name_select"
go
insert into column_docs values("up_name_select","@zid","System generated ID for an individual contact.")
insert into column_docs values("up_name_select","@firstname","First name of the contact. SQL wild card characters are accepted.")
insert into column_docs values("up_name_select","@lastname","Last name of the contact. SQL wild card characters are accepted.")
go
-- print success message and grant permissions
if object_id('up_name_select') is not null
begin
print "Procedure up_name_select created."
grant execute on up_name_select to developer_role
end
go
This stored procedure selects the values from the table "name" for a given where condition (if I am not wrong).
Can any one give me sample java code to select the records from the table "name" for a given zid.
Thankyou in advance.
Regards
sgatl2calling stored procedures from java
here is the sample code
CallableStatement cs = con.prepareCall("{call selectlogin (?)}");
cs.setString (1, "value");
ResultSet rs = cs.executeQuery ();
while (rs.next ())
//your code for display
} more on gooooooogle
http://www.google.com/search?q=calling+stored+procedures+from+java+with+sample+example&client=netscape-pp&rls=com.netscape:en-US -
Calling a VB Com component from Java
Hi,
I wish to call some legacy VB 6 COM dlls from some new Java code I am writing. I was looking (just read quickly haven't tried the examples yet) at the ActiveX Bridge documentation and get the impression that it only goes one way -i.e. make Java into an ActiveX Component to be used from VB, whereas I wish to call VB from Java.
Have I missed something or is this not the way to go to get to the legacy code?
The legacy code also has an MIDL file. Ideally, I would love to just be able to access that from Java, but I can't find any (non-Microsoft VJ++ based) tools to help with either converting MIDL to IDL so I can use Sun's idlj.exe or just converting the MIDL to Java.
Any pointers/tips on any of this would be appreciated.
Thanks,
CherylI looked at Jacob, but didn't get far either.
Right now I'm looking at Jawin -
http://jawinproject.sourceforge.net/jawin.html. Not
making a lot of headway yet.
IDL is OMG's IDL (Interface Definition Language) -
http://www.omg.org/gettingstarted/omg_idl.htm.
MIDL is Microsoft's version of IDL for COM - I believe
it uses IDL., but can't seem to find a conversion
tool.
idlj.exe is in the bin directory of whatever JDK you
have loaded. This tool will convert OMG IDL into Java.
Good luck to you.Hi,
I am facing a similar problem. I need to access a vb dll methods. I took and look at jawin and installed it.
I want to invoke a method in the dll from my servlet.
So do I have to create stubs for it. I opened the Type Browser that comes with jawin. It is a GUI through which I am supposed to create stub java files for that dll. But I am getting this error:
[EXCEPTION] InfoPanel.generateInfo() failed to generated info
org.jawin.browser.xsl.TransformationException: TransformationManager.cacheStyles
heet() failed to compile stylesheet from: stylesheets/info/library.xsl - javax.x
ml.transform.TransformerConfigurationException: javax.xml.transform.TransformerC
onfigurationException: javax.xml.transform.TransformerException: java.net.Malfor
medURLException: no protocol: stylesheets/info/library.xsl
at org.jawin.browser.xsl.TransformationManager.cacheStylesheet(Transform
ationManager.java:130)
at org.jawin.browser.xsl.TransformationManager.checkStylesheet(Transform
ationManager.java:180)
at org.jawin.browser.xsl.TransformationManager.transform(TransformationM
anager.java:147)
at org.jawin.browser.info.InfoPanel.generateInfo(InfoPanel.java:68)
at org.jawin.browser.info.InfoPanel.selectionChanged(InfoPanel.java:61)
at org.jawin.browser.tree.TypeDataTree.fireSelectionChanged(TypeDataTree
.java:61)
Is anyone sucessfully able to generate stub files for the dll in jawin using Type Browser ?
Please let me know
my mailid is tanveerrameez(at) yahoo dot com
thanks
Tanveer -
How to call EJB deployed on OC4J from java stored procedure?
Hello,
I'd like to call EJB from java stored procedure. My example works fine from command line, but the problem seems to be with deployment of this code into database. Especialy I'm wondering how to reference jars like oc4jclient.jar, ejb.jar, ... from java stored procedure.
Is there some example how to do that ?
Can You help me please ?
Many thanks,
Radim Kolek,
Eurotel Prague.Hi,
You may want to check up this thread
Calling JBoss EJBs from Java stored procedure
Hope this helps,
Sujatha.
OTN Group.
Maybe you are looking for
-
Open PDF files in IE by Acrobat Standard 8 instead of Reader
Hi, I have an issue when I open PDF files in Internet Explorer. On my computer, Acrobat Reader 7 and Acrobat Standard 8 are installed. I want that Acrobat Standard 8 opens my PDF files instead of Acrobat Reader 7. There is 2 conditions : I can't (I m
-
Java.lag out of memory error
my x2 cannot work with the pdf reader i downloaded from nokia store as there is java.lag out of memory error what should i do
-
How can i find out how much money i owe on my apple id
when i put my billing info in and try to make a purchase on my ipad mini its not accepting my card. how do i find out how much i owe
-
Finder sidebar error 8058 when try to delete
I have two old files in my finder sidebar that I can't delete . I am running in Lion. when I restart in 10.6.8 they are gone. but when I go back to Lion, they are still there and I cannot move them to trash. I get error code 8058 when I try to move t
-
Hi. Can anyone tell me if it's possible to make modification in SAP B1 2007A that will force all users to view the UDF sidebar. We have AddOn running that require user to have the view of UDF sidebar set to 'ON' at all times. Sometimes the users forg