GetOutputStream()  -- Connection refused: connect

Hi, i'm doing this (inside a function)
URL receiver = new URL(url);
HttpURLConnection receiverConnection  = (HttpURLConnection)(receiver.openConnection());
            receiverConnection.setDoInput(true);
            receiverConnection.setDoOutput(true);
            receiverConnection.setRequestProperty( "Authorization", "Basic " + encodedPassword);
            receiverConnection.setRequestProperty( "Content-type", "application/x-sap.rfc");
            System.setProperty("javax.xml.transform.TransformerFactory", "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            Reader rd = new StringReader(strXml);
            StreamSource streamSource = new StreamSource(rd);
            PrintWriter pw = new PrintWriter(receiverConnection.getOutputStream(), false);
            StreamResult streamResult = new StreamResult(pw);
            transformer.transform(streamSource, streamResult);
            pw.flush();
            pw.close();and when i do the receiverConnection.getOutputStream() it throws
"Connection refused: connect"... i'm using JDK 1.5 with tomcat 5.0...
thanks in advanced!!!

Comment out your call to setDoInput(true). See if that helps. If not, then it is probably a configuration issue on the server you are attempting to send to.
- Saish

Similar Messages

  • Telnet: Sending an output to the connected host.

    Hi all, I have written a GUI to connect to a host using a socket. This is going to be a MUD client (for all who know what a MUD is) and I can't seem to send anything to the host. Any suggestions? Also, the code returned by the host is in some computer language at some areas. Like when there is supposed to be colour it shows a squarebox then [32mL.
    This is the complete working code.
    Thanks.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.IOException;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    public class UMC extends JFrame implements Runnable {
         boolean connected = false;     
         BufferedReader br;
         BufferedWriter bw;
         Container c;
         Socket socket;
         JScrollPane jsp;
         JTextArea ta;
         JTextField tf;
         Thread thread;
         UMC() {
              super("Uknight Mud Client v0.1 - Unknown Knight 2004");
              c = getContentPane();
              c.setLayout(new BorderLayout());
              ta = new JTextArea();
              tf = new JTextField();
              thread = new Thread(this);
              jsp = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              ta.setEditable(false);
              ta.setBackground(Color.black);
              ta.setForeground(Color.white);
              tf.addActionListener(new TextInputHandler());
              c.add(jsp, BorderLayout.CENTER);
              c.add(tf, BorderLayout.SOUTH);
              setSize(800,600);
              show();
              tf.requestFocus();
              connect("tharsis.dyndns.org", 8765);
         public static void main(String args[]) {
              JFrame.setDefaultLookAndFeelDecorated(true);
              new UMC();
         public void connect(String host, int port) {
              try {
                   output("Attempting to connect to " + host + ": " + port);
                   socket = new Socket(host, port);
                   br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                   connected = true;
                   thread.start();
              } catch (IOException e) {
                   JOptionPane.showMessageDialog(null, "Cannot connect to " + host + ": " + port, "Cannot connect", JOptionPane.ERROR_MESSAGE);
         public void run() {
              while(connected) {
                   try {
                        if(br.ready())
                        output(br.readLine());
                   } catch (IOException e) {}
                   try {
                        thread.sleep(5);
                   } catch (InterruptedException e) {}
         public void output(String text) {
              ta.append(text + "\n");
              jsp.getVerticalScrollBar().setValue(jsp.getVerticalScrollBar().getMaximum());
         class TextInputHandler implements ActionListener {
              public void actionPerformed(ActionEvent e) {
                   if(connected)
                   write();
                   else
                   output("You are not connected yet!");
                   tf.setText("");
         public void write() {
              try {
                   bw.write(tf.getText(),0,tf.getText().length());
                   bw.flush();
              } catch(IOException e) {}          
    }

    Erm I got it to work using PrintWriter already thanks..... Though I need help about how to import the colours and such, and I do get some weird characters like Ys with some dots above them. Any suggestions?

  • Problem establishing a https connection

    Hi,
    I have the following problem in establishing a connection to a secured webserver.
    I tried to establish a connection to a secured web server from a application running in weblogic. I used the weblogic specific APIs, created a weblogic.net.http.HttpsURLConnection. I set the connection properties like setSocketFactory and used NulledTrustManager and NulledHostNameVerifier.
    I then tried to get a DataOutputStream so tht i can write my xml string to tht connection, nothing really is happening. When i tried to print the headervariables it is not printing any..... I am doubtful if the connection is established....
    i will attach my code....plz tell me if i am missing something out....
    The same code works when i use Java APIs....they are included in the code as comments....
    Actually i have a jsp file in the secure server which takes this string and sends mail to the required recipients.....
    Plz help.....Thanks in Advance for all the helping minds...
    In the code, the trustallcerts and hostnameverifier are classes written similar to nulledtrustmanager and nulledhostnameverifier.... ie it certifies everything and trusts everything.
    /* Code Snippet */
    import java.io.*;
    import java.util.Properties;
    import java.net.*;
    import weblogic.security.SSL.*;
    import weblogic.net.http.HttpsURLConnection;
    public class EmailClientW
         String XMLMessage;
         byte[] XMLMessageBytes;
         String strURL= "some https url";
         public EmailClientW(){}
         public EmailClientW( String str )
              XMLMessage = str;
              XMLMessageBytes = XMLMessage.getBytes();
         public void HttpsConnect()
              try{
                   // Create the socket connection and open it to the secure remote web server
                   // Used in case of Java API
                   //System.setProperty("javax.net.ssl.trustStore", "C://bea/jdk141_03//jre//lib//security//cacerts");
                   weblogic.security.SSL.SSLContext sc = weblogic.security.SSL.SSLContext.getInstance("SSL");
                   //Used in case of Java API
                   //sc.init(null, trustAllCerts, new java.security.SecureRandom());
                   TrustManagerJSSE tManager = new TrustAllcerts();
                   sc.setTrustManagerJSSE(tManager);
                   //sc.loadLocalIdentity(certs, privateKey);
                   sc.setHostnameVerifierJSSE(new HostNameVerifier());
                   //Used in case of Java API
                   //javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                   URL url = new URL(strURL);
                   weblogic.net.http.HttpsURLConnection connection = new weblogic.net.http.HttpsURLConnection(url);
                   connection.setSSLSocketFactory(sc.getSocketFactoryJSSE());
                   connection.setHostnameVerifierJSSE(new HostNameVerifier());
                   System.out.println("CLASS " + connection.getClass().getName());
                   connection.setDoOutput(true);
                   connection.setDoInput(true);
                   connection.setRequestProperty("Connection", "Keep-Alive");
                   connection.setRequestMethod("POST");
                   connection.setRequestProperty("Content-Type","text/html");
                   connection.setInstanceFollowRedirects(false);
                   connection.setAllowUserInteraction(false);
                   connection.setHostnameVerifierJSSE(new HostNameVerifier());
                   //This doesnt print anything.
                   System.out.println("getOutputStream :"+connection.getHeaderFields());
                   DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
                   dos.write(XMLMessageBytes, 0, XMLMessageBytes.length);
                   dos.flush();
                   dos.close();
              }catch (java.net.MalformedURLException mue){
                   System.err.println("\n" + "URL is not exist or protocol does not exist or there is a typo in the submitted URL" + "\n");
              }catch (java.net.UnknownHostException uhe){
                   System.err.println("\n" + "Remote server does not exist in DNS." + "\n");
              }catch (java.io.IOException ioe){
                   System.err.println("\n" + "I/O Exception in the connection try again or contact developer." + "\n");
                   ioe.printStackTrace();
              }catch (Exception exp){
                   System.err.println("\n" + "Exception in the connection try again or contact developer." + "\n");
                   exp.printStackTrace();
         public static void main(String args[]) throws Exception
              new EmailClientW().HttpsConnect();
    }

    Thx for the prompt reply....But this is not solving my problem.
    I am trying to establish the connection from inside a weblogic container. So i am forced to use weblogic APIs.
    Also i use NulledTrustManager and NulledHostNameVerifier so i think i neednot worry about the certificates...
    Weblogic APIs donot contain init method for sslcontext....So if u can see the code, i have commented these lines and set these properties using the Weblogic supported APIs.
    Also the method which u specified (Using Java APIs) was working for me....problem arose when i tried to use weblogic specific APIs.
    Can u go through the code once and tell me if i am missing something over there? Coz header is not getting populated, the request is not hitting the secure server
    One more thing, if i use the HostNameVerifier(dummy one to verify all the hosts), it tells me tht the key chain obtained from the host is incomplete.... and throws javax.net.ssl.SSLKeyException...
    If i remover hostnameverifier, the exception is not thrown, but the request is not hitting the server...
    Plz help me ... i am helplessly stuck in this situation...
    Thx in advance for all the helping minds.....

  • Uploading an image is not working in jsff

    Hi.,
    Am using jdeveloper 11.1.1.6.,
    I have used the following link to upload the image in jsff
    http://www.baigzeeshan.com/2010/08/uplaoding-and-downloading-images-in.html
    This is workig perfectly in a jsps page but when i used jsff page am getting exception
        private BlobDomain createBlobDomain (UploadedFile file) throws IOException,
                                                                      SQLException {
            InputStream in = null;
            BlobDomain blobDomain = null;
            OutputStream out = null;
            try{
                in= file.getInputStream();    // am getting null pointer exception
                blobDomain = new BlobDomain();
                out = blobDomain.getBinaryOutputStream();
                byte[] buffer = new byte[8192];
                int bytesRead = 0;
                while ((bytesRead = in.read(buffer,0,8192))!= -1){
                    out.write(buffer,0,bytesRead);
            catch (Exception e){
                e.printStackTrace();
            return blobDomain;
        }Pls help me to resolve this.,

    Thank's for your response John.,
    This is the log which am getting
    java.lang.NullPointerException
         at view.imageServlet.doGet(imageServlet.java:53)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
         at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
         at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
         at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
         at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:119)
         at java.security.AccessController.doPrivileged(Native Method)
         at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:315)
         at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:442)
         at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:103)
         at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:171)
         at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:139)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
         at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
         at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
         at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
         at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
         at weblogic.work.ExecuteThread.run(ExecuteThread.java:178)This s the doget() method which i have used
        public void doGet(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException,
                                                               IOException {
            response.setContentType(CONTENT_TYPE);
            String eno = request.getParameter("id");
            OutputStream os = response.getOutputStream();
            Connection con = null;
            try{
                Context ctx = new InitialContext();
                DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/UIConnDS");
                con = ds.getConnection();
                PreparedStatement stmt =  con.prepareStatement("SELECT eei_emp_id,eei_emp_image " +
                                          "FROM ess_emp_image " +
                                          "WHERE eei_emp_id = ?");
                stmt.setString(1, eno);
                ResultSet rs = stmt.executeQuery();
                if (rs.next()) {
                    Blob blob = rs.getBlob("eei_emp_image");
                    BufferedInputStream in =  new BufferedInputStream(blob.getBinaryStream());    //This is the part where exception is showing now.
                    int b;
                    byte[] buffer = new byte[10240];
                    while ((b = in.read(buffer, 0, 10240)) != -1) {
                        os.write(buffer, 0, b);
                    os.close();
                    catch (Exception e){
                        e.printStackTrace();
            finally {
                        try {
                            if (con != null) {
                                con.close();
                        } catch (SQLException sqle) {
                            System.out.println("SQLException error");
            }

  • How can i pass more than 1 param to servlet to show blob image

    Hi
    my servlet expects 2 param to SELECt an image from a blob column
    public class ImageBlobServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    IOException {
    response.setContentType(CONTENT_TYPE);
    String ImageId = request.getParameter("id");
    String TipImg = request.getParameter("tip");
    OutputStream os = response.getOutputStream();
    Connection conn = null;
    try {
    Context ctx;
    ctx = new InitialContext();
    DataSource ds = (DataSource)ctx.lookup("java:/comp/env/jdbc/rhDS");
    conn = ds.getConnection();
    PreparedStatement statement = conn.prepareStatement("select FIT from " +
    "RHH_FOTOS IMG " +
    "where IMG.IDASSO = ? and IMG.TIM_COA = ?");
    statement.setInt(1, new Integer(ImageId));
    statement.setString(2, TipImg);
    To display the image i tried to use:
    <af:image id="ot1"
    *source="/imageblobservlet?id=#{bindings.Con.inputValue}?tip=#{"EMP"}"*
    shortDesc="Foto"/>
    but i receive all content in the get of first param.
    String ImageId = request.getParameter("id");
    How can i pass one more then 1 param in EL.
    Thanks in advance

    Hello,
    seems to me you're using wrong separator for the second param into your URL:
    <af:image id="ot1" source="/imageblobservlet?id=#{bindings.Con.inputValue}
    tip=#{"EMP"}" shortDesc="Foto"/>
    I think it should be:
    <af:image id="ot1" source="/imageblobservlet?id=#{bindings.Con.inputValue}
    tip=#{"EMP"}" shortDesc="Foto"/>
    Jack

  • Problem using a jar file : java.lang.ClassNotFoundException: ApiConn

    Hi everyone.
    i am running a form that use a bean_area to call a jar.
    but i am getting this error, thanks in advnce for any tip.
    Java Plug-in 1.6.0_33
    Using JRE version 1.6.0_33-b05 Java HotSpot(TM) Client VM
    User home directory = C:\Users\user1
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    java.lang.ClassNotFoundException: ApiConn
         at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
         at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
         at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
         at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Unknown Source)
         at oracle.forms.handler.UICommon.instantiate(Unknown Source)
         at oracle.forms.handler.UICommon.onCreate(Unknown Source)
         at oracle.forms.handler.JavaContainer.onCreate(Unknown Source)
         at oracle.forms.engine.Runform.onCreateHandler(Unknown Source)
         at oracle.forms.engine.Runform.processMessage(Unknown Source)
         at oracle.forms.engine.Runform.processSet(Unknown Source)
         at oracle.forms.engine.Runform.onMessageReal(Unknown Source)
         at oracle.forms.engine.Runform.onMessage(Unknown Source)
         at oracle.forms.engine.Runform.processEventEnd(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.redispatchEvent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
         at java.awt.EventQueue.access$000(Unknown Source)
         at java.awt.EventQueue$1.run(Unknown Source)
         at java.awt.EventQueue$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
         at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
         at java.awt.EventQueue$2.run(Unknown Source)
         at java.awt.EventQueue$2.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Dumping class loader cache...
    Live entry: key=http://192.168.10.100:7778/forms/java/,frmall.jar,siberia_jpg.jar,ApiConn.jar,Hasher.jar,ReadCommand.jar,WriteCommand.jar,libAPI.jar, refCount=1, threadGroup=sun.plugin2.applet.Applet2ThreadGroup[name=http://192.168.10.100:7778/forms/java/-threadGroup,maxpri=4]
    Done.
    in my form i have created a bean_area and used as implementation class :ApiConn
    in my formsweb.cfg i used this configuration: archive=frmall.jar,siberia_jpg.jar,ApiConn.jar,Hasher.jar,ReadCommand.jar,WriteCommand.jar,libAPI.jar
    in my forms/java i have placed my jar files listed in the frmall.jar
    i guess i am missing something but i dont know what it is.
    here is my ApiConn.java from wich i generate my jar file:
    package libAPI;
    * This contains connection. Everything should be here,
    * should operate with this class only
    import java.io.*;
    import java.net.*;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    * @author janisk
    public class ApiConn extends Thread {
    private Socket sock = null;
    private DataOutputStream out = null;
    private DataInputStream in = null;
    private String ipAddress;
    private int ipPort;
    private boolean connected = false;
    private String message = "Not connected";
    private ReadCommand readCommand = null;
    private WriteCommand writeCommand = null;
    private Thread listener = null;
    LinkedBlockingQueue queue = new LinkedBlockingQueue(40);
    * Constructor of the connection class
    * @param ipAddress - IP address of the router you want to conenct to
    * @param ipPort - port used for connection, ROS default is 8728
    public ApiConn(String ipAddress, int ipPort) {
    this.ipAddress = ipAddress;
    this.ipPort = ipPort;
    this.setName("settings");
    * State of connection
    * @return - if connection is established to router it returns true.
    public boolean isConnected() {
    return connected;
    public void disconnect() throws IOException{
    listener.interrupt();
    sock.close();
    private void listen() {
    if (this.isConnected()) {
    if (readCommand == null) {
    readCommand = new ReadCommand(in, queue);
    listener = new Thread(readCommand);
    listener.setDaemon(true);
    listener.setName("listener");
    listener.start();
    * to get IP address of the connection. Reads data from socket created.
    * @return InetAddress
    public InetAddress getIpAddress() {
    return sock == null ? null : sock.getInetAddress();
    * returns ip address that socket is asociated with.
    * @return InetAddress
    public InetAddress getLocalIpAddress() {
    return sock == null ? null : sock.getLocalAddress();
    * Socket remote port number
    * @return
    public int getPort() {
    return sock == null ? null : sock.getPort();
    * return local prot used by socket
    * @return
    public int getLocalPort() {
    return sock == null ? null : sock.getLocalPort();
    * Returns status message set up bu class.
    * @return
    public String getMessage() {
    return message;
    * sets and exectues command (sends it to RouterOS host connected)
    * @param s - command will be sent to RouterOS for example "/ip/address/print\n=follow="
    * @return
    public String sendCommand(String s) {
    return writeCommand.setCommand(s).runCommand();
    * exeecutes already set command.
    * @return returns status of the command sent
    public String runCommand() {
    return writeCommand.runCommand();
    * Tries to fech data that is repllied to commands sent. It will wait till it can return something.
    * @return returns data sent by RouterOS
    * @throws java.lang.InterruptedException
    public String getData() throws InterruptedException {
    String s = (String) queue.take();
    return s;
    * returns command that is set at this moment. And will be exectued if runCommand is exectued.
    * @return
    public String getCommand() {
    return writeCommand.getCommand();
    * set up method that will log you in
    * @param name - username of the user on the router
    * @param password - password for the user
    * @return
    public String login(String name, char[] password) {
    this.sendCommand("/login");
    String s = "a";
    try {
    s = this.getData();
    } catch (InterruptedException ex) {
    Logger.getLogger(ApiConn.class.getName()).log(Level.SEVERE, null, ex);
    return "failed read #1";
    if (!s.contains("!trap") && s.length() > 4) {
    String[] tmp = s.trim().split("\n");
    if (tmp.length > 1) {
    tmp = tmp[1].split("=ret=");
    s = "";
    String transition = tmp[tmp.length - 1];
    String chal = "";
    chal = Hasher.hexStrToStr("00") + new String(password) + Hasher.hexStrToStr(transition);
    chal = Hasher.hashMD5(chal);
    String m = "/login\n=name=" + name + "\n=response=00" + chal;
    s = this.sendCommand(m);
    try {
    s = this.getData();
    } catch (InterruptedException ex) {
    Logger.getLogger(ApiConn.class.getName()).log(Level.SEVERE, null, ex);
    return "failed read #2";
    if (s.contains("!done")) {
    if (!s.contains("!trap")) {
    return "Login successful";
    return "Login failed";
    @Override
    public void run() {
    try {
    InetAddress ia = InetAddress.getByName(ipAddress);
    if (ia.isReachable(1000)) {
    sock = new Socket(ipAddress, ipPort);
    in = new DataInputStream(sock.getInputStream());
    out = new DataOutputStream(sock.getOutputStream());
    connected = true;
    readCommand = new ReadCommand(in, queue);
    writeCommand = new WriteCommand(out);
    this.listen();
    message = "Connected";
    } else {
    message = "Not reachable";
    } catch (UnknownHostException ex) {
    connected = false;
    message = ex.getMessage();
    ex.printStackTrace();
    } catch (IOException ex) {
    connected = false;
    message = ex.getMessage();
    ex.printStackTrace();
    }

    I need your help again, i think this is a minor thing.
    i have compiled the class file that i needed and i signed it too. but now it is giving me a new error and need your tip.
    here is the java console loyout and my java file ((i think here is the problem in java file, something must be missing)).
    thanks in advance for any help.
    Java Plug-in 10.17.2.02
    Using JRE version 1.7.0_17-b02 Java HotSpot(TM) Client VM
    User home directory = C:\Users\Administrator
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    network: Connecting http://192.168.10.100:7778/forms/lservlet;jsessionid=c0a80a6430d6e191eded93774f2f8d1bed73056e66ef.e3mObhiMbxeKe34PahiKbx4Nbh90n6jAmljGr5XDqQLvpAe with proxy=DIRECT
    security: Validate the certificate chain using CertPath API
    security: The certificate hasnt been expired, no need to check timestamping info
    security: Cannot find jurisdiction list file
    security: The CRL support is disabled
    security: The OCSP support is disabled
    security: This OCSP End Entity validation is disabled
    security: Checking if certificate is in Deployment denied certificate store
    security: Checking if certificate is in Deployment permanent certificate store
    basic: updateValidationResultsForApplet update
    cache: Mark prevalidated: http://192.168.10.100:7778/forms/java/ApiConn.jar true tm=1363335797289 cert=1371107987000
    basic: Plugin2ClassLoader.getPermissions CeilingPolicy allPerms
    java.lang.InstantiationException: oracle.forms.siberia.ApiConn
         at java.lang.Class.newInstance0(Unknown Source)
         at java.lang.Class.newInstance(Unknown Source)
         at oracle.forms.handler.UICommon.instantiate(Unknown Source)
         at oracle.forms.handler.UICommon.onCreate(Unknown Source)
         at oracle.forms.handler.JavaContainer.onCreate(Unknown Source)
         at oracle.forms.engine.Runform.onCreateHandler(Unknown Source)
         at oracle.forms.engine.Runform.processMessage(Unknown Source)
         at oracle.forms.engine.Runform.processSet(Unknown Source)
         at oracle.forms.engine.Runform.onMessageReal(Unknown Source)
         at oracle.forms.engine.Runform.onMessage(Unknown Source)
         at oracle.forms.engine.Runform.processEventEnd(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.redispatchEvent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
         at java.awt.EventQueue.access$200(Unknown Source)
         at java.awt.EventQueue$3.run(Unknown Source)
         at java.awt.EventQueue$3.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
         at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
         at java.awt.EventQueue$4.run(Unknown Source)
         at java.awt.EventQueue$4.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    network: Connecting http://192.168.10.100:7778/forms/lservlet;jsessionid=c0a80a6430d6e191eded93774f2f8d1bed73056e66ef.e3mObhiMbxeKe34PahiKbx4Nbh90n6jAmljGr5XDqQLvpAe with proxy=DIRECT
    Exception in thread "Forms-DialogThread2" java.lang.NullPointerException
         at oracle.forms.handler.JavaContainer.onDestroy(Unknown Source)
         at oracle.forms.engine.Runform.destroyHandlers(Unknown Source)
         at oracle.forms.handler.DialogThread.doAlert(Unknown Source)
         at oracle.forms.handler.DialogThread.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Dumping class loader cache...
    Live entry: key=http://192.168.10.100:7778/forms/java/,frmall.jar,siberia_jpg.jar,ApiConn.jar,ConcealTextField.jar, refCount=1, threadGroup=sun.plugin2.applet.Applet2ThreadGroup[name=http://192.168.10.100:7778/forms/java/-threadGroup,maxpri=4]
    Done.
    here is my java file
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package oracle.forms.siberia;
    * This contains connection. Everything should be here,
    * should operate with this class only
    import java.io.*;
    import java.net.*;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import oracle.forms.*;
    * @author janisk
    public class ApiConn extends Thread {
    private Socket sock = null;
    private DataOutputStream out = null;
    private DataInputStream in = null;
    private String ipAddress;
    private int ipPort;
    private boolean connected = false;
    private String message = "Not connected";
    private ReadCommand readCommand = null;
    private WriteCommand writeCommand = null;
    private Thread listener = null;
    LinkedBlockingQueue queue = new LinkedBlockingQueue(40);
    * Constructor of the connection class
    * @param ipAddress - IP address of the router you want to conenct to
    * @param ipPort - port used for connection, ROS default is 8728
    public ApiConn(String ipAddress, int ipPort) {
    this.ipAddress = ipAddress;
    this.ipPort = ipPort;
    this.setName("settings");
    * State of connection
    * @return - if connection is established to router it returns true.
    public boolean isConnected() {
    return connected;
    public void disconnect() throws IOException{
    listener.interrupt();
    sock.close();
    private void listen() {
    if (this.isConnected()) {
    if (readCommand == null) {
    readCommand = new ReadCommand(in, queue);
    listener = new Thread(readCommand);
    listener.setDaemon(true);
    listener.setName("listener");
    listener.start();
    * to get IP address of the connection. Reads data from socket created.
    * @return InetAddress
    public InetAddress getIpAddress() {
    return sock == null ? null : sock.getInetAddress();
    * returns ip address that socket is asociated with.
    * @return InetAddress
    public InetAddress getLocalIpAddress() {
    return sock == null ? null : sock.getLocalAddress();
    * Socket remote port number
    * @return
    public int getPort() {
    return sock == null ? null : sock.getPort();
    * return local prot used by socket
    * @return
    public int getLocalPort() {
    return sock == null ? null : sock.getLocalPort();
    * Returns status message set up bu class.
    * @return
    public String getMessage() {
    return message;
    * sets and exectues command (sends it to RouterOS host connected)
    * @param s - command will be sent to RouterOS for example "/ip/address/print\n=follow="
    * @return
    public String sendCommand(String s) {
    return writeCommand.setCommand(s).runCommand();
    * exeecutes already set command.
    * @return returns status of the command sent
    public String runCommand() {
    return writeCommand.runCommand();
    * Tries to fech data that is repllied to commands sent. It will wait till it can return something.
    * @return returns data sent by RouterOS
    * @throws java.lang.InterruptedException
    public String getData() throws InterruptedException {
    String s = (String) queue.take();
    return s;
    * returns command that is set at this moment. And will be exectued if runCommand is exectued.
    * @return
    public String getCommand() {
    return writeCommand.getCommand();
    * set up method that will log you in
    * @param name - username of the user on the router
    * @param password - password for the user
    * @return
    public String login(String name, char[] password) {
    this.sendCommand("/login");
    String s = "a";
    try {
    s = this.getData();
    } catch (InterruptedException ex) {
    Logger.getLogger(ApiConn.class.getName()).log(Level.SEVERE, null, ex);
    return "failed read #1";
    if (!s.contains("!trap") && s.length() > 4) {
    String[] tmp = s.trim().split("\n");
    if (tmp.length > 1) {
    tmp = tmp[1].split("=ret=");
    s = "";
    String transition = tmp[tmp.length - 1];
    String chal = "";
    chal = Hasher.hexStrToStr("00") + new String(password) + Hasher.hexStrToStr(transition);
    chal = Hasher.hashMD5(chal);
    String m = "/login\n=name=" + name + "\n=response=00" + chal;
    s = this.sendCommand(m);
    try {
    s = this.getData();
    } catch (InterruptedException ex) {
    Logger.getLogger(ApiConn.class.getName()).log(Level.SEVERE, null, ex);
    return "failed read #2";
    if (s.contains("!done")) {
    if (!s.contains("!trap")) {
    return "Login successful";
    return "Login failed";
    @Override
    public void run() {
    try {
    InetAddress ia = InetAddress.getByName(ipAddress);
    if (ia.isReachable(1000)) {
    sock = new Socket(ipAddress, ipPort);
    in = new DataInputStream(sock.getInputStream());
    out = new DataOutputStream(sock.getOutputStream());
    connected = true;
    readCommand = new ReadCommand(in, queue);
    writeCommand = new WriteCommand(out);
    this.listen();
    message = "Connected";
    } else {
    message = "Not reachable";
    } catch (UnknownHostException ex) {
    connected = false;
    message = ex.getMessage();
    ex.printStackTrace();
    } catch (IOException ex) {
    connected = false;
    message = ex.getMessage();
    ex.printStackTrace();
    }

  • View in image from database

    hi will i be able to view image from my database using this class, am using jdeveloper 11g release 2
    package TaskFlowView;
    import java.io.BufferedInputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.sql.DataSource;
    public class ImageServlet extends HttpServlet {
        private static final String CONTENT_TYPE =
            "image/jpg; charset=utf-8";
         * @param config
         * @throws ServletException
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
         * @param request
         * @param response
         * @throws ServletException
         * @throws IOException
        public void doGet(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException,
                                                               IOException {
            response.setContentType(CONTENT_TYPE);
            response.setContentType(CONTENT_TYPE);
            String detailDocumentId = request.getParameter("detail");
            String thumbnailDocumentId = request.getParameter("thumbnail");
            boolean thumbnail = true;
            String DocumentId = null;
            OutputStream os = response.getOutputStream();
            Connection conn = null;
            try {
                Context ctx = new InitialContext();
                DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/SMSDEV");
                conn = ds.getConnection();
                PreparedStatement statement = conn.prepareStatement(
                  "SELECT file_name, " +
                  "dlin.id, " +
                  "FROM  sms_document_links dlin " +
                  "sms_document_references dref" +
                  "WHERE dref.id = ?" +
                  "dref.dlin_id = dlin.id");
                if (detailDocumentId != null) {
                    DocumentId = detailDocumentId;
                    thumbnail = false;
                } else {
                    DocumentId = thumbnailDocumentId;
                statement.setString(1,(thumbnail ? "Y" : "N"));           
                statement.setInt(2, new Integer(DocumentId));
                ResultSet rs = statement.executeQuery();
                if (rs.next()) {
                    Blob blob = rs.getBlob("IMAGE");
                    BufferedInputStream in = new BufferedInputStream(blob.getBinaryStream());
                    int b; byte[] buffer = new byte[10240];
                    while ((b = in.read(buffer, 0, 10240)) != -1) { os.write(buffer, 0, b); }
                    os.close();
            } catch (Exception e){
                System.out.println(e);
            } finally {
                try{
                    if (conn != null){
                         conn.close();
                 } catch (SQLException sqle){
                     System.out.println("SQLException error");
        }Edited by: Tshifhiwa on 2012/05/29 1:52 PM
    Edited by: Tshifhiwa on 2012/05/29 1:56 PM

    hi this what i have done, am still having error with my iterator line= DCIteratorBinding lBinding = lBindingContainer.findIteratorBinding(sms4200ModuleDataControlIter),the error say type or variable sms4200ModuleDataControlIter not found but thats the name in my page defination,and is this the class i must write this method
    import com.sun.rowset.internal.Row;
    import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ContentType;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.sql.SQLException;
    import oracle.jbo.domain.BlobDomain;
    import oracle.jbo.domain.Timestamp;
    import oracle.jbo.server.AttributeDefImpl;
    import oracle.jbo.server.EntityImpl;
    import oracle.jbo.server.ViewRowImpl;
    import javax.faces.event.ValueChangeEvent;
    import org.apache.myfaces.trinidad.model.UploadedFile;
    import javax.faces.application.FacesMessage;
    import javax.faces.context.FacesContext;
    import javax.faces.event.ValueChangeEvent;
    import oracle.adf.model.binding.DCBindingContainer;
    import oracle.adf.model.binding.DCIteratorBinding;
    import oracle.adf.model.BindingContext;
    import oracle.adf.model.binding.DCIteratorBindingDef;
    import sms4200.common.SmsDocumentLinksViewRow;
    import sun.misc.IOUtils;
    // ---    File generated by Oracle ADF Business Components Design Time.
    // ---    Wed May 30 13:12:49 CAT 2012
    // ---    Custom code may be added to this class.
    // ---    Warning: Do not modify method signatures of generated methods.
    public class SmsDocumentLinksViewRowImpl extends ViewRowImpl implements SmsDocumentLinksViewRow {
        public static final int ENTITY_SMSDOCUMENTLINKS = 0;
        private static final String CONTENT_TYPE =
            "image/jpg; charset=utf-8";
            DocumentImage {
                public Object get(SmsDocumentLinksViewRowImpl obj) {
                    return obj.getDocumentImage();
                public void put(SmsDocumentLinksViewRowImpl obj, Object value) {
                    obj.setDocumentImage((BlobDomain)value);
      public static final int DOCUMENTIMAGE = AttributesEnum.DocumentImage.index();
        public BlobDomain getDocumentImage() {
            return (BlobDomain) getAttributeInternal(DOCUMENTIMAGE);
         * Sets <code>value</code> as attribute value for DOCUMENT_IMAGE using the alias name DocumentImage.
         * @param value value to set the DOCUMENT_IMAGE
        public void setDocumentImage(BlobDomain value) {
            setAttributeInternal(DOCUMENTIMAGE, value);
        private BlobDomain createBlobDomain(UploadedFile file)
            // init the internal variables
            InputStream in = null;
            BlobDomain blobDomain = null;
            OutputStream out = null;
            try
                // Get the input stream representing the data from the client
                in = file.getInputStream();
                // create the BlobDomain datatype to store the data in the db
                blobDomain = new BlobDomain();
                // get the outputStream for hte BlobDomain
                out = blobDomain.getBinaryOutputStream();
                // copy the input stream into the output stream
        39               * IOUtils is a class from the Apache Commons IO Package (http://www.apache.org/)
        40               * Here version 2.0.1 is used
        41               * please download it directly from http://projects.apache.org/projects/commons_io.html
        42               */
                IOUtils.copy(in, out);
            catch (IOException e)
                e.printStackTrace();
            catch (SQLException e)
                e.fillInStackTrace();
            // return the filled BlobDomain
            return blobDomain;
        public void uploadFileValueChangeEvent(ValueChangeEvent valueChangeEvent){
                    // The event give access to an Uploade dFile which contains data about the file and its content
                    // Get the original file name
                    UploadedFile file = (UploadedFile) valueChangeEvent.getNewValue();
                    // Get the original file name
                    String fileName = file.getFilename();
                    String contentType = CONTENT_TYPE.valueOf(fileName);
                        //get(fileName);
                    // get the current roew from the ImagesView2Iterator via the binding
                    DCBindingContainer lBindingContainer =
                        (DCBindingContainer) BindingContext.getCurrent().getCurrentBindingsEntry();
                   // DCIteratorBinding lBinding = lBindingContainer.findIteratorBinding(&quot;sms4200ModuleDataControlIter&quot;);
                      DCIteratorBinding lBinding = lBindingContainer.findIteratorBinding(sms4200ModuleDataControlIter);
                    Row newRow = (Row)lBinding.getCurrentRow();
                    // set the file name
                    //newRow.setAttribute(&quot;DOCUMENTIMAGE&quot; fileName);
                    newRow.setColumnObject(DOCUMENTIMAGE, fileName);
                    // create the BlobDomain and set it into the row
                   // newRow.setAttribute(DOCUMENTIMAGE, createBlobDomain(file));
                    newRow.setColumnObject(DOCUMENTIMAGE, createBlobDomain(file));
                    // set the mime type
                    //newRow.setAttribute(&quot;ContentType&quot;, contentType);
                    newRow.setColumnObject(DOCUMENTIMAGE,contentType);                                                       
    my PageDef file is
    <?xml version="1.0" encoding="UTF-8" ?>
    <pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel" version="11.1.2.60.81" id="sms4200PageDef"
                    Package="SmsFrontUI.pageDefs">
      <parameters/>
      <executables>
        <variableIterator id="variables"/>
        <iterator Binds="ViewObj1" RangeSize="25" DataControl="TaskFlowAppModuleDataControl" id="ViewObj1Iterator"/>
        <iterator Binds="sms4200_1" RangeSize="25" DataControl="TaskFlowAppModuleDataControl" id="sms4200_1Iterator"/>
        <iterator id="sms4200ModuleDataControlIter" DataControl="sms4200ModuleDataControl" RangeSize="25"
                  Binds="SmsDocumentLinksView1"/>
      </executables>
      <bindings>
        <attributeValues IterBinding="ViewObj1Iterator" id="IntegrationTypeName">
          <AttrNames>
            <Item Value="IntegrationTypeName"/>
          </AttrNames>
        </attributeValues>
        <attributeValues IterBinding="ViewObj1Iterator" id="Name">
          <AttrNames>
            <Item Value="Name"/>
          </AttrNames>
        </attributeValues>
        <attributeValues IterBinding="ViewObj1Iterator" id="LocalUpDirectory">
          <AttrNames>
            <Item Value="LocalUpDirectory"/>
          </AttrNames>
        </attributeValues>
        <attributeValues IterBinding="sms4200_1Iterator" id="IntegrationTypeName1">
          <AttrNames>
            <Item Value="IntegrationTypeName"/>
          </AttrNames>
        </attributeValues>
        <attributeValues IterBinding="sms4200_1Iterator" id="Name1">
          <AttrNames>
            <Item Value="Name"/>
          </AttrNames>
        </attributeValues>
        <attributeValues IterBinding="sms4200_1Iterator" id="LocalUpDirectory1">
          <AttrNames>
            <Item Value="LocalUpDirectory"/>
          </AttrNames>
        </attributeValues>
      </bindings>
    </pageDefinition>and my view is
    <?xml version="1.0" encoding="windows-1252" ?>
    <!DOCTYPE ViewObject SYSTEM "jbo_03_01.dtd">
    <!---->
    <ViewObject
      xmlns="http://xmlns.oracle.com/bc4j"
      Name="SmsDocumentLinksView"
      Version="11.1.2.60.81"
      SelectList="SmsDocumentLinks.ID,
           SmsDocumentLinks.EDRMS_ID,
           SmsDocumentLinks.FILE_PLAN_NO,
           SmsDocumentLinks.DOCUMENT_NAME,
           SmsDocumentLinks.SCAN_DT,
           SmsDocumentLinks.DATE_CREATED,
           SmsDocumentLinks.DATE_MODIFIED,
           SmsDocumentLinks.MODIFIED_BY,
           SmsDocumentLinks.CREATED_BY,
           SmsDocumentLinks.DOCUMENT_IMAGE,
           SmsDocumentLinks.DITYP_ID,
           SmsDocumentLinks.DWSTA_CODE,
           SmsDocumentLinks.SOURCE_FILE_NAME"
      FromList="SMS_DOCUMENT_LINKS SmsDocumentLinks"
      BindingStyle="OracleName"
      CustomQuery="false"
      PageIterMode="Full"
      UseGlueCode="false"
      RowClass="sms4200.SmsDocumentLinksViewRowImpl"
      ComponentClass="sms4200.SmsDocumentLinksViewImpl"
      RowInterface="sms4200.common.SmsDocumentLinksViewRow"
      ClientRowProxyName="sms4200.client.SmsDocumentLinksViewRowClient">
      <DesignTime>
        <Attr Name="_codeGenFlag2" Value="Access|Coll|Prog|VarAccess"/>
        <Attr Name="_isCodegen" Value="true"/>
      </DesignTime>
      <EntityUsage
        Name="SmsDocumentLinks"
        Entity="sms4200.SmsDocumentLinks"/>
      <ViewAttribute
        Name="Id"
        IsNotNull="true"
        PrecisionRule="true"
        EntityAttrName="Id"
        EntityUsage="SmsDocumentLinks"
        AliasName="ID">
        <TransientExpression><![CDATA[(new oracle.jbo.server.SequenceImpl("SMS_CAT_SEQ",adf.object.getDBTransaction())).getSequenceNumber()]]></TransientExpression>
      </ViewAttribute>
      <ViewAttribute
        Name="EdrmsId"
        PrecisionRule="true"
        EntityAttrName="EdrmsId"
        EntityUsage="SmsDocumentLinks"
        AliasName="EDRMS_ID"/>
      <ViewAttribute
        Name="FilePlanNo"
        PrecisionRule="true"
        EntityAttrName="FilePlanNo"
        EntityUsage="SmsDocumentLinks"
        AliasName="FILE_PLAN_NO"/>
      <ViewAttribute
        Name="DocumentName"
        PrecisionRule="true"
        EntityAttrName="DocumentName"
        EntityUsage="SmsDocumentLinks"
        AliasName="DOCUMENT_NAME"/>
      <ViewAttribute
        Name="ScanDt"
        PrecisionRule="true"
        EntityAttrName="ScanDt"
        EntityUsage="SmsDocumentLinks"
        AliasName="SCAN_DT"/>
      <ViewAttribute
        Name="DateCreated"
        PrecisionRule="true"
        EntityAttrName="DateCreated"
        EntityUsage="SmsDocumentLinks"
        AliasName="DATE_CREATED"/>
      <ViewAttribute
        Name="DateModified"
        PrecisionRule="true"
        EntityAttrName="DateModified"
        EntityUsage="SmsDocumentLinks"
        AliasName="DATE_MODIFIED"/>
      <ViewAttribute
        Name="ModifiedBy"
        PrecisionRule="true"
        EntityAttrName="ModifiedBy"
        EntityUsage="SmsDocumentLinks"
        AliasName="MODIFIED_BY"/>
      <ViewAttribute
        Name="CreatedBy"
        PrecisionRule="true"
        EntityAttrName="CreatedBy"
        EntityUsage="SmsDocumentLinks"
        AliasName="CREATED_BY"/>
      <ViewAttribute
        Name="DocumentImage"
        IsQueriable="false"
        PrecisionRule="true"
        EntityAttrName="DocumentImage"
        EntityUsage="SmsDocumentLinks"
        AliasName="DOCUMENT_IMAGE"/>
      <ViewAttribute
        Name="DitypId"
        PrecisionRule="true"
        EntityAttrName="DitypId"
        EntityUsage="SmsDocumentLinks"
        AliasName="DITYP_ID"/>
      <ViewAttribute
        Name="DwstaCode"
        PrecisionRule="true"
        EntityAttrName="DwstaCode"
        EntityUsage="SmsDocumentLinks"
        AliasName="DWSTA_CODE"/>
      <ViewAttribute
        Name="SourceFileName"
        PrecisionRule="true"
        EntityAttrName="SourceFileName"
        EntityUsage="SmsDocumentLinks"
        AliasName="SOURCE_FILE_NAME"/>
    </ViewObject>Edited by: Tshifhiwa on 2012/05/30 8:57 PM

  • How to send a HTTP request to servlet in java application

    I'm new in Java. I need to send a HTTP request with parameters to servlet in a java aplication. Here is my code. It can be compiled but always threw an exceptions when I ran it. Can anyone help?
    package coreservlets;
    import java.io.*;
    import java.net.*;
    public class PostHTTP
         public static void main(String args[])
              throws IOException, UnknownHostException {
              try
              // URL and servlet
                   URL myURL = new URL("http://pc076/servlet/coreservlets.OffHold");
                   URLConnection c = myURL.openConnection();
                   c.setUseCaches(false);
                   c.setDoOutput(true);
                   ByteArrayOutputStream byteStream = new ByteArrayOutputStream(512);
                   PrintWriter out = new PrintWriter(byteStream, true);
    //parameters
                   String postData = "REASON_CODE=3B&RSPCODE=JSmith&CASENUM=NA795401&REPLY=123&SOURCE=XYZ&REPLYLINK=http://pc076/servlet/coreservlets.ShowParameters";
                   out.print(postData);
                   out.flush();
                   String lengthString = String.valueOf(byteStream.size());
                   c.setRequestProperty("Content-Length", lengthString);
                   c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                   byteStream.writeTo(c.getOutputStream());
                   BufferedReader in =     new BufferedReader(new InputStreamReader
                                                 (c.getInputStream()));
                   String line;
                   //String linefeed = "\n";
                   //resultsArea.setText("");
                   while((line = in.readLine()) != null) {
                        System.out.println(line);
                        //resultsArea.append(linefeed);
              catch(IOException ioe) {
              // Print debug info in Java Console
              System.out.println("IOException: " + ioe);

    here are some updates to your code I haven't tested it running
    post again if you still have trouble
    URL myURL = new URL("http://pc076/servlet/coreservlets.OffHold");
    HttpURLConnection c = (HttpURLConnection)myURL.openConnection();
    c.setDoInput(true);
    c.setDoOutput(true);
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream(512);
    String lengthString = String.valueOf(byteStream.size());
    c.setRequestProperty("Content-Length", lengthString);
    c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    PrintWriter out = new PrintWriter(byteStream, true);
    //parameters
    String postData = "REASON_CODE=3B&RSPCODE=JSmith&CASENUM=NA795401&REPLY=123&SOURCE=XYZ&REPLYLINK=http://pc076/servlet/coreservlets.ShowParameters";
    out.print(postData);
    out.flush();
    byteStream.writeTo(c.getOutputStream());
    // connect
    c.connect();
    BufferedReader in = new BufferedReader(new InputStreamReader
    (c.getInputStream()));
    String line;
    while((line = in.readLine()) != null)
        System.out.println(line);

  • Show image in JDev

    Why the picture cannot be showed? Is there any wrong with the servlet code? What's wrong with my code?
    Thanks
    package javaclass;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import fuego.lang.ConnectionPassport;
    import fuego.lang.DynamicObject;
    import fuego.papi.Activity;
    import fuego.papi.Arguments;
    import fuego.papi.CommunicationException;
    import fuego.papi.InstanceInfo;
    import fuego.papi.OperationException;
    import fuego.papi.Process;
    import fuego.papi.ProcessService;
    import fuego.papi.ProcessServiceSession;
    import java.util.Properties;
    import fuego.workspace.UrlActions;
    import com.sun.image.codec.jpeg.*;
    import javax.imageio.stream.*;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    public class showWorkloadImgServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>showWorkloadImgServlet</title></head>");
    out.println("<body>");
    out.println("<p>The servlet has received a GET. This is the reply.</p>");
    out.println("</body><img src='http://192.168.125.125:8988/Application1-Project1-context-root/showworkloadimgservlet'></a></html>");
    out.close();
    Properties configuration = new Properties();
    System.out.println("25");
    configuration.setProperty(ProcessService.DIRECTORY_ID, "default");
    System.out.println("28");
    configuration.setProperty(ProcessService.DIRECTORY_PROPERTIES_FILE, "F:\\share\\192_168_1_16\\directory.xml");
    System.out.println("30");
    configuration.setProperty(ProcessService.WORKING_FOLDER, "/tmp");
    System.out.println("32");
    ProcessService processService=null;
    try {
    processService = ProcessService.create(configuration);
    } catch (CommunicationException e) {
    // TODO
    System.out.println("66===========");
    System.out.println("34");
    ConnectionPassport passport=null;
    passport = processService.createPassport("jcooper");
    passport.setPassword("welcome1");
    passport.fillPassport();
    System.out.println("38");
    ProcessServiceSession session=null;
    try {
    session = processService.createSession(passport, "192.168.1.16");
    } catch (OperationException e) {
    // TODO
    System.out.println("40");
    Arguments arguments = Arguments.create();
    DynamicObject argument = DynamicObject.create();
    argument.setField("condition", 600);
    argument.setField("orSplit", 400);
    arguments.putArgument("beginArg",argument);
    String processId2="/P1";
    try {
    session.processCreateInstance(processId2, arguments);
    } catch (OperationException e) {
    // TODO
    System.out.println("50");
    System.out.println("76");
    UrlActions ua=new UrlActions();
    String st="";
    String instanceId="/P1#Default-1.0/9863/0";
    String processId="/P1#Default-1.0";
    st=ua.showWorkloadImage(request, response, processId /*, instanceId*/);
    System.out.println("26="+st);
    OutputStream output = response.getOutputStream();
    String imagePath = getServletContext().getRealPath(st);
    InputStream imageIn = new FileInputStream(new File(imagePath));
    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(imageIn);
    BufferedImage image = decoder.decodeAsBufferedImage();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
    encoder.encode(image);
    imageIn.close();
    session.close();
    processService.close();
    [Starting OC4J using the following ports: HTTP=8988, RMI=23891, JMS=9227.]
    E:\Jdeveloper10131_20090318\jdev\system\oracle.j2ee.10.1.3.39.84\embedded-oc4j\config>
    D:\JDeveloper11g_20090318\jdk160_05\bin\javaw.exe -client -classpath E:\Jdeveloper10131_20090318\j2ee\home\oc4j.jar;E:\Jdeveloper10131_20090318\jdev\lib\jdev-oc4j-embedded.jar -Xverify:none -DcheckForUpdates=adminClientOnly -Doracle.application.environment=development -Doracle.j2ee.dont.use.memory.archive=true -Doracle.j2ee.http.socket.timeout=500 -Doc4j.jms.usePersistenceLockFiles=false oracle.oc4j.loader.boot.BootStrap -config E:\Jdeveloper10131_20090318\jdev\system\oracle.j2ee.10.1.3.39.84\embedded-oc4j\config\server.xml
    [waiting for the server to complete its initialization...]
    Oct 5, 2009 3:19:39 PM com.evermind.server.XMLDataSourcesConfig parseRootNode
    INFO: Legacy datasource detected...attempting to convert to new syntax.
    Oct 5, 2009 3:19:41 PM com.evermind.server.jms.JMSMessages log
    INFO: JMSServer[]: OC4J JMS server recovering transactions (commit 0) (rollback 0) (prepared 0).
    Oct 5, 2009 3:19:41 PM com.evermind.server.jms.JMSMessages log
    INFO: JMSServer[]: OC4J JMS server recovering local transactions Queue[jms/Oc4jJmsExceptionQueue].
    Ready message received from Oc4jNotifier.
    Embedded OC4J startup time: 13718 ms.
    Target URL -- http://192.168.1.16:8988/GDHZdemo-javaclass-context-root/showworkloadimgservlet
    09/10/05 15:19:47 Oracle Containers for J2EE 10g (10.1.3.1.0) initialized
    WARNING: Code-source D:\BPM_HOME_standalone\client\papi\lib\mail.jar (from manifest of /D:/BPM_HOME_standalone/client/papi/lib/fuegopapi-client.jar) has the same filename but is not identical to /E:/Jdeveloper10131_20090318/j2ee/home/lib/mail.jar (from <code-source> (ignore manifest Class-Path) in META-INF/boot.xml in E:\Jdeveloper10131_20090318\j2ee\home\oc4j.jar). If it contains different versions of the same classes, it will be masked as the latter is already visible in the search path of loader current-workspace-app.web.GDHZdemo-javaclass-webapp:0.0.0.
    WARNING: Code-source D:\BPM_HOME_standalone\client\papi\lib\jaxrpc-api.jar (from manifest of /D:/BPM_HOME_standalone/client/papi/lib/fuegopapi-client.jar) has the same filename but is not identical to /E:/Jdeveloper10131_20090318/webservices/lib/jaxrpc-api.jar (from <code-source> (ignore manifest Class-Path) in META-INF/boot.xml in E:\Jdeveloper10131_20090318\j2ee\home\oc4j.jar). If it contains different versions of the same classes, it will be masked as the latter is already visible in the search path of loader current-workspace-app.web.GDHZdemo-javaclass-webapp:0.0.0.
    WARNING: Code-source D:\BPM_HOME_standalone\client\papi\lib\saaj-api.jar (from manifest of /D:/BPM_HOME_standalone/client/papi/lib/fuegopapi-client.jar) has the same filename but is not identical to /E:/Jdeveloper10131_20090318/webservices/lib/saaj-api.jar (from <code-source> (ignore manifest Class-Path) in META-INF/boot.xml in E:\Jdeveloper10131_20090318\j2ee\home\oc4j.jar). If it contains different versions of the same classes, it will be masked as the latter is already visible in the search path of loader current-workspace-app.web.GDHZdemo-javaclass-webapp:0.0.0.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\catalina-optional.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\catalina.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\commons-el.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\commons-logging.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\commons-modeler.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\jasper-compiler-jdt.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\jasper-compiler.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\jasper-runtime.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\jsp-api.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\naming-factory.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\naming-resources.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\servlet-api.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\servlets-default.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\tomcat-coyote.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\tomcat-http.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    Could not canonicalize 'D:\BPM_HOME_standalone\client\papi\lib\D:\fuego\trunk\local\thirdparty\tomcat-embed\dist\apache-tomcat-5.5.15-embed\lib\tomcat-util.jar' (????????????????). From manifest of /D:/BPM_HOME_standalone/client/papi/lib/catalina.jar.
    09/10/05 15:19:50 25
    09/10/05 15:19:50 28
    09/10/05 15:19:50 30
    09/10/05 15:19:50 32
    09/10/05 15:19:51 java.io.IOException: ????????????????
    09/10/05 15:19:51      at java.io.WinNTFileSystem.canonicalize0(Native Method)
    09/10/05 15:19:51      at java.io.Win32FileSystem.canonicalize(Win32FileSystem.java:396)
    09/10/05 15:19:51      at java.io.File.getCanonicalPath(File.java:559)
    09/10/05 15:19:51      at java.io.File.getCanonicalFile(File.java:583)
    09/10/05 15:19:51      at fuego.boot.ClassPath.getBaseDir(ClassPath.java:402)
    09/10/05 15:19:51      at fuego.boot.ClassPath.getBaseDir(ClassPath.java:290)
    09/10/05 15:19:51      at fuego.boot.Loader.getInstallationDir(Loader.java:652)
    09/10/05 15:19:51      at fuego.util.FuegoDirectories.installationDir(FuegoDirectories.java:97)
    09/10/05 15:19:51      at fuego.util.FuegoDirectories.installationRelativeFile(FuegoDirectories.java:106)
    09/10/05 15:19:51      at fuego.util.FuegoDirectories.configDir(FuegoDirectories.java:167)
    09/10/05 15:19:51      at fuego.directory.DirectoryConfigurationManager.createDefaultRuntimeDirectoryConfigurationManager(DirectoryConfigurationManager.java:376)
    09/10/05 15:19:51      at fuego.directory.DirectoryConfigurationManager.<clinit>(DirectoryConfigurationManager.java:410)
    09/10/05 15:19:51      at fuego.papi.impl.ProcessServiceFactoryImpl.create(ProcessServiceFactoryImpl.java:55)
    09/10/05 15:19:51      at fuego.papi.ProcessService.create(ProcessService.java:335)
    09/10/05 15:19:51      at javaclass.showWorkloadImgServlet.doGet(showWorkloadImgServlet.java:70)
    09/10/05 15:19:51      at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
    09/10/05 15:19:51      at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    09/10/05 15:19:51      at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:711)
    09/10/05 15:19:51      at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:368)
    09/10/05 15:19:51      at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:866)
    09/10/05 15:19:51      at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:448)
    09/10/05 15:19:51      at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:216)
    09/10/05 15:19:51      at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:117)
    09/10/05 15:19:51      at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:110)
    09/10/05 15:19:51      at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
    09/10/05 15:19:51      at oracle.oc4j.network.ServerSocketAcceptHandler.procClientSocket(ServerSocketAcceptHandler.java:239)
    09/10/05 15:19:51      at oracle.oc4j.network.ServerSocketAcceptHandler.access$700(ServerSocketAcceptHandler.java:34)
    09/10/05 15:19:51      at oracle.oc4j.network.ServerSocketAcceptHandler$AcceptHandlerHorse.run(ServerSocketAcceptHandler.java:880)
    09/10/05 15:19:51      at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:298)
    09/10/05 15:19:51      at java.lang.Thread.run(Thread.java:619)
    09/10/05 15:20:40 25
    09/10/05 15:20:40 28
    09/10/05 15:20:40 30
    09/10/05 15:20:40 32
    Process exited.

    I guess the ImageServlet class of the StoreFront demo of JDeveloper 11g is a good start for you. Below is the code snippet:
    package oracle.fodemo.storefront.servlet;
    import java.io.BufferedInputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.sql.DataSource;
    public class ImageServlet extends HttpServlet {
    private static final String CONTENT_TYPE =
    "image/jpg; charset=utf-8";
    * @param config
    * @throws ServletException
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    * @param request
    * @param response
    * @throws ServletException
    * @throws IOException
    public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    IOException {
    response.setContentType(CONTENT_TYPE);
    response.setContentType(CONTENT_TYPE);
    String detailProductId = request.getParameter("detail");
    String thumbnailProductId = request.getParameter("thumbnail");
    boolean thumbnail = true;
    String productId = null;
    OutputStream os = response.getOutputStream();
    Connection conn = null;
    try {
    Context ctx = new InitialContext();
    DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/FODDS");
    conn = ds.getConnection();
    PreparedStatement statement = conn.prepareStatement(
    "SELECT ProductImageEO.PRODUCT_IMAGE_ID, " +
    " ProductImageEO.PRODUCT_ID, " +
    " ProductImageEO.DEFAULT_VIEW_FLAG, " +
    " ProductImageEO.DETAIL_IMAGE_ID, " +
    " ProductImageEO.IMAGE " +
    "FROM PRODUCT_IMAGES ProductImageEO " +
    "WHERE ProductImageEO.DEFAULT_VIEW_FLAG = ?" +
    " AND ProductImageEO.PRODUCT_ID = ?");
    if (detailProductId != null) {
    productId = detailProductId;
    thumbnail = false;
    } else {
    productId = thumbnailProductId;
    statement.setString(1,(thumbnail ? "Y" : "N"));
    statement.setInt(2, new Integer(productId));
    ResultSet rs = statement.executeQuery();
    if (rs.next()) {
    Blob blob = rs.getBlob("IMAGE");
    BufferedInputStream in = new BufferedInputStream(blob.getBinaryStream());
    int b; byte[] buffer = new byte[10240];
    while ((b = in.read(buffer, 0, 10240)) != -1) { os.write(buffer, 0, b); }
    os.close();
    } catch (Exception e){
    System.out.println(e);
    } finally {
    try{
    if (conn != null){
    conn.close();
    } catch (SQLException sqle){
    System.out.println("SQLException error");
    regards,
    pino

  • Long Raw Picture not showing in adf

    I have used following servlet to show long raw picture. the problem is in line
    Blob blob = rs.getBlob("PLAN_PIC"); 
    The oracle column is Long Raw  and in ADF table this column shows as Raw. I have tried to use Raw class but could not identify proper functions. For example I used      Long blob=rs.getLong("PLAN_PIC"); it is ok but then how to get its buffered binary stream because getBinaryStream() does not work for long. I also tried to use to_blob function to convert long raw column to blob but it also gives ora-0932 error. The same table shows picture in oracle form and also Dot Net developer showed the same picture. Kindly help.
    //servlet code is
    public class imageservlet extends HttpServlet {
       // private static final String CONTENT_TYPE = "text/html; charset=UTF-8";   ( I checked both content types but nothing)
          private static final String CONTENT_TYPE =   "image/jpg; charset=utf-8";
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        public void doGet(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException,
                                                               IOException {
            response.setContentType(CONTENT_TYPE);
            String imageId = request.getParameter("id");
           // String imageId="4000";
            OutputStream os = response.getOutputStream();
            Connection conn = null;
            try {
                Context ctx = new InitialContext();
                //Datasource as defined in <res-ref-name> element of weblogic.xml
                DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/DYEDS");
                conn = ds.getConnection();
                PreparedStatement statement =
                    conn.prepareStatement("SELECT plan_no, plan_pic " +
                                          "FROM tblplanpics " +
                                          "WHERE plan_no = ?");
               // statement.setInt(1, new Integer(imageId));
                statement.setString(1,imageId);
                ResultSet rs = statement.executeQuery();
                if (rs.next()) {
                   Blob blob = rs.getBlob("PLAN_PIC");     
                    BufferedInputStream in =
                        new BufferedInputStream(blob.getBinaryStream());
                    int b;
                    byte[] buffer = new byte[10240];
                    while ((b = in.read(buffer, 0, 10240)) != -1) {
                        os.write(buffer, 0, b);
                    os.close();
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                } catch (SQLException sqle) {
                    System.out.println("SQLException error");

    The answers are the same as in your other thread https://forums.oracle.com/thread/2591893 about this issue.
    Timo

  • How to show long raw picture  in adf jsp

    Pictures are stored in long raw column in oracle database. I have followed to show picture based on servlet to retrieve image from blob column but to no success. Kindly help.

    Thanks for helping.
    I have  already used following servlet but no picture. I think problem is in specific line because image is in Long Raw instead of Blob..
    Blob blob = rs.getBlob("PLAN_PIC");
    Image Servlet
    public class imageservlet extends HttpServlet {
        private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        public void doGet(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException,
                                                               IOException {
            response.setContentType(CONTENT_TYPE);
            String imageId = request.getParameter("id");
           // String imageId="4000";
            OutputStream os = response.getOutputStream();
            Connection conn = null;
            try {
                Context ctx = new InitialContext();
                //Datasource as defined in <res-ref-name> element of weblogic.xml
                DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/DYEDS");
                conn = ds.getConnection();
                PreparedStatement statement =
                    conn.prepareStatement("SELECT plan_no, plan_pic " +
                                          "FROM tblplanpics " +
                                          "WHERE plan_no = ?");
               // statement.setInt(1, new Integer(imageId));
                statement.setString(1,imageId);
                ResultSet rs = statement.executeQuery();
                if (rs.next()) {
             //       Blob blob = rs.getBlob("PLAN_PIC");
                  Blob blob = rs.getBlob("PLAN_PIC");
                    BufferedInputStream in =
                        new BufferedInputStream(blob.getBinaryStream());
                    int b;
                    byte[] buffer = new byte[10240];
                    while ((b = in.read(buffer, 0, 10240)) != -1) {
                        os.write(buffer, 0, b);
                    os.close();
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                } catch (SQLException sqle) {
                    System.out.println("SQLException error");

  • How to test ImageServlet on JDev 10.1.3 (OCJ4) ?

    Hello,
    I download StoreFront.zip OTN sample and modify Imageservlet class to read blob data into an image object on my jspx.
    I place a breakpoint in ImageServlet's source, and run my test with debug mode. The jspx is displayed but the ImageServlet is not executed !
    DO I NEED TO CONFIGURE SOMETHING TO MAKE IMAGESERVLET ACCESSIBLE TO MY JSPX ?
    Thanks.
    1. Image object with test value of 21321955
    ....... and so on
    <af:objectImage height="200" width="180"
    binding="#{backing_app_Tax_MissionTax.objectImage1}"
    id="objectImage1"
    source="/imageservlet?personid=21321955"/>
    ...... and so on
    2. ImageServlet class
    public class ImageServlet extends HttpServlet {
    private static final String CONTENT_TYPE =
    "image/jpg; charset=utf-8";
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    IOException {
    response.setContentType(CONTENT_TYPE);
    response.setContentType(CONTENT_TYPE);
    String personId = request.getParameter("personid");
    if (personId == null) {
    return;
    OutputStream os = response.getOutputStream();
    Connection conn = null;
    try {
    Context ctx = new InitialContext();
    DataSource ds = (DataSource)ctx.lookup("jdbc/P03DB");
    conn = ds.getConnection();
    PreparedStatement statement = conn.prepareStatement(
    "SELECT PersonImage.PID, " +
    " PersonImage.PORTRAIT " +
    "FROM IMAGE.PORTRAITS PersonImage " +
    "WHERE PersonImage.PID = ?");
    statement.setInt(10, new Integer(personId));
    ResultSet rs = statement.executeQuery();
    if (rs.next()) {
    Blob blob = rs.getBlob("PORTRAIT");
    BufferedInputStream in = new BufferedInputStream (blob.getBinaryStream());
    int b; byte[] buffer = new byte[4096];
    while ((b = in.read(buffer, 0, 4096)) != -1) { os.write(buffer, 0, b); }
    os.close();
    } catch (Exception e){
    e.printStackTrace();
    } finally {
    try{
    if (conn != null){
    conn.close();
    } catch (SQLException sqle){
    sqle.printStackTrace();
    }

    That's why I asked whether you have tried to invoke the servlet directly. It would have shown that your web.xml configuration wasn't correct for that.
    By packaging I mean that the JSPX and the Servlet are in the same project or web application (WAR).
    --olaf                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Where can I find the description of the codes returned by exitValue()?

    Hi Everybody,
    I have a java porgram on HP/UX and this program executes the OS level commands and exe file on HP UNIX. When I supply "/usr/bin ls -l" as a param to this program it executes it very well.
    But if I pass the "/utils/Myapp/app arg1 arg2" as a parameter it returns some non zero codes
    I tried several ways to make it work and I even harcoded the "/utils/Myapp/app arg1 arg2" in the program but it never executes it properly and I got the following return Code return by exitvalue() during my hit and trial method.
    255,17,15,12
    Does any one have clue what are they.
    Note: When I executes /utils/Myapp/app arg1 arg2" from the UNIX prompt it works fine
    The java program is given below.
    Pl help
    Thanks
    Yatsomy.
    This is my first program in JAVA.
    import java.lang.Runtime;
    import java.lang.Process;
    import java.io.IOException;
    import java.lang.InterruptedException;
    class executecmd {
    public static void main(String args[]) {
    System.out.println("In main");
    try {
    /* Execute the command using the Runtime object and get the
    Process which controls this command */
    Process p = Runtime.getRuntime().exec(args[0]);
    /* Use the following code to wait for the process to finish
    and check the return code from the process */
    try {
    p.waitFor();
    /* Handle exceptions for waitFor() */
    } catch (InterruptedException intexc) {
    System.out.println("Interrupted Exception on waitFor: " + intexc.getMessage());
    System.out.println("Return code from process"+ p.exitValue());
    System.out.println("Done executing");
    /* Handle the exceptions for exec() */
    } catch (IOException e) {
    System.out.println("IO Exception from exec : " + e.getMessage());
    e.printStackTrace();

    1. exitValue() codes are the numeric codes returned by native applications you're calling: the meaning of this code is both application and platform dependant (it has nothing to do with java), so you should try to find those info in "app" documentation, or in HP Unix standard docs.
    2. I think you'd better "debug" the Runtime.exec() behaviour by capturing stdout and especially stderr of the spawned process: doing so, you will be able to see error messages printed out by called applications or commands...
    It's very simple using this small class:
    /** connects I/O streams, just like a pipe :-)
    * @author: Giorgio Maone
    class Pipe {
    private InputStream in;
    private OutputStream out;
    public Pipe(InputStream in, OutputStream out) {
       this.in=in; this.out=out;
    public void connect() {
       new Thread() {
        public void run() {
         try {
          for(int b;(b=in.read())!=-1;) {
            out.write(b);
          out.flush();
        } catch(IOException ex) {}
      }.start();
    }So you can do this:
    Process p = Runtime.getRuntime().exec(args[0]);
    new Pipe(p.getInputStream(),System.out).connect();
    new Pipe(p.getErrorStream(),System.out).connect();
    new Pipe(System.in,p.getOutputStream()).connect();
    try {
    System.out.println("Exit code: "+p.waitFor());
    } catch(InterruptedException ex) {}If you want to use a "smart wrapper" on Runtime.exec(), feel free to use my MultiExec class:
    /** executes multiple commands in one shell
    * @author: Giorgio Maone
    import java.io.*;
    public class MultiExec {
    static final boolean IS_WIN=System.getProperty("os.name").toLowerCase().indexOf("win")==0;
    protected String shell=IS_WIN?"":"sh";
    public void setShell(String s) {
       shell=s;
    public String getShell() {
       return shell;
    public Process exec(String cmds[]) throws IOException {
      File f=File.createTempFile("muexec",".bat");
      PrintWriter out=new PrintWriter(new FileWriter(f));
      if(IS_WIN) out.println("@echo off");
      for(int j=0,len=cmds.length; j<len; j++)
        out.println(cmds[j]);
      out.close();
      f.deleteOnExit();
      return Runtime.getRuntime().exec(shell+" "+f.getCanonicalPath());
    public int execAndWait(String cmds[]) throws IOException {
       Process p=exec(cmds);
      new Pipe(p.getInputStream(),System.out).connect();
      new Pipe(p.getErrorStream(),System.out).connect();
      new Pipe(System.in,p.getOutputStream()).connect();
      int exitCode=-1;
      try {
       exitCode=p.waitFor();
       } catch(InterruptedException ex) {}
      return exitCode;
    static class Pipe {
       private InputStream in;
      private OutputStream out;
      public Pipe(InputStream in, OutputStream out) {
        this.in=in; this.out=out;
      public void connect() {
        new Thread() {
         public void run() {
          try {
           for(int b;(b=in.read())!=-1;) {
             out.write(b);
           out.flush();
         } catch(IOException ex) {}
       }.start();

  • Servlet Database I/O: How to "lock" a record being updated ?

    Say you have a servlet that displays a list of customers in HTML page, and a button on each customer to click to bring up another page (servlet generated) with the customer info to edit. The customer info is in a database file (could be Access or ORACLE). User makes any changes and clicks a button to update the customer record (with a servlet).
    How do you prevent two users from editing the same customer record at the same time? I do not want to lock the whole file, just a record.
    Any pointers towards info about this subject appreciated.
    Walk Good

    sridharranganathan, does your technique assume that the read operation is locked, so that two users cannot obtain the same value of LockCounter?
    I have some questions relevant to the following code:
    public class theServlet extends HttpServlet
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException
             Helper theHelper = new Helper();
             theHelper.setUser(req.getCookies);
             resp.setContentType("text/html");
                PrintWriter out = new PrintWriter(resp.getOutputStream());
                Connection con = null;
             try
                   SybDriver sybDriver = (SybDriver) Class.forName("com.sybase.jdbc2.jdbc.SybDriver").newInstance();
                   sybDriver.setVersion(com.sybase.jdbcx.SybDriver.VERSION_5);
                   DriverManager.registerDriver(sybDriver);
                   con = DriverManager.getConnection("jdbc:sybase:Tds:dbsrv1:3520/hospcap", "myuserid", "mypassword");                 if (con != null) {
                  if(theHelper.getUserRecord(con, this)) {
                           //do some stuff
                        else { //do some other stuff }
                        con.close();
                 }catch(Exception e) { //whatever }
                 finally { out.flush(); }
             } //end doGet()
    } //end class
    public class Helper {
        private String user = "";
        private String field1Val= "";
        private String field2Val= "";
        public boolean setUser(Cookie [] cookies) {
         // method gets the user's userid from a cookie and then:
            user = user_id_from_cookie;
       public boolean getUserRecord(Connection con, theServlet serv){
            StringBuffer sb = new StringBuffer();
            Statement stmt = null;
         try {
             //Try to get the user's info:
                stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
             StringBuffer sql = new StringBuffer("SELECT field1, field2 FROM UserRecords WHERE user_id = '" + user + "'");
             ResultSet rs = stmt.executeQuery(sql.toString());
                rs.last();
                int nrows = rs.getRow();
                if(nrows < 1) { //user doesn't have an entry in the table yet.
                 //First, get result set of records with blank userids:
                 sql.replace(0, sql.length(), "SELECT * FROM UserRecords WHERE user_id = '' OR user_id = NULL ORDER BY field1");
              rs = stmt.executeQuery(sql.toString());
                    rs.last();
                    nrows = rs.getRow();
                 if(nrows > 0) {
                     //there ARE some records with null user_id, so assign this user to the first one:
                        rs.first();
                     field1Val = rs.getString("field1").trim();
                     field2Val = rs.getString("field2").trim();
                        //QUESTION: IS IT POSSIBLE THAT TWO USERS/THREADS HAVE THE SAME VALUE OF field1Val AT THIS POINT?
                     sql.replace(0, sql.length(), "UPDATE UserRecords SET user_id = '" + user + "' ");
                     sql.append(" WHERE field1 = '" + field1Val+ "' AND user_id is NULL");
                  con.setAutoCommit(false);
                  //Trying to use transaction isolation to prevent two users from updating the same record.
                  //Does this only work if the users share the connection, con?
                  int level = con.getTransactionIsolation();
                  try {
                      if(con.getMetaData().supportsTransactionIsolationLevel(con.TRANSACTION_READ_COMMITTED)) {
                          con.setTransactionIsolation(con.TRANSACTION_READ_COMMITTED);
                            //SYNCHRONIZE ON SERVLET INSTANCE?
                      //synchronized(serv){
                            nrows = stmt.executeUpdate(sql.toString());
                  }catch(SQLException se) {
                         con.rollback();
                         con.setAutoCommit(true);
                         con.setTransactionIsolation(level);
                         stmt.close();
                         return false;
                     con.commit();
                     con.setAutoCommit(true);
                     con.setTransactionIsolation(level);
                        if(nrows < 1) { //couldn't update the db.
                         stmt.close();
                         return false;
                     else {
                         stmt.close();
                         return true;
                 else { //There aren't any unused records; deal with it.
                     stmt.close();
                     return false;
                else { // the user has an entry in the table
                    rs.first(); //should only be one record for this userid.
                    field1Val = rs.getString("field1").trim();
                    field2Val = rs.getString("field2").trim();
                    stmt.close();
                 return true;
            }catch(SQLException se) {
             //some problem not caught elsewhere
             return false;
       } // end getUserRecord
    } // end class HelperI should say that the UserRecords table now contains about 5000 records (this will grow in increments of 5000), many of which have null user_id. If the value is not null, then it contains a userid. A user can have either zero or one entry in the table.
    Here are my questions regarding the above:
    1. In the servlet, each thread will have its own instance of Helper and of Connection, correct?
    2. I want to ensure that only one thread can update a particular UserRecords table record at a time. In the getUserRecord method, please note the line where field1Val is assigned, just above the capitalized QUESTION comment. Is it possible that two threads could have the same value of field1Val at the same time?
    3. When you set the transaction isolation level for connection1, does that prevent other threads that are using other connections to the database from accessing records being updated by the thread using connection1?
    4. As you can see, I am considering passing a reference to the servlet instance into the getUserRecords method and synchronizing the update statement on the servlet instance. Will that ensure only one thread at a time can update the record, without using the transaction isolation code?
    Thanks in advance for your answer.

  • Set directory path

    I have to call native applications from within my java application (using the Runtime.getRuntime().exec() method). That works fine but I need to change the current directory path to a specific path.
    How it is done to change the current directory path with java ?
    Steffen Kux.

    You can use one class of mine that I already posted to this forums some time ago...
    /** executes multiple commands in one shell
    * @author: Giorgio Maone
    import java.io.*;
    public class MultiExec {
    static final boolean IS_WIN=System.getProperty("os.name").toLowerCase().indexOf("win")==0;
    protected String shell=IS_WIN?"":"sh";
    public void setShell(String s) {
       shell=s;
    public String getShell() {
       return shell;
    public Process exec(String cmds[]) throws IOException {
      File f=File.createTempFile("muexec",".bat");
      PrintWriter out=new PrintWriter(new FileWriter(f));
      if(IS_WIN) out.println("@echo off");
      for(int j=0,len=cmds.length; j<len; j++)
        out.println(cmds[j]);
      out.close();
      f.deleteOnExit();
      return Runtime.getRuntime().exec(shell+" "+f.getCanonicalPath());
    public int execAndWait(String cmds[]) throws IOException {
       Process p=exec(cmds);
      new Pipe(p.getInputStream(),System.out).connect();
      new Pipe(p.getErrorStream(),System.out).connect();
      new Pipe(System.in,p.getOutputStream()).connect();
      int exitCode=-1;
      try {
       exitCode=p.waitFor();
       } catch(InterruptedException ex) {}
      return exitCode;
    static class Pipe {
       private InputStream in;
      private OutputStream out;
      public Pipe(InputStream in, OutputStream out) {
        this.in=in; this.out=out;
      public void connect() {
        new Thread() {
         public void run() {
          try {
           for(int b;(b=in.read())!=-1;) {
             out.write(b);
           out.flush();
         } catch(IOException ex) {}
       }.start();
    // Test code
    public static void main(String[] args) throws Exception {
    String path=args[0];
    String drive=path.indexOf(":")==1?path.substring(0,1):"";
    System.out.println("\nExit code:"+
      new MultiExec().execAndWait(
       new String[]{
        drive,
        "cd "+path,
        args[1];
    }

Maybe you are looking for

  • Flash CS4: My animated gif isn't playing right in flash

    Thank you so much for your help. I made an animated gif in Photoshop CS4 and opened it in Flash CS4, but for some reason the gif won't play without interruption. I opened and played it without a problem several times in Internet Explorer and Safari,

  • Exception EOlesysERROR in module Skype.exe @ 00129...

    Skype ran with no problems prior to the latest update. Computer is Dell Latitude laptop running Win 7 Ultimate SP 1 64-bit. First Install 1. Logged in to local admin account. 2. Disabled malwarebytes realtime protection. 3. Got a fresh download from

  • Deferred transaction fails due to a "ORA-01403: no data found" error

    I recently acticated replication between two Oracle instances. (one being the master definition site and the other one being a second master site). Everything was going well until two weeks ago, when i realized that some datas were different between

  • Canon EOS 6D - Black & White photos

    Hello, With my current camera (Canon Powershot IS 50) I can do black & white photos but tell the camera which colour should remain (so for example I can do pics where all the photo is black & white but the red colours stay red, etc.) I would like to

  • How to view .chm file in internet explorer

    Hi Friends, I have one .chm file with me and I have to add this file as a help file for my application. When I tried to open this file in browser its not opening properly. Can anyone suggest how to open this .chm file in proper format? Regards, Wahid