Help with Java JNI and C++

Hi everyone! I have a problem with Hello World example. I wrote java code in Visual Age 4.0:
<HelloGinja.java>
package jnitest;
public class HelloGinja {
     static {
          System.load("c://c++//hellotest//release//hellotest.dll");
      * HelloGinja constructor comment.
     public HelloGinja() {
          super();
     public native void displayHelloGinja();
     public static void main (String args[]) {
          System.out.println("Calling displayHelloGinja...\n");
          new HelloGinja().displayHelloGinja();
          System.out.println("Finished displayHelloGinja...\n");
}I made header file from command line:
javah -jni jnitest.HelloGinja
I wrote C++ code in Visual Studio 6.0:
<hellotest.cpp>
#include "stdafx.h"
#include "hellotest.h"
#include <jni.h>
#include "jnitest_HelloGinja.h"
#include <stdio.h>
BOOL APIENTRY DllMain( HANDLE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
    switch (ul_reason_for_call)
          case DLL_PROCESS_ATTACH:
          case DLL_THREAD_ATTACH:
          case DLL_THREAD_DETACH:
          case DLL_PROCESS_DETACH:
               break;
    return TRUE;
// This is an example of an exported variable
HELLOTEST_API int nHellotest=0;
// This is an example of an exported function.
HELLOTEST_API int fnHellotest(void)
     return 42;
// This is the constructor of a class that has been exported.
// see hellotest.h for the class definition
CHellotest::CHellotest()
     return;
extern "C" {
     JNIEXPORT void JNICALL Java_jnitest_HelloGinja_displayHelloGinja(JNIEnv *env, jobject obj)
          printf("\nHello Ginja Glisic!\n");
          return;
}What is the problem? I compile program well but when I run it from VAJ I am getting:
Calling displayHelloGinja...
Finished displayHelloGinja...
It seems like it does not call native method at all. I exported file out from VAJ and run it from command line.I got:
Calling displayHelloGinja...
Hello Ginja Glisic!
Finished displayHelloGinja...
Everything is ok.It works. why then it won't work in VAJ?
Can anyone have idea? I will be very thankfull for any help or advice.

Ok, I solved my problem. I returned string from native method to java code and I got it. The point is native method is being called but I couldn't see it's output from VAJ.
Does anyone know any good tutorial about VAJ? If does, please post it .

Similar Messages

  • Help with Java program and PKGBUILD

    Hey guys, I'm fairly new to Arch and very new to making packages. I write a lot of my stuff in Java, and I know that Java is normally a pain to package on Linux systems. I have had a good look at the Java Packaging Guidelines, http://wiki.archlinux.org/index.php/Jav … Guidelines and I see that it says about not bothering compiling from Java source and just provide the JARs (am I correct?). So my question is, if I were to make a PKGBUILD for my Java based program, would the build() block just basically create the folders in the filesystem and move the content (JARs etc) to the folders? And then create the shell script in the appropriate location?
    Forgive me I have the completely wrong idea...
    Many thanks

    Hey guys, I'm fairly new to Arch and very new to making packages. I write a lot of my stuff in Java, and I know that Java is normally a pain to package on Linux systems. I have had a good look at the Java Packaging Guidelines, http://wiki.archlinux.org/index.php/Jav … Guidelines and I see that it says about not bothering compiling from Java source and just provide the JARs (am I correct?). So my question is, if I were to make a PKGBUILD for my Java based program, would the build() block just basically create the folders in the filesystem and move the content (JARs etc) to the folders? And then create the shell script in the appropriate location?
    Forgive me I have the completely wrong idea...
    Many thanks

  • Need help with Java MIDI and VST info

    I am currently a college student for programming and I know programming very well, but for this current task, I am completely stuck. This is not a school project or work, just a personal project I'm working on at the moment to learn more about Java.
    What I am trying to create is a VST (Virtual Studio Synthesizer) using Java for use in music programs such as FL Studio, Sonar, Ableton, and so on. I did alot of Googling and found the following program:
    [http://jvaptools.sourceforge.net/index.html]
    I got it working, but it's not quite what I am looking for (it's more like an on-site editor that you enter code into and then run it). I want to create a VST from scratch and learn what each thing means in the program. I've done some research on MIDI input and output and found the following in the Java documentation:
    [http://java.sun.com/javase/6/docs/api/javax/sound/midi/MidiDevice.html]
    I figured I'm on track of what I'm looking for, but the problem is that the Java documentation simply sucks. It has no examples of code, how the functions work, and how I'm suppose to use them.
    First off, I want to start with the extreme bare basics. Is it even possible to do a VST in JUST Java? I've seen and used examples of obtaining data from a MIDI file and playing it, but that's not what I'm trying to do. Second, how would I take MIDI data from a music program running the VST and enter the data into a text box? Once I'm able to do that, I should be able to work with the data to produce audio output.
    My program I am attempting to make is a guitar synthesizer that I can run in music programs as a VST. If anyone around here knows anything about MIDI and VST plugins, please, post some example code and help point me in the right direction to creating something. I'm not looking to use other people's programs or code, I want to make something myself from scratch but I don't know where to start!

    Programming guide
    [http://java.sun.com/j2se/1.5.0/docs/guide/sound/programmer_guide/contents.html]
    Examples...
    [http://www.jsresources.org/examples/]

  • Need help with Java Beans and PDA

    How can I get Java Bean applets to work on a PDA, with either Palm or Pocket PC?

    first hit on google
    thankyou for using the georgemc google proxy

  • Help with java mapping

    PI File adapter has a processing option u2018Empty-Message Handlingu2019 to ignore or Write Empty Files. In case there is no data created after mapping on target side then this option determines whether to write an empty file or not. But there is a catch to this option when it comes to using it with File Content Conversion which is described in SAP Note u2018821267u2019. It states following:
    I configure the receiver channel with File content conversion mode and I set the 'Empty Message Handling' option to ignore. Input payload to the receiver channel is generated out of mapping and it does not have any record sets. However, this payload has a root element. Why does file receiver create empty output file with zero byte size in the target directory?  Example of such a payload generated from mapping is as follows:                                                           
    <?xml version="1.0" encoding="UTF-8"?>                          
    <ns1:test xmlns:ns1="http://abcd.com/ab"></ns1:test>
    solution :
    If the message payload is empty (i.e., zero bytes in size), then File adapter's empty message handling feature does NOT write files into the target directory. On the other hand, if the payload is a valid XML document (as shown in example) that is generated from mapping with just a root element in it, the File Adapter does not treat it as an empty message and accordingly it writes to the target directory. To achieve your objective of not writing files (that have just a single root element) into the target directory, following could be done:
    Using a Java or ABAP Mapping in order to restrict the creation of node itself during mapping. (This cannot be achieved via Message Mapping)
    Using standard adapter modules to do content conversion first and then write file. 
    can someone help with java mapping that can be used in this case?

    Hi,
        You have not mentioned the version of PI you are working in. In case you are working with PI 7.1 or above then here is the java mapping code you need to add after message mapping in the same interface mapping
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import com.sap.aii.mapping.api.AbstractTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    import com.sap.aii.mapping.api.TransformationInput;
    import com.sap.aii.mapping.api.TransformationOutput;
    public class RemoveRootNode extends AbstractTransformation{
         public void execute(InputStream in, OutputStream out)
         throws StreamTransformationException {
    // TODO Auto-generated method stub
    try
         DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
         DocumentBuilder builderel=factory.newDocumentBuilder();
         /*input document in form of XML*/
         Document docIn=builderel.parse(in);
         /*document after parsing*/
         Document docOut=builderel.newDocument();
         TransformerFactory tf=TransformerFactory.newInstance();
         Transformer transform=tf.newTransformer();
         if(docIn.getDocumentElement().hasChildNodes())
              docOut.appendChild(docOut.importNode(docIn.getDocumentElement(),true));
              transform.transform(new DOMSource(docOut), new StreamResult(out));
         else
              out.write(null);
    catch(Exception e)
    public void setParameter(Map arg0) {
    // TODO Auto-generated method stub
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    try{
         RemoveRootNode genFormat=new RemoveRootNode();
         FileInputStream in=new FileInputStream("C:\\apps\\sdn\\rootNode.xml");
         FileOutputStream out=new FileOutputStream("C:\\apps\\sdn\\rootNode1.xml");
         genFormat.execute(in,out);
         catch(Exception e)
         e.printStackTrace();
    public void transform(TransformationInput arg0, TransformationOutput arg1)
              throws StreamTransformationException {
         // TODO Auto-generated method stub
         this.execute(arg0.getInputPayload().getInputStream(), arg1.getOutputPayload().getOutputStream());
    In case you are working in PI 7.0 you can use this code
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    public class RemoveRootNode implements StreamTransformation{
         public void execute(InputStream in, OutputStream out)
         throws StreamTransformationException {
    // TODO Auto-generated method stub
    try
         DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
         DocumentBuilder builderel=factory.newDocumentBuilder();
         /*input document in form of XML*/
         Document docIn=builderel.parse(in);
         /*document after parsing*/
         Document docOut=builderel.newDocument();
         TransformerFactory tf=TransformerFactory.newInstance();
         Transformer transform=tf.newTransformer();
         if(docIn.getDocumentElement().hasChildNodes())
              docOut.appendChild(docOut.importNode(docIn.getDocumentElement(),true));
              transform.transform(new DOMSource(docOut), new StreamResult(out));
         else
              out.write(null);
    catch(Exception e)
    public void setParameter(Map arg0) {
    // TODO Auto-generated method stub
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    try{
         RemoveRootNode genFormat=new RemoveRootNode();
         FileInputStream in=new FileInputStream("C:\\apps\\sdn\\rootNode.xml");
         FileOutputStream out=new FileOutputStream("C:\\apps\\sdn\\rootNode1.xml");
         genFormat.execute(in,out);
         catch(Exception e)
         e.printStackTrace();
    The code for PI 7.0 should also work for PI 7.1 provided you use the right jar files for compilation, but vice-versa is not true.
    Could you please let us know if this code was useful to you or not?
    Regards
    Anupam
    Edited by: anupamsap on Dec 15, 2011 9:43 AM

  • Need help with Blog, Wiki and Gallery

    Hi Team,
    Need help with Blog, Wiki and Gallery startup. I have newly started visiting forums and quite interested to contribute towards these areas also.
    Please help.
    Thanks,
    Santosh Singh
    Santosh Singh

    Hello Santhosh,
    Blog is for Microsoft employees only. However, you can contribute towards WIKI and GALLERY using the below links.
    http://social.technet.microsoft.com/wiki/
    http://gallery.technet.microsoft.com/

  • New @ RMI need help with  java.rmi.UnmarshalException: error unmarshalling

    Hi @ all out there,
    I'm new with Java RMI and have to write a EventSystem for an college project where clients can subscribe to a topic and get notified when someone publishes a message to the subscribed topic.
    At server-side I have a class called EventSystem that provides methods for subscribing and unsubscribing from topics, and also for posting messages (for publishers).
    To subscribe i thought that the client must specify the topic and also itself ( means that a client calls in this way: obj.subscribe("mytopic", this).
    The EventSystem handles a list of all clients, and whenever a new message is posted it goes trough all clients and invokes the handleMessage(String msg) method that all Clients have to provide.
    On my local machine without RMi this concept works just great.
    I now tried to get it working using RMI , but I get the following Exception when starting the client (the server starts fine) :
    Looking up for rmiregistry at 138.232.248.22:1099
    Subscriber exception:
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
            java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
            java.io.InvalidClassException: SubscriberImpl; SubscriberImpl; class invalid for deserialization
            at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:336)
            at sun.rmi.transport.Transport$1.run(Transport.java:159)
            at java.security.AccessController.doPrivileged(Native Method)
            at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
            at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
            at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
            at java.lang.Thread.run(Thread.java:619)
            at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:255)
            at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:233)
            at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:142)
            at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:178)
            at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:132)
            at $Proxy0.subscribe(Unknown Source)
            at SubscriberImpl.main(SubscriberImpl.java:48)
    Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
            java.io.InvalidClassException: SubscriberImpl; SubscriberImpl; class invalid for deserialization
            at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:293)
            at sun.rmi.transport.Transport$1.run(Transport.java:159)
            at java.security.AccessController.doPrivileged(Native Method)
            at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
            at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
            at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
            at java.lang.Thread.run(Thread.java:619)
    Caused by: java.io.InvalidClassException: SubscriberImpl; SubscriberImpl; class invalid for deserialization
            at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:713)
            at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1733)
            at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
            at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
            at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:306)
            at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:290)
            ... 9 more
    Caused by: java.io.InvalidClassException: SubscriberImpl; class invalid for deserialization
            at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:587)
            at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1583)
            at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
            at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1732)
            ... 13 moreI googled now for 2 hours but can't resolve the problem alone. As far as I can understand I have to serialize Objects that I want to send to the server, right?
    So how can i do this? I've never used serialization till now.
    any ideas how to solve this problem?
    greets from italy and sorry for my very weak english
    bd_italy

    A class has been modified after deployment. Stop the Registry, clean, recompile, and redeploy.

  • What's the phone number I should call for help with my iPhone and ihome dock?

    What's the phone number I should call for help with my iPhone and ihome dock?

    http://www.ihomeaudio.com/support/

  • Help with photoshop quitting and AMD graphics

    help with photoshop quitting and AMD graphics
    im not a techy, but it appears i have to do someting with my amd graphics card - this might be why my software is crashing - ive no idea what to do though

    Hi Chris
    I have tried to go on the website, then i tried to download the automatic detect because i wasnt sure which driver i had or needed - but it has just downloaded a load of game software - which i dont want ( i dont think)
    i have find out my laptop has a amd radeon HD 8750M card, but i dont know what im doing! i would hate to mess my computer up as i am in thailand with no one to help me!
    its frustrating as i am paying for CC but cant use it!

  • Set role with Java JPA and NativeSQL

    Hi,
    using 10g setting roles with Java JPA and NativeSQL works fine. After the upgrade to 11g the same commands will not work.
    Ars ther any significant changes to set roles in 11g?
    Regards
    Siegwin

    siegwin.port wrote:
    using 10g setting roles with Java JPA and NativeSQL works fine. After the upgrade to 11g the same commands will not work.
    Ars ther any significant changes to set roles in 11g?When I eval'd 11g, I did not notice any changes in setting my roles. I did notice a significant difference in Java. I cannot remember the JDK version change from 10g to 11g. We ended up settling back to 10g for other reasons.

  • Help with java coding involving stacks and queues.

    I was wondering if anyone can help with tips on what to fill in for the coding.
    My project is to creating a word processor by the process of 2 stacks. The methods are given, but I'm not really sure what goes in them. So I was wonder if anyone can answer this for me, or give tips that would be great thanks.
    Example Code, similar to what were suppose to do, but instead it's CHARACTER stacks rather than String.
    [http://www.cs.jhu.edu/~jason/226/hw3/source/EditableString.java]

    /** Stack of Characters to the left of the cursor; the ones
       * near the top of the stack are closest to the cursor.
      private Stack left;
      /** Stack of Characters to the right of the cursor; the ones
       * near the top of the stack are closest to the cursor.
      private Stack right;Do you know how a stack works?
    No - Google it
    Yes - Continue on with this post
    /** Another constructor.
       * @param left The text to the left of the cursor.
       * @param right The text to the right of the cursor.
      public EditableString(String left, String right) {
        // fill this in
      }Do you know how to read?
    No - How did you answer this question then?
    Yes - Then why can't you read the comments above each method. Is it really that hard to understand?
    Mel

  • Help with java and adobe

    I have CS6 and ever since I installed Yosemite on my mac none of my adobe products will open and it keeps giving me a message saying I must install legacy java se 6. I updated my java already and I am still running into issues. Please help

    needhelpnow,
    Did you download from here,
    http://support.apple.com/kb/DL1572
    or what happens if you do?

  • Problem with java look and feel

    Hi! This is my first time posting here. Do apologize me if I am not familiar with the regulations here. Thanks!
    Currently, I am developing a project using NetBeans IDE. It is using RMI, and some basic UI. I am facing the following error when I tried applying the java look and feel code. Please see below for the code used and the error message.
    try {   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception e) { }
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.plaf.ColorUIResource cannot be cast to java.util.List
    at javax.swing.plaf.metal.MetalUtils.drawGradient(MetalUtils.java:196)
    at javax.swing.plaf.metal.MetalInternalFrameTitlePane.paintComponent(MetalInternalFrameTitlePane.java:384)
    at javax.swing.JComponent.paint(JComponent.java:1027)
    at javax.swing.JComponent.paintChildren(JComponent.java:864)
    at javax.swing.JComponent.paint(JComponent.java:1036)
    at javax.swing.JComponent.paintChildren(JComponent.java:864)
    at javax.swing.JComponent.paint(JComponent.java:1036)
    at javax.swing.JLayeredPane.paint(JLayeredPane.java:564)
    at javax.swing.JComponent.paintChildren(JComponent.java:864)
    at javax.swing.JComponent.paint(JComponent.java:1036)
    at javax.swing.JComponent.paintChildren(JComponent.java:864)
    at javax.swing.JComponent.paint(JComponent.java:1036)
    at javax.swing.JLayeredPane.paint(JLayeredPane.java:564)
    at javax.swing.JComponent.paintChildren(JComponent.java:864)
    at javax.swing.JComponent.paintToOffscreen(JComponent.java:5129)
    at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:285)
    at javax.swing.RepaintManager.paint(RepaintManager.java:1128)
    at javax.swing.JComponent.paint(JComponent.java:1013)
    at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
    at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
    at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
    at java.awt.Container.paint(Container.java:1797)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:734)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:679)
    at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:659)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Java Result: 1

    Thanks for everyone's help!
    Below is the executable code generated using NetBeans which is enough to generate the error message. Sometimes you can get the error message just by running the program. Sometimes the error will occur when you go into the Menu and click on Item.
    * NewJFrame.java
    * Created on January 8, 2008, 1:11 PM
    package client;
    import javax.swing.UIManager;
    * @author  Yang
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jDesktopPane1 = new javax.swing.JDesktopPane();
            jInternalFrame1 = new javax.swing.JInternalFrame();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            jMenuItem1 = new javax.swing.JMenuItem();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
            jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
            jInternalFrame1Layout.setHorizontalGroup(
                jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 190, Short.MAX_VALUE)
            jInternalFrame1Layout.setVerticalGroup(
                jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 95, Short.MAX_VALUE)
            jInternalFrame1.setBounds(80, 40, 200, 130);
            jDesktopPane1.add(jInternalFrame1, javax.swing.JLayeredPane.DEFAULT_LAYER);
            jMenu1.setText("Menu");
            jMenuItem1.setText("Item");
            jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenuItem1ActionPerformed(evt);
            jMenu1.add(jMenuItem1);
            jMenuBar1.add(jMenu1);
            setJMenuBar(jMenuBar1);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE)
                    .addGap(20, 20, 20))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
            pack();
        }// </editor-fold>                       
        private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
            jInternalFrame1.setVisible(true);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
        // Variables declaration - do not modify                    
        private javax.swing.JDesktopPane jDesktopPane1;
        private javax.swing.JInternalFrame jInternalFrame1;
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JMenuItem jMenuItem1;
        // End of variables declaration                  
    }Edited by: Boxie on Jan 7, 2008 11:23 PM

  • Help with Java script

    So , I edited the ITunes.java as described in the Admin guide.Copied the .class to my cgi folder in the server.I copied the itunesu file from the shell folder of the sample code.I have modified it accordingly.But when I run it in browser(Firefox) as ..../cgi-bin/itunesu it just gives me a blank page.Nothing shows up.I ran the ITunes.java file locally and it generates an HTML output, which I copied and created a new html.After I run this HTML file, it opens my itunes, but again it says page not found and url contains https://www.xxx.edu/cgi-bin/itunesu?destination=xxx.edu where xxx is my institution name.Not sure if I am supposed to display my institution name in forum.
    The admin guide says on page 15 step 4.Copy the itunes.class file and other itunes file to your web server's cgi-bin directory.
    I am not quiet sure what does other itunes file mean??
    This is how my .java file looks.
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.util.*;
    * The <CODE>ITunesU</CODE> class permits the secure transmission
    * of user credentials and identity between an institution's
    * authentication and authorization system and iTunes U.
    * The code in this class can be tested by
    * running it with the following commands:
    * <PRE>
    * javac ITunesU.java
    * java ITunesU</PRE>
    * Changes to values defined in this class' main() method must
    * be made before it will succesfully communicate with iTunes U.
    public class ITunesU extends Object {
    * Generate the HMAC-SHA256 signature of a message string, as defined in
    * RFC 2104.
    * @param message The string to sign.
    * @param key The bytes of the key to sign it with.
    * @return A hexadecimal representation of the signature.
    public String hmacSHA256(String message, byte[] key) {
    // Start by getting an object to generate SHA-256 hashes with.
    MessageDigest sha256 = null;
    try {
    sha256 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
    throw new java.lang.AssertionError(
    this.getClass().getName()
    + ".hmacSHA256(): SHA-256 algorithm not found!");
    // Hash the key if necessary to make it fit in a block (see RFC 2104).
    if (key.length > 64) {
    sha256.update(key);
    key = sha256.digest();
    sha256.reset();
    // Pad the key bytes to a block (see RFC 2104).
    byte block[] = new byte[64];
    for (int i = 0; i < key.length; ++i) block = key;
    for (int i = key.length; i < block.length; ++i) block = 0;
    // Calculate the inner hash, defined in RFC 2104 as
    // SHA-256(KEY ^ IPAD + MESSAGE)), where IPAD is 64 bytes of 0x36.
    for (int i = 0; i < 64; ++i) block ^= 0x36;
    sha256.update(block);
    try {
    sha256.update(message.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
    throw new java.lang.AssertionError(
    "ITunesU.hmacSH256(): UTF-8 encoding not supported!");
    byte[] hash = sha256.digest();
    sha256.reset();
    // Calculate the outer hash, defined in RFC 2104 as
    // SHA-256(KEY ^ OPAD + INNER_HASH), where OPAD is 64 bytes of 0x5c.
    for (int i = 0; i < 64; ++i) block ^= (0x36 ^ 0x5c);
    sha256.update(block);
    sha256.update(hash);
    hash = sha256.digest();
    // The outer hash is the message signature...
    // convert its bytes to hexadecimals.
    char[] hexadecimals = new char[hash.length * 2];
    for (int i = 0; i < hash.length; ++i) {
    for (int j = 0; j < 2; ++j) {
    int value = (hash >> (4 - 4 * j)) & 0xf;
    char base = (value < 10) ? ('0') : ('a' - 10);
    hexadecimals[i * 2 + j] = (char)(base + value);
    // Return a hexadecimal string representation of the message signature.
    return new String(hexadecimals);
    * Combine user credentials into an appropriately formatted string.
    * @param credentials An array of credential strings. Credential
    * strings may contain any character but ';'
    * (semicolon), '\\' (backslash), and control
    * characters (with ASCII codes 0-31 and 127).
    * @return <CODE>null</CODE> if and only if any of the credential strings
    * are invalid.
    public String getCredentialsString(String[] credentials) {
    // Create a buffer with which to generate the credentials string.
    StringBuffer buffer = new StringBuffer();
    // Verify and add each credential to the buffer.
    if (credentials != null) {
    for (int i = 0; i < credentials.length; ++i) {
    if (i > 0) buffer.append(';');
    for (int j = 0, n = credentials.length(); j < n; ++j) {
    char c = credentials.charAt(j);
    if (c != ';' && c != '\\' && c >= ' ' && c != 127) {
    buffer.append(c);
    } else {
    return null;
    // Return the credentials string.
    return buffer.toString();
    * Combine user identity information into an appropriately formatted string.
    * @param displayName The user's name (optional).
    * @param emailAddress The user's email address (optional).
    * @param username The user's username (optional).
    * @param userIdentifier A unique identifier for the user (optional).
    * @return A non-<CODE>null</CODE> user identity string.
    public String getIdentityString(String displayName, String emailAddress,
    String username, String userIdentifier) {
    // Create a buffer with which to generate the identity string.
    StringBuffer buffer = new StringBuffer();
    // Define the values and delimiters of each of the string's elements.
    String[] values = { displayName, emailAddress,
    username, userIdentifier };
    char[][] delimiters = { { '"', '"' }, { '<'(', ')' }, { '[', ']' } };
    // Add each element to the buffer, escaping
    // and delimiting them appropriately.
    for (int i = 0; i < values.length; ++i) {
    if (values != null) {
    if (buffer.length() > 0) buffer.append(' ');
    buffer.append(delimiters[0]);
    for (int j = 0, n = values.length(); j < n; ++j) {
    char c = values.charAt(j);
    if (c == delimiters[1] || c == '\\') buffer.append('\\');
    buffer.append(c);
    buffer.append(delimiters[1]);
    // Return the generated string.
    return buffer.toString();
    * Generate an iTunes U digital signature for a user's credentials
    * and identity. Signatures are usually sent to iTunes U along
    * with the credentials, identity, and a time stamp to warrant
    * to iTunes U that the credential and identity values are
    * officially sanctioned. For such uses, it will usually makes
    * more sense to use an authorization token obtained from the
    * {@link #getAuthorizationToken(java.lang.String, java.lang.String, java.util.Date, byte[])}
    * method than to use a signature directly: Authorization
    * tokens include the signature but also the credentials, identity,
    * and time stamp, and have those conveniently packaged in
    * a format that is easy to send to iTunes U over HTTPS.
    * @param credentials The user's credentials string, as
    * obtained from getCredentialsString().
    * @param identity The user's identity string, as
    * obtained from getIdentityString().
    * @param time Signature time stamp.
    * @param key The bytes of your institution's iTunes U shared secret key.
    * @return A hexadecimal representation of the signature.
    public String getSignature(String credentials, String identity,
    Date time, byte[] key) {
    // Create a buffer in which to format the data to sign.
    StringBuffer buffer = new StringBuffer();
    // Generate the data to sign.
    try {
    // Start with the appropriately encoded credentials.
    buffer.append("credentials=");
    buffer.append(URLEncoder.encode(credentials, "UTF-8"));
    // Add the appropriately encoded identity information.
    buffer.append("&identity=");
    buffer.append(URLEncoder.encode(identity, "UTF-8"));
    // Add the appropriately formatted time stamp. Note that
    // the time stamp is expressed in seconds, not milliseconds.
    buffer.append("&time=");
    buffer.append(time.getTime() / 1000);
    } catch (UnsupportedEncodingException e) {
    // UTF-8 encoding support is required.
    throw new java.lang.AssertionError(
    "ITunesU.getSignature(): UTF-8 encoding not supported!");
    // Generate and return the signature.
    String signature = this.hmacSHA256(buffer.toString(), key);
    return signature;
    * Generate and sign an authorization token that you can use to securely
    * communicate to iTunes U a user's credentials and identity. The token
    * includes all the data you need to communicate to iTunes U as well as
    * a creation time stamp and a digital signature for the data and time.
    * @param credentials The user's credentials string, as
    * obtained from getCredentialsString().
    * @param identity The user's identity string, as
    * obtained from getIdentityString().
    * @param time Token time stamp. The token will only be valid from
    * its time stamp time and for a short time thereafter
    * (usually 90 seconds).
    * @param key The bytes of your institution's iTunes U shared secret key.
    * @return The authorization token. The returned token will
    * be URL-encoded and can be sent to iTunes U with
    * a form
    * submission. iTunes U will typically respond with
    * HTML that should be sent to the user's browser.
    public String getAuthorizationToken(String credentials, String identity,
    Date time, byte[] key) {
    // Create a buffer with which to generate the authorization token.
    StringBuffer buffer = new StringBuffer();
    // Generate the authorization token.
    try {
    // Start with the appropriately encoded credentials.
    buffer.append("credentials=");
    buffer.append(URLEncoder.encode(credentials, "UTF-8"));
    // Add the appropriately encoded identity information.
    buffer.append("&identity=");
    buffer.append(URLEncoder.encode(identity, "UTF-8"));
    // Add the appropriately formatted time stamp. Note that
    // the time stamp is expressed in seconds, not milliseconds.
    buffer.append("&time=");
    buffer.append(time.getTime() / 1000);
    // Generate and add the token signature.
    String data = buffer.toString();
    buffer.append("&signature=");
    buffer.append(this.hmacSHA256(data, key));
    } catch (UnsupportedEncodingException e) {
    // UTF-8 encoding support is required.
    throw new java.lang.AssertionError(
    "ITunesU.getAuthorizationToken(): "
    + "UTF-8 encoding not supported!");
    // Return the signed authorization token.
    return buffer.toString();
    * Send a request for an action to iTunes U with an authorization token.
    * @param url URL defining how to communicate with iTunes U and
    * identifying which iTunes U action to invoke and which iTunes
    * U page or item to apply the action to. Such URLs have a
    * format like <CODE>[PREFIX]/[ACTION]/[DESTINATION]</CODE>,
    * where <CODE>[PREFIX]</CODE> is a value like
    * "https://deimos.apple.com/WebObjects/Core.woa" which defines
    * how to communicate with iTunes U, <CODE>[ACTION]</CODE>
    * is a value like "Browse" which identifies which iTunes U
    * action to invoke, and <CODE>[DESTINATION]</CODE> is a value
    * like "example.edu" which identifies which iTunes U page
    * or item to apply the action to. The destination string
    * "example.edu" refers to the root page of the iTunes U site
    * identified by the domain "example.edu". Destination strings
    * for other items within that site contain the site domain
    * followed by numbers separated by periods. For example:
    * "example.edu.123.456.0789". You can find these
    * strings in the items' URLs, which you can obtain from
    * iTunes. See the iTunes U documentation for details.
    * @param token Authorization token generated by getAuthorizationToken().
    * @return The iTunes U response, which may be HTML or
    * text depending on the type of action invoked.
    public String invokeAction(String url, String token) {
    // Send a request to iTunes U and record the response.
    StringBuffer response = null;
    try {
    // Verify that the communication will be over SSL.
    if (!url.startsWith("https")) {
    throw new MalformedURLException(
    "ITunesU.invokeAction(): URL \""
    + url + "\" does not use HTTPS.");
    // Create a connection to the requested iTunes U URL.
    HttpURLConnection connection =
    (HttpURLConnection)new URL(url).openConnection();
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty(
    "Content-Type",
    "application/x-www-form-urlencoded; charset=UTF-8");
    // Send the authorization token to iTunes U.
    connection.connect();
    OutputStream output = connection.getOutputStream();
    output.write(token.getBytes("UTF-8"));
    output.flush();
    output.close();
    // Read iTunes U's response.
    response = new StringBuffer();
    InputStream input = connection.getInputStream();
    Reader reader = new InputStreamReader(input, "UTF-8");
    reader = new BufferedReader(reader);
    char[] buffer = new char[16 * 1024];
    for (int n = 0; n >= 0;) {
    n = reader.read(buffer, 0, buffer.length);
    if (n > 0) response.append(buffer, 0, n);
    // Clean up.
    input.close();
    connection.disconnect();
    } catch (UnsupportedEncodingException e) {
    // ITunes U requires UTF-8 and ASCII encoding support.
    throw new java.lang.AssertionError(
    "ITunesU.invokeAction(): UTF-8 encoding not supported!");
    } catch (IOException e) {
    // Report communication problems.
    throw new java.lang.AssertionError(
    "ITunesU.invokeAction(): I/O Exception " + e);
    // Return the response received from iTunes U.
    return response.toString();
    * iTunes U credential and identity transmission sample. When your
    * itunes U site is initially created, Apple will send your institution's
    * technical contact a welcome email with a link to an iTunes U page
    * containing the following information, which you will need to customize
    * this method's code for your site:
    <DD><DL><DT>
    * Information:<DD><CODE>
    * Site URL</CODE> - The URL to your site in iTunes U. The last
    * component of that URL, after the last slash,
    * is a domain name that uniquely identifies your
    * site within iTunes U.<DD><CODE>
    * shared secret</CODE> - A secret key known only to you and Apple that
    * allows you to control who has access to your
    * site and what access they have to it.<DD><CODE>
    * debug suffix</CODE> - A suffix you can append to your site URL
    * to obtain debugging information about the
    * transmission of credentials and identity
    * information from your institution's
    * authentication and authorization services
    * to iTunes U.<DD><CODE>
    * administrator credential</CODE> - The credential string to assign
    * to users who should have the
    * permission to administer your
    * iTunes U site.</DL></DD>
    <DD>
    * Once you have substitute the information above in this method's code
    * as indicated in the code's comments, this method will connect
    * to iTunes U and obtain from it the HTML that needs to be returned to a
    * user's web browser to have a particular page or item in your iTunes U
    * site displayed to that user in iTunes. You can modify this method to
    * instead output the URL that would need to be opened to have that page
    * or item displayed in iTunes.</DD>
    public static void main(String argv[]) {
    // Define your site's information. Replace these
    // values with ones appropriate for your site.
    String siteURL =
    "https://deimos.apple.com/WebObjects/Core.woa/Browse/xxx.edu" ;
    String debugSuffix = "/abc123";
    String sharedSecret = "some key";
    String administratorCredential =
    "Administrator@urn:mace:itunesu.com:sites:xxx.edu";
    // Define the user information. Replace the credentials with the
    // credentials you want to grant to the current user, and the
    // optional identity information with the identity of that user.
    // For initial testing and site setup, use the singe administrator
    // credential defined when your iTunes U site was created. Once
    // you have access to your iTunes U site, you will be able to define
    // additional credentials and the iTunes U access they provide.
    String[] credentialsArray = { administratorCredential };
    String displayName = "my name";
    String emailAddress = "my [email protected]";
    String username = "mylogin";
    String userIdentifier = "1243";
    // Define the iTunes U page to browse. Use the domain name that
    // uniquely identifies your site in iTunes U to browse to that site's
    // root page; use a destination string extracted from an iTunes U URL
    // to browse to another iTunes U page; or use a destination string
    // supplied as the "destination" parameter if this program is being
    // invoked as a part of the login web service for your iTunes U site.
    String siteDomain = siteURL.substring(siteURL.lastIndexOf('/') + 1);
    String destination = siteDomain;
    // Append your site's debug suffix to the destination if you want
    // to receive an HTML page providing information about the
    // transmission of credentials and identity between this program
    // and iTunes U. Uncomment the following line for testing only.
    //destination = destination + debugSuffix;
    // Use an ITunesU instance to format the credentials and identity
    // strings and to generate an authorization token for them.
    ITunesU iTunesU = new ITunesU();
    String identity = iTunesU.getIdentityString(displayName, emailAddress,
    username, userIdentifier);
    String credentials = iTunesU.getCredentialsString(credentialsArray);
    Date now = new Date();
    byte[] key = null;
    try {
    key = sharedSecret.getBytes("US-ASCII");
    } catch (UnsupportedEncodingException e) {
    throw new java.lang.AssertionError(
    "ITunesU.hmacSH256(): US-ASCII encoding not supported!");
    String token = iTunesU.getAuthorizationToken(credentials, identity,
    now, key);
    // Use the authorization token to connect to iTunes U and obtain
    // from it the HTML that needs to be returned to a user's web
    // browser to have a particular page or item in your iTunes U
    // site displayed to that user in iTunes. Replace "/Browse/" in
    // the code below with "/API/GetBrowseURL/" if you instead want
    // to return the URL that would need to be opened to have that
    // page or item displayed in iTunes.
    String prefix = siteURL.substring(0, siteURL.indexOf(".woa/") + 4);
    String url = prefix + "/Browse/" + destination;
    String results = iTunesU.invokeAction(url, token);
    System.out.println(results);
    The itunes file from Shell folder has been modified as follows
    DISPLAY_NAME= "myname"
    EMAIL_ADDRESS="[email protected]"
    USERNAME="mylogin"
    USER_IDENTIFIER="1243"
    all the other things in that file have been untouched.
    I also generated the debug which looks like this
    iTunes U Access Debugging
    Received
    Destination xxx.edu
    Identity "my name" <[email protected]> (mylogin) [1243]
    Credentials Administrator@urn:mace:itunesu.com:sites:xxx.edu
    Time 1196706873
    Signature 533870b8jshdidk333lfsf6a3143a55c132ec548a4d545bd79322402e8e2596e4
    Analysis
    The destination string is valid and the corresponding destination item was found.
    The identity string is valid and provides the following information:
    Display Name my name
    Email Address [email protected]
    Username mylogin
    User Identifier 1243
    The credential string is valid and contains the following recognized credential:
    1. Administrator@urn:mace:itunesu.com:sites:xxx.edu
    The time string is valid and corresponds to 2007-12-03 18:34:33Z.
    The signature string is valid.
    Access
    Because the received signature and time were valid, the received identity and credentials were accepted by iTunes U.
    In addition, the following 2 credentials were automatically added by iTunes U:
    1. All@urn:mace:itunesu.com:sites:xxx.edu
    2. Authenticated@urn:mace:itunesu.com:sites:xxx.edu
    With these credentials, you have browsing, downloading, uploading, and editing access to the requested destination.
    I am pretty new to this, and working on this for the first time.If someone could guide me through this would be pretty helpful.

    This is only going to work under IE !
    Go to your page template :
    Modify the definition, make sur you have this :
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>#TITLE#</title>
    #HEAD#
    <Script language = javascript>
    Browser = navigator.appName
    Net = Browser.indexOf("Netscape")
    Micro = Browser.indexOf("Microsoft")
    Netscape = false
    IE = false
    if(Net >= 0) {Netscape = true}
    if(Micro >= 0) {IE = true}
    function XYpos() {
    if (IE == true) {
    xPos = event.screenX
    yPos = event.screenY
    alert(xPos + " left " + yPos + " down")
    else if (Netscape == true) {alert("Script won't work: " + "\n" + "You're using Netscape")}
    </script>
    Modify the body definition, make sure you have this :
    <body #ONLOAD# onMouseDown = XYpos()>
    I didnt try it but it make sens to me... tell me if it works!
    Flex
    Homepage : http://www.insum.ca
    InSum Solutions' blog : http://insum-apex.blogspot.com

  • Help with Java to XML

    All I need to know is how to bold the tag <CompanyID> </CompanyID> OR the text within it (1001, in given sample).
    Here's a sample line of the data.txt file I'm working with:
    1001,"Fitzsimmons, Des Marteau, Beale and Nunn",109,"COD","Standard",,109,8/14/1998 8:50:02
    Thanks in advance!
    public class PracticeExerciseOne {
        public static void main(String [] args){
            DocumentBuilderFactory domFac = null;
            DocumentBuilder domBuild = null;
            //Element tags
            final String COMPANY = "Companies";
            final String COMPANY_ID = "CompanyID";
            //rest too long to post
            //Regex to be used for each field in the CSV file
            ArrayList<Pattern> patterns = new ArrayList<Pattern>();
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("[^,]*,"));
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("[^,]+ [^,]+"));
            //Store element tags in an array - too long to post
            try{
                //Build a new documet
                domFac = DocumentBuilderFactory.newInstance();
                domBuild = domFac.newDocumentBuilder();
                Document doc = domBuild.newDocument();
                //Create a new root element
                Element rootElement = doc.createElement(COMPANY);
                doc.appendChild(rootElement);
                //Read in the file
                BufferedReader in = new BufferedReader(new FileReader(new File("texts/data.txt")));
                BufferedWriter out = new BufferedWriter(new FileWriter(new File("texts/dataOut.xml")));
                int tempI;
                String line = in.readLine();
                //We will cut this string down after every element we take out of it
                String temp = line;
                String tempElement = "";
                while(line != null){
                    for(int i = 0; i < patterns.size(); i++){
                        //Matches a pattern to a field, starting with the first pattern
                        //Matchup should be 1st pattern = 1st field
                        Matcher matcher = patterns.get(i).matcher(temp);
                        if(matcher.find()){
                            //if we haven't reached the last field
                            if(i != 7){
                                //we want to get the index of the last comma within the matched group
                                tempI = matcher.group().lastIndexOf(',');
                                //create an element using the beginning of the given string and the last comma within that data
                                tempElement = temp.substring(0,tempI);
                            else{
                                //no comma in last field, so we just want to get the whole field
                                tempI = 0;
                                tempElement = temp.substring(0);
                            //if an empty element appears, add a space for tags to be placed correctly
                            if(tempElement.equals("")){
                                tempElement = " ";
                            //temp will be set to the remaining string, once we have taken the nth field out
                            temp = temp.substring(tempI+1);
                            //create an element with tags and append to document
                            Element em = doc.createElement(tags);
    em.appendChild(doc.createTextNode(tempElement));
    rootElement.appendChild(em);
    line = in.readLine();
    temp = line;
    //Transformer will create a new XML document using the Document we have built
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(out);
    transformer.transform(source, result);
    out.close();
    in.close();
    catch(Exception e){
    System.err.println("Exception: " + e.getMessage());
    e.printStackTrace();

    maybe this can help You for now and future,
    in this site You can download a sample codes publish in this books - java fundamentals and advanced features.,
    in 2nd book, is a big chapter about java and xml. Please read this code, i will hope, this can help You.
    http://www.horstmann.com/corejava.html (for mod: this is not SPAM)

Maybe you are looking for

  • SAP CRM Interfacing Techiniques

    Hi All, I am working on CRM 7.0, I would like to know all the possible Interfacing techniques currently available for 1. SAP CRM 7.0 and SAP systems like ECC, BW, etc 2. SAP CRM 7.0 and Non SAP systems. OR, What would be best suited/solution/proposal

  • Error opening excel files in browser

                Okai I am currently facing an error when i try to open excel files in browser .  it gives the prompt "The workbook can not be opened". Upon checking the logs I found the following entries in the log file . recently we tried to move our si

  • Battery status in the menubar...

    Hi, I have a second problem in my new OS. I cannot choose a battery setting from the menubar. It only shows the following: Battery status Power source "Show" –> Energy save preferences. Right now the only way for me to change settings is to open up s

  • Itunes says can not connect.  Store may be busy.. What does that mean?

    iTunes will not connect.  It is version 7. It will not let me update to latest version.  Operating system is OS X 10.4.11.  What do I do?

  • Software update 1.2 Issues

    Hi, wondering if anyone else is haviing this problem (as it is a PAIN) recently updated to iTunes 7 and iPod software version 1.2 and everytime I now connect either of my iPods (Video or Mini) it keeps giving me an error message that "the iPod xxx ca