Loading Matlab variables into Java

I have written a program in Matlab which creates a matrix. I now need to use this matrix in my Java code but i dont know how to do this. One suggestion I was given was to save the Matlab matrix as a binary file (easy) and then load the file in Java. Does anyone know how I could do this? And are there better ways? I think there are ways of running Matlab code from Java and vice versa but i dont know what that involves.
Thanks.

Well, OX
1) Use the Runtime.exec() method to execute the Matlab program
2) Get the InputStream from the Process object that the exec() method generates.
3) Modift the Matlab program to write the matrix in some format to the standard OutputStream of the Matlab program - for formating, you can take a row and print it to the OutputStream as a LWS separated line of text terminating with a CR-LF
4) Read the text line from the InputStream in the Java program.
5) Parse the string (may be with a StringTokenizer) and construct the matrix in a 2d array or by some other means.
Hope it helps!
Ironluca

Similar Messages

  • How to load additional libraries into java

    how can I load additional system libraries into Java?
    ...

    Here is how:
    http://java.sun.com/docs/books/tutorial/ext/
    It is called "Extension Mechanism" and simply put, it let's you add your extension libraries (jar files) in the "ext" directory of your installation of JRE or SDK, and they become available to all java programs without caring of other configurations (like setting the CLASSPATH variable or the like...)

  • Loading php variables into flash 8

    i'm trying to load some vars into flash 8. i tried
    loadvariables, loadvariablesnum, loadvars, google. can't figure it
    out.
    2 years ago when using flash mx trying the same thing, the
    line:
    loadVariablesNum("file",0);
    was enough to do the trick.
    but in flash 8 can't get it to work ;(
    i have the simplest php file, something like this:
    <?
    $town = "where";
    $person = "who";
    $sex = "male";
    print "town=$town&person=$person&sex=$sex";
    ?>
    the use of variables is a must, so the solution
    print "town=where&person=who&sex=male"
    doesn't do me any good. actually this works.
    so what's the correct way of loading this into flash 8?
    thanks guyz.

    you can also use a FlashVars= parameter in your
    <object><embed> code, IF you are using your PHP code to
    also display your flash movie, and if you only need to pass these
    variables once when the movie loads. If this is what you need to
    do, use this....
    <object ...>
    ....// other params .....
    <param name="FlashVars" value="<?
    echo var1name;
    ?>=<?
    echo var1value;
    ?>&<?
    echo var2name;
    ?>=<?
    echo var2value;
    ?>" >
    Though you will have to do that in two places, once in the
    object code, and once in the embed code.
    The embed code would look more like
    <embed ...... FlashVars="<? //php similar to above
    ?>" ..... />
    I have used this successfully to pass in variables when the
    flash movie first loads, to pass in stuff like a URL for a link and
    other info. There are a lot of different ways to pass values in to
    flash. You can also use ExternalInterface.call and use Javascript
    along with PHP to retrieve info at any time, but that is more
    complex.
    This may not be what you need - but you can still use
    LoadVariables with Flash 8, as well.

  • How to pass a JavaScript variable into a java method

    I would like to know how to pass a JavaScript variable into a java method with in a <% %> tag inside a JSP file like so:
    <%@ page contentType="text/html;charset=windows-1252"%>
    <html>
    <head>
    <script LANGUAGE="JavaScript">
    myValue = someDynamicValue;
    <% System.out.println(myValue)%>
    </script>
    </head>
    <body>
    </body>
    </html>
    obviously "System.out.println(myValue)" will not work because myValue is seen as a java variable and not a JavaScript variable.
    I would like to know how to let the jsp file, that I wrote in the above code, see myValue as a JavaScript variable and not a java variable so that I can pass it to a java method.
    NOTE: the java method does not have to be a println() method, it can be any method of my choice.
    NOTE: someDynamicValue is a JavaScript value that can dynamically change

    I don't believe you can. JSPs are really just elaborate templates that an engine such as Tomcat parses and generates an HTML page based on. That page is then displayed to the user. By the time you want to use some function in Javascript, the JSP has already been parsed and generated.
    Basically, Javascript and JSPs can't talk to each other. One's server-side and the other is client-side.

  • How to load a variable using MATLAB Script?

    I need to load a selected variable from .mat file, using MATLAB script , and analyse it.
    the attched shows my vi, there are two inputs nodes 'file' contains the .mat file path, and 'varn' contains varibale name in that .mat file which can be selected by user. Using " load(file)" the whole .mat file is loaded in the workspace and become avaiable at output node, however I am not able to pass a selected variable name through string "varn" input, MATLAB script does not recognize the variable.
    any idea to reslove it is realy appreciated.
    Attachments:
    load a variable.JPG ‏18 KB

    Download the VI and .MAT file. Run the VI, and it'll plot the data inside of the .MAT file.
    Andy Chang
    National Instruments
    LabVIEW Control Design and Simulation
    Attachments:
    testfile.zip ‏5 KB

  • Loading large text files into java vectors and outof memmory

    Hi there,
    need your help for the following:
    i'm trying to load large ammoubnts of data into a Vector in order to concatenate several text files and treat them, but i'm getting outofmemory error. I even tried using xml structure and saving to database but the error is still the same. Can you help?
    thanks
    here's the code:
    public void Concatenate() {
    try {
    //for(int i=0;i<1;i++) {
    vEntries =  new Vector();
    for(int i=0;i<BopFiles.length;i++) {
    MainPanel.WriteLog("reading file " + BopFiles[i] + "...");
    FileInputStream fis = new FileInputStream(BopFiles);
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream in = new DataInputStream(bis);
    String line = in.readLine();
    Database db = new Database();
    Connection conn = db.open();
    while(line != null) {
    DivideLine(BopFiles[i], line);
    line = in.readLine();
    FreeMemory(db, conn);
    MainPanel.WriteLog("Num of elements: " + root.getChildNodes().getLength());
    MainPanel.WriteLog("Done!");
    } catch (Exception e) {
    e.printStackTrace();
    public void DivideLine(String file, String line) {
         if (line.toLowerCase().startsWith("00694")) {
              Header hd = new Header();
              hd.headerFile = file;
              hd.headerLine = line;
              vHeaders.add(hd);
         } else if (line.toLowerCase().startsWith("10694")) {
              Line entry = new Line();
              Vector vString = new Vector();
              Vector vType = new Vector();
              Vector vValue = new Vector();
              entry.name = line.substring(45, 150).trim();
              entry.number = line.substring(30, 45).trim();
              entry.nif = line.substring(213, 222).trim();
              entry.index=BopIndex;
              entry.message=line;
              entry.file=file;
              String series = line.substring(252);
              StringTokenizer st = new StringTokenizer(series, "A");
              while (st.hasMoreTokens()) {
                   String token=st.nextToken();
                   if(!token.startsWith(" ")) {
                        vString.add(token);
                        vType.add(token.substring(2,4));
                        vValue.add(token.substring(4));
                   token=null;
              entry.strings= new String[vString.size()];
              vString.copyInto(entry.strings);
              entry.types= new String[vType.size()];
              vType.copyInto(entry.types);
              entry.values= new String[vType.size()];
              vValue.copyInto(entry.values);
              vEntries.add(entry);
              entry=null;
              vString=null;
              vType=null;
              vValue=null;
              st=null;
              series=null;
              line=null;
              file=null;
              MainPanel.SetCount(BopIndex);
              BopIndex ++;
    public void FreeMemory(Database db, Connection conn) {
    try {
    //db.update("CREATE TABLE entries (message VARCHAR(1000))");
                   db.update("DELETE FROM entries;");
                   PreparedStatement ps = null;
                   for( int i=0; i<vEntries.size(); i++ ) {
                        Line entry = (Line) vEntries.get(i);
                        String value = "" + entry.message;
                        if(!value.equals("")) {
                             try {
                                  ps = conn.prepareStatement("INSERT INTO entries (message) VALUES('" + Tools.RemoveSingleQuote(value) + "');");
                                  ps.execute();
                             } catch(Exception e) {
                                  e.printStackTrace();
                                  System.out.println("error in number->" + i);
                   MainPanel.WriteLog("Releasing memory...");
         vEntries = null;
         vEntries = new Vector();
         System.gc();
              } catch (Exception e1) {
                   e1.printStackTrace();

    Well, i need to treat those contents, and calculate values withing those files, so wrinting files using FileInputstream wont do. for instance i need to get line 5 from file 1, split it, grab a value according to its class (value also taken) and compare it with another line of another file, adding those values to asingle file.
    that's why i need vector capabilities, but since these files have more than 5 Mb each, an out of memory error is returned by loading those values into vector.
    A better explanaition:
    Each file has a line like
    CLIENTNUM CLASS VALUE
    so if the client is the same withing 2 files, i need to sum the lines into a single file.
    If class is the same, then sum values, if not add it to the front.
    we could have a final line like
    CLIENTNUM CLASS1 VALUE1 CLASS2 VALUE2

  • Running Matlab code from java code

    Ok so I need to make a java gui interface to run Matlab code. After a lot of search I am aware of three approaches,the com.mathworks.jmi package, JNI and i/o streams. So as far as the first approach I cannot find that package nowhereto downlaod, so please if anyone knows where to find it, or why I cannot find it... As far as the second and third approach, I need this to run on both linux and windows so JNI is the only way. So first of all if someone has another approach to suggest, I would like to hear! So I have found code to do this but it is not working and the problem is that there is c code in all this, and my c knowledge is not good at all, so as you have probably understand this is more like a c problem than java, but I'm not completely sure. Anyway I'm posting all the code I use, then the commands I used to compile it and at last the problem.
    Engine.java
    package MatlabNativeInterface;
    import java.io.*;
    * <b>Java Engine for Matlab via Java Native Interface (JNI)</b><br>
    * This class demonstrates how to call Matlab from a Java program via
    * JNI, thereby employing Matlab as the computation engine.
    * The Matlab engine operates by running in the background as a separate
    * process from your own program.
    * <p>
    * Date: 04.04.03
    * <p>
    * Copyright (c) 2003 Andreas Klimke, Universit&#65533;t Stuttgart
    * <p>
    * Permission is hereby granted, free of charge, to any person
    * obtaining a copy of this software and associated documentation
    * files (the "Software"), to deal in the Software without
    * restriction, including without limitation the rights to use, copy,
    * modify, merge, publish, distribute, sublicense, and/or sell copies
    * of the Software, and to permit persons to whom the Software is
    * furnished to do so, subject to the following conditions:
    * <p>
    * The above copyright notice and this permission notice shall be
    * included in all copies or substantial portions of the Software.
    * <p>
    * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    * OTHER DEALINGS IN THE SOFTWARE.
    * @author W. Andreas Klimke, University of Stuttgart
    *         ([email protected])
    * @version 0.1
    public class Engine {
         * Calls the function <code>engOpen</code> of Matlab's C Engine library.
         * Excerpts from the Matlab documentation:
         * "On UNIX systems, if startcmd is NULL or the empty string,
         * <code>engOpen</code> starts MATLAB on the current host using the
         * command <code>matlab</code>. If startcmd is a hostname, <code>engOpen
         * </code> starts MATLAB on the designated host by embedding the specified
         * hostname string into the larger string:
         * <code>rsh hostname \"/bin/csh -c 'setenv DISPLAY\ hostname:0; matlab'\"
         * </code>. If startcmd is any other string (has white space in it, or
         * nonalphanumeric characters), the string is executed literally to start
         * MATLAB. On Windows, the startcmd string must be NULL."<br>     
         * See the Matlab documentation, chapter "External Interfaces/API
         * Reference/C Engine Functions" for further information.
         * @param startcmd The start command string.
         * @throws IOException Thrown if starting the process was not successful.
      public native void open(String startcmd) throws IOException;
          * Calls the function <code>engClose</code> of Matlab's C Engine
          * library.     This routine allows you to quit a MATLAB engine session.
          * @throws IOException Thrown if Matlab could not be closed.
         public native void close() throws IOException;
         * Calls the function <code>engEvalString</code> of Matlab's C Engine
         * library. Evaluates the expression contained in string for the MATLAB
         * engine session previously started by <code>open</code>.
         * See the Matlab documentation, chapter "External Interfaces/API
         * Reference/C Engine Functions" for further information.
         * @param str Expression to be evaluated.
         * @throws IOException Thrown if data could not be sent to Matlab. This
         *                     may happen if Matlab is no longer running.
         * @see #open
      public native void evalString(String str) throws IOException;
          *  Reads a maximum of <code>numberOfChars</code> characters from
          * the Matlab output buffer and returns the result as String.<br>
          * If the number of available characters exceeds <code>numberOfChars</code>,
          * the additional data is discarded. The Matlab process must be opended
          * previously with <code>open()</code>.<br>
          * @return String containing the Matlab output.
          * @see #open
          * @throws IOException Thrown if data could not be received. This may
          *                     happen if Matlab is no longer running.
      public native String getOutputString(int numberOfChars);
          * Initialize the native shared library.
      static {
             System.loadLibrary("Engine");//I have changed this
         //System.loadLibrary("engineJavaMatlab");
         System.err.println("Native Matlab shared library loaded.");
    }Engine.c
    #include <jni.h>
    #include "MatlabNativeInterface_Engine.h"
    #include <stdio.h>
    #include "engine.h"
    #define DEFAULT_BUFFERSIZE 65536
    Engine* ep;
    char outputBuffer[DEFAULT_BUFFERSIZE];
    JNIEXPORT void JNICALL
    Java_MatlabNativeInterface_Engine_open(JNIEnv *env, jobject obj, const jstring startcmd) {
      const char *c_string = (*env)->GetStringUTFChars(env, startcmd, 0);
      if (!(ep = engOpen(c_string))) {
        jclass exception;
        (*env)->ReleaseStringUTFChars(env, startcmd, c_string);
        exception = (*env)->FindClass(env, "java/io/IOException");
        if (exception == 0) return;
        (*env)->ThrowNew(env, exception, "Opening Matlab failed.");
        return;
      (*env)->ReleaseStringUTFChars(env, startcmd, c_string);
         /* indicate that output should not be discarded but stored in */
         /* outputBuffer */
      engOutputBuffer(ep, outputBuffer, DEFAULT_BUFFERSIZE);
    JNIEXPORT void JNICALL
    Java_MatlabNativeInterface_Engine_close(JNIEnv *env, jobject obj) {
         if (engClose(ep) == 1) {
           jclass exception;
        exception = (*env)->FindClass(env, "java/io/IOException");
        if (exception == 0) return;
        (*env)->ThrowNew(env, exception, "Closing Matlab failed.");
        return;
    JNIEXPORT void JNICALL
    Java_MatlabNativeInterface_Engine_evalString(JNIEnv *env, jobject obj, const jstring j_string) {
      const char *c_string;
         c_string = (*env)->GetStringUTFChars(env, j_string, 0);
      if (engEvalString(ep, c_string) != 0) {
           jclass exception;
        exception = (*env)->FindClass(env, "java/io/IOException");
        if (exception == 0) return;
        (*env)->ThrowNew(env, exception, "Error while sending/receiving data.");
      (*env)->ReleaseStringUTFChars(env, j_string, c_string);
    JNIEXPORT jstring JNICALL
    Java_MatlabNativeInterface_Engine_getOutputString(JNIEnv *env, jobject obj, jint numberOfChars) {
      char *c_string;
         jstring j_string;
         if (numberOfChars > DEFAULT_BUFFERSIZE) {
              numberOfChars = DEFAULT_BUFFERSIZE;
      c_string = (char *) malloc ( sizeof(char)*(numberOfChars+1) );
         c_string[numberOfChars] = 0;
      strncpy(c_string, outputBuffer, numberOfChars);
         j_string = (*env)->NewStringUTF(env, c_string);
         free(c_string);
      return j_string;
    }MatlabNativeInterface_Engine.h (as produced by javah)
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class MatlabNativeInterface_Engine */
    #ifndef _Included_MatlabNativeInterface_Engine
    #define _Included_MatlabNativeInterface_Engine
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class:     MatlabNativeInterface_Engine
    * Method:    open
    * Signature: (Ljava/lang/String;)V
    JNIEXPORT void JNICALL Java_MatlabNativeInterface_Engine_open
      (JNIEnv *, jobject, jstring);
    * Class:     MatlabNativeInterface_Engine
    * Method:    close
    * Signature: ()V
    JNIEXPORT void JNICALL Java_MatlabNativeInterface_Engine_close
      (JNIEnv *, jobject);
    * Class:     MatlabNativeInterface_Engine
    * Method:    evalString
    * Signature: (Ljava/lang/String;)V
    JNIEXPORT void JNICALL Java_MatlabNativeInterface_Engine_evalString
      (JNIEnv *, jobject, jstring);
    * Class:     MatlabNativeInterface_Engine
    * Method:    getOutputString
    * Signature: (I)Ljava/lang/String;
    JNIEXPORT jstring JNICALL Java_MatlabNativeInterface_Engine_getOutputString
      (JNIEnv *, jobject, jint);
    #ifdef __cplusplus
    #endif
    #endifand a Main.java
    import MatlabNativeInterface.*;
    import java.io.*;
    * Demonstration program for connecting Java with Matlab using the Java
    * Native Interface (JNI). Wrapper functions access Matlab via Matlab's
    * native C Engine library.
    public class Main {
         public static void main(String[] args) {
              Engine engine = new MatlabNativeInterface.Engine();
              try {
                   // Matlab start command:
                   engine.open("matlab -nosplash -nojvm");
                   // Display output:
                   System.out.println(engine.getOutputString(500));
          // Example: Solve the system of linear equations Ax = f with
                   // Matlab's Preconditioned Conjugate Gradients method.
                   engine.evalString("A = gallery('lehmer',10);");  // Define Matrix A
                   engine.evalString("f = ones(10,1);");            // Define vector f
                   engine.evalString("pcg(A,f,1e-5)");              // Compute x
                   // Retrieve output:
                   System.out.println(engine.getOutputString(500));
                   // Close the Matlab session:
                   engine.close();
              catch (Exception e) {
                   e.printStackTrace();
    }so I compile them with:
    javac -d classes @files.txt
    javah -classpath classes MatlabNativeInterface.Engine
    cc -shared -I/usr/java/jdk1.6.0_06/include/ -I/usr/java/jdk1.6.0_06/include/linux/ -I/usr/local/share/matlab7.6/extern/include/ Engine.c -o libEngine.soso everything gets compiled well and then I run Main:
    /javas/classes/_>mv libEngine.so classes/
    /javas/classes/_>cd classes/
    /javas/classes/_>java -Djava.library.path=. Main
    Exception in thread "main" java.lang.UnsatisfiedLinkError: /javas/classes/libEngine.so: /javas/classes/libEngine.so: undefined symbol: engOpen
            at java.lang.ClassLoader$NativeLibrary.load(Native Method)
            at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1751)
            at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1676)
            at java.lang.Runtime.loadLibrary0(Runtime.java:823)
            at java.lang.System.loadLibrary(System.java:1030)
            at MatlabNativeInterface.Engine.<clinit>(Engine.java:99)
            at Main.main(Main.java:11)So... please help!

    I need this to run on both linux and windows so JNI is the only wayHuh? Streams in general work on windows and linux. So maybe some more specific info
    about what you mean by "i/o streams."
    I am aware of three approachesA fourth approach is to write an application in C which communicates with Matlab directly
    and then uses some idiom such as sockets to allow communication to java. This would generally
    be the method that I would prefer over all others since it makes debugging and testing easier.
    undefined symbol: engOpenSomehow you are missing a library (nothing specific to to with JNI nor java) in you JNI code.
    Odd error since I would normally expect something else. Try using System.load/loadLibrary() in java to explicitly load the Matlab
    library (or libraries) before your JNI library. The load/LoadLibrary calls don't care if it is JNI or not.

  • Inserting user variables into MYSQL database using servlet

    I have a servlet that recieves user entered parameters from an html form and inserts them into a user table in MYSQL, or at least is supposed to. I can get it to update the table with specific values but not with the user variables. I know the single quote marks are for inserting specific values but without them it doesn't properly work.
    The parameters are parsed correctly into the variables, so I just can't figure out how to ge tthe variables into the database. Any help would be wonderful
    register.html:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
      <TITLE>Register</TITLE>
    </HEAD>
    <BODY BGCOLOR="#FDF5E6">
    <CENTER><IMG SRC="dvdti.jpg" ALIGN=middle >   </CENTER>
    <HR>
    <H1 ALIGN="CENTER">Please enter your registration details:</H1>
    <FORM ACTION="http://localhost:8080/examples/servlet/Assignment1.register">
      <BR>First Name: <input type="text" NAME="Ufirst_name"><BR>
      <BR>Last Name: <input TYPE="TEXT" NAME="Ulast_name"><BR>
      <BR>Address: <INPUT TYPE="text"  name="Uaddress"><BR>
      <BR>E-mail:     <INPUT TYPE="TEXT" NAME="Uemail"><BR
      <BR>Password: <INPUT TYPE="password" NAME="Upassword"><BR>
      <CENTER>
        <INPUT TYPE="SUBMIT" VALUE="Register">
      </CENTER>
    </FORM>
    </BODY>
    </HTML>
    register.java:
    package Assignment1;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    // Connects to a database to retrieve music data
    public class register extends HttpServlet {
      public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
          throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
    // Database connection code starts here
         Connection conn = null;
         // loading jdbc driver for mysql (help in mysql.jar file in classpath)
         try{
             Class.forName("com.mysql.jdbc.Driver").newInstance();
         } catch(Exception e) {
             System.out.println(e);
         // connecting to database
         try{
              // connection string for demos database, username demos, password demo-pass
             conn = DriverManager.getConnection
            ("jdbc:mysql://mudfoot.doc.stu.mmu.ac.uk:3306/roddiea?user=roddiea&password=");
              System.out.println("Connection to database successful.");
           catch(SQLException se) {
             System.out.println(se);
    // Create select statement and execute it
      try        { Statement stmt2 = conn.createStatement();
              // Get the regdetails from the reg form
               String Ufirst_name = request.getParameter("Ufirst_name");
               String Ulast_name = request.getParameter("Ulast_name");
               String Uaddress = request.getParameter("Uaddress");
               String Uemail = request.getParameter("Uemail");
                  String Upassword = request.getParameter("Upassword");
              stmt2.executeUpdate("INSERT INTO customer(first_name, last_name, address, email, password)" + "VALUES('Ufirst_name', 'Ulast_name', 'Uaddress', 'Uemail', 'Upassword')");
              System.out.println (stmt2);
              out.println(stmt2);
              out.println(Ufirst_name + Ulast_name + Uaddress + Uemail + Upassword);
        // close the html
        out.println("</BODY></HTML>");
              stmt2.close();
             conn.close();
         }catch(SQLException se) {
             System.out.println(se);
    }Message was edited by:
    Altered_Carbon
    Message was edited by:
    Altered_Carbon
    I also realise that this is a more MYSQL titled problem, but those forums look rubbish <_<

    Investigate PreparedStatement.
    Currently you're trying to insert a value "Ufirst_name" instead of the value of the variable called Ufirst_name.
    It's possible to do this (you could do something like this: "... '" + UfirstName + "' ...") but DEFINITELLY NOT RECOMMENDED. Instead use a prepared statement.
    D.

  • Trouble loading JOGL (OpenGL) libraries, java.lang.UnsatisfiedLinkError

    Hello everyone.
    Ok, I went over to jogl.dev.java.net and downloaded jogl.jar and the native files. I extracted jogl.jar to Program Files/java/jre1.5.0_04/lib/ext and the natives to Program Files/java/jre1.5.0_04/bin. I then put the DLL's extracted from the natives into the C:\Windows\System32 (also added the bin directory to the PATH environmental variable, but it couldnt find the jogl.DLL for some reason).
    So i then I write this little piece of code to test if TextPad can find the library:
    public class Greeting {
         public static void main(String[] args) {
              System.loadLibrary("jogl");
    And I get the following error:
    Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\WINDOWS\system32\j
    ogl.dll: Can't find dependent libraries
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1751)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1676)
    at java.lang.Runtime.loadLibrary0(Runtime.java:822)
    at java.lang.System.loadLibrary(System.java:992)
    at Greeting.main(Greeting.java:7)
    Press any key to continue . . .
    So it find's jogl.dll happily enough, but not the dependent libraries. I'm a noob to all this, so not really sure what a Dependent Library is or where I can find it, can anyone help?

    You already figured it out. Dependent libraries are loaded via LD_LIBRARY_PATH just like any other shared libraries on the system. The JVM doesn't control the loading of dependent libraries, so the JVM's library path doesn't apply.
    -slj-

  • Loading an image into an Applet from a JAR file

    Hello everyone, hopefully a simple question for someone to help me with!
    Im trying to load some images into an applet, currently it uses the JApplet.getImage(url) method just before registering with a media tracker, which works but for the sake of efficiency I would prefer the images all to be contained in the jar file as oppossed to being loaded individually from the server.
    Say I have a class in a package eg, 'com.mydomain.myapplet.class.bin' and an images contained in the file structure 'com.mydomain.myapplet.images.img.gif' how do I load it (and waiting for it to be loaded before preceeding?
    I've seen lots of info of the web for this but much of it is very old (pre 2000) and im sure things have changed a little since then.
    Thanks for any help!

    I don't touch applets, so I can't help you there, but here's some Friday Fun: tracking image loading.
    import java.awt.*;
    import java.awt.image.*;
    import java.beans.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.imageio.event.*;
    import javax.imageio.stream.*;
    import javax.swing.*;
    public class ImageLoader extends SwingWorker<BufferedImage, Void> {
        private URL url;
        private JLabel target;
        private IIOReadProgressAdapter listener = new IIOReadProgressAdapter() {
            @Override public void imageProgress(ImageReader source, float percentageDone) {
                setProgress((int)percentageDone);
            @Override public void imageComplete(ImageReader source) {
                setProgress(100);
        public ImageLoader(URL url, JLabel target) {
            this.url = url;
            this.target = target;
        @Override protected BufferedImage doInBackground() throws IOException {
            ImageInputStream input = ImageIO.createImageInputStream(url.openStream());
            try {
                ImageReader reader = ImageIO.getImageReaders(input).next();
                reader.addIIOReadProgressListener(listener);
                reader.setInput(input);
                return reader.read(0);
            } finally {
                input.close();
        @Override protected void done() {
            try {
                target.setIcon(new ImageIcon(get()));
            } catch(Exception e) {
                JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
        //demo
        public static void main(String[] args) throws IOException {
            final URL url = new URL("http://blogs.sun.com/jag/resource/JagHeadshot.jpg");
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    launch(url);
        static void launch(URL url) {
            JLabel imageLabel = new JLabel();
            final JProgressBar progress = new JProgressBar();
            progress.setBorderPainted(true);
            progress.setStringPainted(true);
            JScrollPane scroller = new JScrollPane(imageLabel);
            scroller.setPreferredSize(new Dimension(800,600));
            JPanel content = new JPanel(new BorderLayout());
            content.add(scroller, BorderLayout.CENTER);
            content.add(progress, BorderLayout.SOUTH);
            JFrame f = new JFrame("ImageLoader");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(content);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            ImageLoader loader = new ImageLoader(url, imageLabel);
            loader.addPropertyChangeListener( new PropertyChangeListener() {
                 public  void propertyChange(PropertyChangeEvent evt) {
                     if ("progress".equals(evt.getPropertyName())) {
                         progress.setValue((Integer)evt.getNewValue());
                         System.out.println(evt.getNewValue());
                     } else if ("state".equals(evt.getPropertyName())) {
                         if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
                             progress.setIndeterminate(true);
            loader.execute();
    abstract class IIOReadProgressAdapter implements IIOReadProgressListener {
        @Override public void imageComplete(ImageReader source) {}
        @Override public void imageProgress(ImageReader source, float percentageDone) {}
        @Override public void imageStarted(ImageReader source, int imageIndex) {}
        @Override public void readAborted(ImageReader source) {}
        @Override public void sequenceComplete(ImageReader source) {}
        @Override public void sequenceStarted(ImageReader source, int minIndex) {}
        @Override public void thumbnailComplete(ImageReader source) {}
        @Override public void thumbnailProgress(ImageReader source, float percentageDone) {}
        @Override public void thumbnailStarted(ImageReader source, int imageIndex, int thumbnailIndex) {}
    }

  • How to store serval char variables into a string variable?

    I have serval char variables, but i don't know how to put them together (without using arrays). I am thinking to store these char variables into a string variable but i don't know how to do it. For example,
    char letter1 = 'a', letter2 = 'b', letter3 = 'c';
    String letters;
    then how can i do to make letters = "abc" from using letter1,2,3?
    I am just a beginner of Java, if anyone can help me, i will appreciate that very much!!!

    String letters=""+leter1+letter2+letter3;is fine and dandy. What it actually compiles to is
    String letters = new StringBuffer().append(letter1).append(letter2).append(letter3).toString();Which ofcourse is much more code to write, but still good to know.
    So do see the API for java.lang.StringBuffer.
    Heikki

  • Error While Loading XMl Doc into Oracle Database 10g

    Hi all,
    I have a task that , I have to make a utillity by which we can load XML Doc into a Table. While searching on Internet i found following Procedure on ASK Tom
    CREATE OR REPLACE
    procedure insert_xml_emps(
    p_directory in varchar2, p_filename in varchar2, vtableName in varchar2 )
    as
    v_filelocator bfile;
    v_cloblocator clob;
    l_ctx dbms_xmlsave.ctxType;
    l_rows number;
    begin
    dbms_lob.createtemporary(v_cloblocator,true);
    v_filelocator := bfilename(p_directory, p_filename);
    dbms_lob.open(v_filelocator, dbms_lob.file_readonly);
    DBMS_LOB.LOADFROMFILE(v_cloblocator, v_filelocator,
    dbms_lob.getlength(v_filelocator));
    l_ctx := dbms_xmlsave.newContext(vTableName);
    l_rows := dbms_xmlsave.insertxml(l_ctx,v_cloblocator);
    dbms_xmlsave.closeContext(l_ctx);
    dbms_output.put_line(l_rows || ' rows inserted...');
    dbms_lob.close(v_filelocator);
    DBMS_LOB.FREETEMPORARY(v_cloblocator);
    end ;
    when i try to run this procedure
    BEGIN
    insert_xml_emps('XML_LOAD','load.xml','IBSCOLYTD');
    END;
    it gaves me following Error
    ORA-29532: java call terminated by uncaught java exception : Oracle.xml.sql.OracleXMLSQLException:No
    rows to modify-- the row enclosing tag missing. Specify the correct row enclosing tag.
    ORA-06512: at "SYS.DBMS_XMLSAVE", line 115
    ORA-06512: at "EXT_TEST.INSERT_XML_EMPS", line 18
    ORA-06512: at line 2
    Can anyone describe me this error
    Thanks.
    Best Regards.

    SQL> /* Creating Your table */
    SQL> CREATE TABLE IBSCOLYTD
      2  (
      3  ACTNOI VARCHAR2 (8),
      4  MEMONOI NUMBER (7,0),
      5  MEMODTEI DATE,
      6  AMOUNTI NUMBER (8,0),
      7  BRCDSI NUMBER (4,0),
      8  TYPEI NUMBER (4,0),
      9  TRANSMONI NUMBER (6,0)
    10  );
    Table created.
    SQL> CREATE OR REPLACE PROCEDURE insert_xml_emps(p_directory in varchar2,
      2                                              p_filename  in varchar2,
      3                                              vtableName  in varchar2) as
      4    v_filelocator    BFILE;
      5    v_cloblocator    CLOB;
      6    l_ctx            DBMS_XMLSTORE.CTXTYPE;
      7    l_rows           NUMBER;
      8    v_amount_to_load NUMBER;
      9    dest_offset      NUMBER := 1;
    10    src_offset       NUMBER := 1;
    11    lang_context     NUMBER := DBMS_LOB.DEFAULT_LANG_CTX;
    12    warning          NUMBER;
    13  BEGIN
    14    dbms_lob.createtemporary(v_cloblocator, true);
    15    v_filelocator := bfilename(p_directory, p_filename);
    16    dbms_lob.open(v_filelocator, dbms_lob.file_readonly);
    17    v_amount_to_load := DBMS_LOB.getlength(v_filelocator);
    18    ---  ***This line is changed*** ---
    19    DBMS_LOB.LOADCLOBFROMFILE(v_cloblocator,
    20                              v_filelocator,
    21                              v_amount_to_load,
    22                              dest_offset,
    23                              src_offset,
    24                              0,
    25                              lang_context,
    26                              warning);
    27 
    28    l_ctx := DBMS_XMLSTORE.newContext(vTableName);
    29    DBMS_XMLSTORE.setRowTag(l_ctx, 'ROWSET');
    30    DBMS_XMLSTORE.setRowTag(l_ctx, 'IBSCOLYTD');
    31    -- clear the update settings
    32    DBMS_XMLStore.clearUpdateColumnList(l_ctx);
    33    -- set the columns to be updated as a list of values
    34    DBMS_XMLStore.setUpdateColumn(l_ctx, 'ACTNOI');
    35    DBMS_XMLStore.setUpdateColumn(l_ctx, 'MEMONOI');
    36    DBMS_XMLStore.setUpdatecolumn(l_ctx, 'MEMODTEI');
    37    DBMS_XMLStore.setUpdatecolumn(l_ctx, 'AMOUNTI');
    38    DBMS_XMLStore.setUpdatecolumn(l_ctx, 'BRCDSI');
    39    DBMS_XMLStore.setUpdatecolumn(l_ctx, 'TYPEI');
    40    DBMS_XMLStore.setUpdatecolumn(l_ctx, 'TRANSMONI');
    41    -- Now insert the doc.
    42    l_rows := DBMS_XMLSTORE.insertxml(l_ctx, v_cloblocator);
    43    DBMS_XMLSTORE.closeContext(l_ctx);
    44    dbms_output.put_line(l_rows || ' rows inserted...');
    45    dbms_lob.close(v_filelocator);
    46    DBMS_LOB.FREETEMPORARY(v_cloblocator);
    47  END;
    48  /
    Procedure created.
    SQL> BEGIN
      2  insert_xml_emps('TEST_DIR','load.xml','IBSCOLYTD');
      3  END;
      4  /
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM ibscolytd;
    ACTNOI      MEMONOI MEMODTEI     AMOUNTI     BRCDSI      TYPEI  TRANSMONI
    28004125     251942 05-SEP-92        400        513          1          0
    28004125     251943 04-OCT-92        400        513          1          0
    SQL>

  • How to use host variable in Java?

    How do I use host variable in java? I am getting SQL code of -404 and description of SQL code is The UPDATE or INSERT statement specifies a String that is too long column-name SQLSTATE=22001. Below is my code:
    * i n s e r t M e s s a g e
    * insertMessage: This method will retrive detail message and other fields for
    * selected item from screen1.
    public final Collection insertMessage(String businessId,String messageNumber,String messageType,
    String messageTitle,String printStyle,String statusIndicator,
    String approverId,String lastUpdateId,String longMessage) {
    MessageTransport msi = new MessageTransport();
    PreparedStatement ps = null;
    Connection connection = null;
    MessageTransport msi1 = new MessageTransport();
    PreparedStatement ps1 = null;
    Connection connection1 = null;
    ArrayList list = new ArrayList();
    try {
    if (businessId != null) {
    businessId = businessId.trim();
    if (messageNumber != null) {
    messageNumber = messageNumber.trim();
    if (messageType != null) {
    messageType = messageType.trim();
    if (messageTitle != null) {
    messageTitle = messageTitle.trim();
    if (printStyle != null) {
    printStyle = printStyle.trim();
    if (statusIndicator != null) {
    statusIndicator = statusIndicator.trim();
    if (approverId != null) {
    approverId = approverId.trim();
    if (lastUpdateId != null) {
    lastUpdateId = lastUpdateId.trim();
    if (longMessage != null) {
    longMessage = longMessage.trim();
    int len = longMessage.length();
    if (len > 254) {
    int constant = 254;
    int k = len % constant; //k will hold value that has number of loops including initial insert.
    k = k - 1; //this is for total number of loop.
    int j = len / constant; //this will have remainder if any to insert rest of longmessage.
    System.out.println("Display remainder: " + k);
    System.out.println("Display divisible: " + j);
    System.out.println("Display Length of longMessage: " + len);
    StringBuffer sql = new StringBuffer();
    sql.append("INSERT INTO " + MESSAGE_TBL + " ( MT_BUS_ID,MT_MSG_NBR,MT_MSG_TYPE,MT_MSG_TITLE,MT_PRINT_STYLE,MT_APV_STATUS,MT_APV_ID,MT_APV_DT,MT_APV_TM,MT_LAST_UPDATE_ID,MT_LAST_UPDATE_DT,MT_LAST_UPDATE_TM,MT_MSG_TXT ) VALUES ");
    sql.append("(");
    sql.append("'");
    sql.append(businessId).append("'");
    sql.append(",").append(messageNumber);
    sql.append(",").append("'I'");
    sql.append(",").append("'").append(messageTitle).append("'");
    sql.append(",").append("'").append(printStyle).append("'");
    sql.append(",").append("'P'");
    sql.append(",").append("' '");
    sql.append(",").append("CURRENT DATE");
    sql.append(",").append("CURRENT TIME");
    sql.append(",").append("'").append(lastUpdateId).append("'");
    sql.append(",").append("CURRENT DATE");
    sql.append(",").append("CURRENT TIME");
    sql.append(",").append("'").append(longMessage).append("'");
    sql.append(")");
    System.out.println("Display SQL Statement: " + sql);
    connection = DriverManager.getConnection(DATABASE_URI, USER, PASS);
    ps = connection.prepareStatement(sql.toString());
    ps.executeUpdate();
    System.out.println("Refreshed Record: ");
    catch (SQLException sqle) {
    System.out.println("SQLException: "+ sqle + ". SQLSTATE=" + sqle.getSQLState()+" SQLCODE=" + sqle.getErrorCode());
    finally {
    if (ps != null) {
    try {
    ps.close();
    ps=null;
    catch (Exception e) {}
    if (ps1 != null) {
    try {
    ps1.close();
    ps1=null;
    catch (Exception e) {}
    if (connection != null) {
    try {
    connection.close();
    connection = null;
    catch (Exception e) {}
    if (connection1 != null) {
    try {
    connection1.close();
    connection1 = null;
    catch (Exception e) {}
    return list;
    if my longMessage is smaller like one line then everything works fine, but as soon as my longMessage if greater than 254 it starts giving me -404. How do I work around or Is there any way to use host variable in Java?
    All kind of help is appreciated. Any question then please email me at [email protected].
    Thank you.

    This is what you got to do to insert a larger value.
    //Assuming that message length is less than 254+ 254 characters.
    //If larger then run the update loop that many times.
    String longMessage = "Blah blah ... ";
    String firstPart = "";
    String secondPart = "";
    int messageLength = longMessage.length();
    if (messageLength > 254)
         try
              firstPart = longMessage.subString(0, 253);
              secondPart = longMessage.subString(254, message);
         catch (IndexOutOfBoundsException e)
    //In the first insert  set the first 254 characters
    ps.setString(1, firstPart);
    int result = ps.executeUpdate();
    if (result != 0)
           System.out.println("Insert  sucessful  ");
           if (messageLength > 254)
                //now update with the second part.
                static String UPDATE_SECOND_PART = UPDATE my.table SET LONG_COL = LONG_COL || ? WHERE KEY_COL = ?;
                ps2 = connection.getPreparedStatement(UPDATE_SECOND_PART);
                ps2.setString(1, secondPart);
                ps2.setString(2, businessId);  //assuming that businessId is the primary key.
                int result2 = ps2.executeUpdate();
                if (result2 != 0)
                      System.out.println("Update  sucessful  ");
                else
                     System.out.println("Update failed ");
    else
           System.out.println("Insert failed ");
    }Hope this helps.

  • Best method to load XML data into Oracle

    Hi,
    I have to load XML data into Oracle tables. I tried using different options and have run into a dead end in each of those. I do not have knowledge of java and hence have restricted myself to PL/SQL solutions. I tried the following options.
    1. Using DBMS_XMLSave package : Expects the ROWSET and ROW tags. Connot change format of the incoming XML file (Gives error oracle.xml.sql.OracleXMLSQLException: Start of root element expected).
    2. Using the XMLPARSER and XMLDOM PL/SQL APIs : Works fine for small files. Run into memory problems for large files (Gives error java.lang.OutOfMemoryError). Have tried increasing the JAVA_POOL_SIZE but does not work. I am not sure whether I am changing the correct parameter.
    I have read that the SAX API does not hog memory resources since it does not build the entire DOM tree structure. But the problem is that it does not have a PL/SQL implementation.
    Can anyone PLEASE guide me in the right direction, as to the best way to achieve this through PL/SQL ??? I have not designed the tables so am flexible on using purely relational or object-relational design. Although would prefer to keep a purely relational design. (Had tried used object-relational for 1. and purely relational for 2. above)
    The XML files are in the following format, (EXAMINEEs with single DEMOGRAPHIC and multiple TESTs)
    <?xml version="1.0"?>
    <Root_Element>
    <Examinee>
    <MACode>A</MACode>
    <TestingJID>TN</TestingJID>
    <ExamineeID>100001</ExamineeID>
    <CreateDate>20020221</CreateDate>
    <Demographic>
    <InfoDate>20020221</InfoDate>
    <FirstTime>1</FirstTime>
    <LastName>JANE</LastName>
    <FirstName>DOE</FirstName>
    <MiddleInitial>C</MiddleInitial>
    <LithoNumber>73</LithoNumber>
    <StreetAddress>SomeAddress</StreetAddress>
    <City>SomeCity</City>
    <StateCode>TN</StateCode>
    <ZipCode>37000</ZipCode>
    <PassStatus>1</PassStatus>
    </Demographic>
    <Test>
    <TestDate>20020221</TestDate>
    <TestNbr>1</TestNbr>
    <SrlNbr>13773784</SrlNbr>
    </Test>
    <Test>
    <TestDate>20020221</TestDate>
    <TestNbr>2</TestNbr>
    <SrlNbr>13773784</SrlNbr>
    </Test>
    </Examinee>
    </Root_Element>
    Thanks for the help.

    Please refer to the XSU(XML SQL Utility) or TransX Utility(for Multi-language Document) if you want to load data in XML format into database.
    Both of them require special XML formats, please first refer to the following docs:
    http://otn.oracle.com/docs/tech/xml/xdk_java/doc_library/Production9i/doc/java/xsu/xsu_userguide.html
    http://otn.oracle.com/docs/tech/xml/xdk_java/doc_library/Production9i/doc/java/transx/readme.html
    You can use XSLT to transform your document to the required format.
    If you document is large, you can use SAX method to insert data into database. But you need to write the code.
    The following sample may be useful:
    http://otn.oracle.com/tech/xml/xdk_sample/xdksample_040602i.html

  • How to pass a jsp variable into javascript??

    <p><%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
    <p><%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
    <p><html>
    <p><c:set var="binrmapi" value="http://localhost/paas-api/bingorooms.action;jsessionid=XXXXXX?userId=TEST2&sessionId=1&key=1" />
    <p><c:import var="testbinrm" url="${fn:replace(binrmapi, 'XXXXXX', jsessionid)}"/>
    <p><c:set var="tuples" value="${fn:split(testbinrm, '><')}" />
    <p>Time until next game
    <p><c:forEach var="tuple" items="${tuples}">
    <p><c:if test="${fn:contains(tuple, 'row ')}">
    <p> <p><code>
    <p> <c:set var="values" value="${fn:split(tuple, '=\"')}" />
    <p> <font color="blue">
    <p> <c:out value="${values[17]}" />
    <p><c:set var="remainingtime" value="${values[17]}" />
    <p> </font>
    <p> </code>
    <p></c:if>
    <p></c:forEach>
    <p><form name="counter"><input type="text" size="8" name="d2"></form>
    <p><script>
    <p>var milisec=0
    <p>var seconds=eval("document.myForm.remaining").value;
    <p>function display(){
    <p> if (milisec<=0){
    <p> milisec=9
    <p> seconds-=1
    <p>}
    <p>if (seconds<=-1){
    <p> milisec=0
    <p> seconds+=1
    <p> }
    <br>else
    <p> milisec-=1
    <p> document.counter.d2.value=seconds+"."+milisec
    setTimeout("display()",100)
    <p>}
    <p>display()
    <p></script>
    <p></body>
    <p></html>
    <p>This is my code that i was working on, in the jsp part of the script, i get a api call and save a value of time in the variable remainingtime.. and in the javascript, i try to have a countdown clock counting down the remaining time.. but i guess it doesnt work.. how can i get that working? thanks alot
    Message was edited by:
    hamham3001
    Message was edited by:
    hamham3001
    Message was edited by:
    hamham3001
    Message was edited by:
    hamham3001

    Re: How to pass a jsp variable into javascript??Here is the sameple one, hope it will solves your problem.
    <html>
    <body>
    <form name=f>
    <%!
    String str = "A String"
    %>
    <script>
    var avariable = <%=str%>
    <script>
    </form>
    </body>
    </html>
    Let me know if you face any problem

Maybe you are looking for

  • IiPhone - Outlook 2007 Contact map

    Where can I find the default contact fields map that iTunes uses to to sync Outlook 2007 with iPhone? Can it be modified. I do not currently have an iPhone.

  • Disk size: 4.0 vs 4.7

    My dvd disks say that they are 4.7G but iDVD will only write 4.0G to them. Is there any way I can use the 0.7G??? -Jake

  • Pls pls pls help :(

    ok im a minor 12 yrs old i created a apple id for the first time on my iphone 4 ios 5.1.1 it asked me to verify the id i wen there but it asked for A PAYMENT option i hv no credit card obviously but it dosent allow me to verify mi id now (us app stor

  • Rotate a bob image

    hi, I need to rotate a blob image and place it on a JLabel. can anyone help me to do that. it is really urgent thx in advance

  • PekWM - installing themes

    I have installed pekWM and wanted to get rid of the amazing standard theme. So, I grabbed Elegant-Brit from lyra, put it into /usr/share/pekwm/themes and tried to run it. Right-click > Pekwm > Reload; again Right-click > Pekwm > Themes > Elegant-Brit