BufferedReader  error on i.4

Hi,
I see following exception, when try to use BufferedReader to get the inputstream form the HttpsURLConnection object.
Not sure if the handshanking is happening properly. The program is on jdk 1.5.0.
Can anyone please help me figure out what is happening?
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewH
ttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Sour
ce)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect
(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown So
urce)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unkn
own Source)
at testing.main(testing.java:90)
Thanks!
Kav_madhu

Thanks ghstark! I suspect TCP handshake.Also, I'm using intranet site, firewall shuld not be an issue, right? Here my code,
Pls let me know..
public class test_ssl{
public static void main(String[] args) throws Exception {
     URL url;
HttpsURLConnection urlConnection1,urlConnection;
String line;
String fullURL = new String();
     Boolean res;
String URLPASSWD = "user:test_password";
Calendar c = Calendar.getInstance();
Provider sunJCE = new com.sun.crypto.provider.SunJCE();
Security.addProvider(sunJCE);
     System.getProperties().put("org.w3c.www.protocol.http.connections.timeout","1200000" );
     fullURL = "https://interanetsite";
url = new URL(fullURL);
     urlConnection = (HttpsURLConnection)url.openConnection();
     String userPassword = URLPASSWD ; //URLPASSWD
String encoding = new sun.misc.BASE64Encoder().encode     (userPassword.getBytes());
urlConnection.setRequestProperty("Authorization", "Basic "      +      encoding);
c = Calendar.getInstance();
String s = c.toString() ;
byte[] seed = s.getBytes() ;
SecureRandom secRand = new SecureRandom(seed);
// SSLContext context = new SSLContext(secRand);
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
     new X509TrustManager() {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
          return null;}
          public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
          public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
// Install the all-trusting trust manager
try {
     SSLContext sc = SSLContext.getInstance("SSL");
     sc.init(null, trustAllCerts, secRand);
     urlConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
     urlConnection.setRequestProperty("Content-Type", "MIME");
}catch (Exception essl) {
          essl.printStackTrace();}
InputStream inStream = urlConnection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
try {
while ((line =in.readLine()) != null) {
out.write(line); }
out.flush();
catch (Exception e1){
e1.printStackTrace();}
}//end main
}//end class

Similar Messages

  • Java interactive Shell command Execution

    Hello,
    I wish to execute a shell command with password from a java program. I want to issue the first command "serctl add 2000 password email" and then when prompted for a MySQL password, enter it.
    Below is my current code. I think it is going into an infinite loop. When I comment out the "while ((s = in.readLine()) != null){" portion of the code, I dont get an infinite loop but then i dont know how to enter the password.
    Can someone please please help me as im really stuck on this?
    BR,
    Aisling.
    String[] command = { "serctl", "add", 2000, password, email};
    Runtime runtime = Runtime.getRuntime();
       Process process = null;
       response.setContentType(CONTENT_TYPE);
       PrintWriter out = response.getWriter();
       String s = null;
       try {
         process = runtime.exec(command);
         System.out.println(process);
         BufferedReader in =
         new BufferedReader(new InputStreamReader(process.getInputStream()));
         BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
         OutputStream stdout = process.getOutputStream();
         String pwd ="password";
      /*   while((s=in.readLine())!=null)
           s = in.readLine();
           System.out.println(s);
           stdout.write(pwd.getBytes());
           stdout.flush();
         System.out.println("Here is the standard error of the command(if any):\n");
         while ((s = error.readLine()) != null){
           System.out.println(s);
         stdout.close();
         in.close();
         error.close();

    Thats great and I think that should have worked...However its still hanging and evidently going into some kind of loop....very strange.
    If I execute the command in a shell its as follows:
    localhost: ~# serctl add 2000 password email
    MySql password: password
    My new code is below:
    String[] command = { "serctl", "add", username, password, email};
       Runtime runtime = Runtime.getRuntime();
       Process process = null;
       response.setContentType(CONTENT_TYPE);
       PrintWriter out = response.getWriter();
       String s = null;
       try {
         process = runtime.exec(command);
         System.out.println(process);
         BufferedReader in =
         new BufferedReader(new InputStreamReader(process.getInputStream()));
         BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
         OutputStream stdout = process.getOutputStream();
         String pwd ="password";
         while((s=in.readLine())!=null)
           //s = in.readLine();
           System.out.println(s);
           if (s.equals("MySql password:")) {
             stdout.write(pwd.getBytes());
             stdout.flush();
             break;
         System.out.println("Here is the standard error of the command(if any):\n");
         while ((s = error.readLine()) != null){
           System.out.println(s);
         stdout.close();
         in.close();
         error.close();Any more ideas?
    Many thanks for help so far,
    Aisling.

  • Repost my question

    I want to use "telnet" in java program in this way:
    1.run telnet(such as using runtime class)
    2.wait for the '>'
    3.input : open www.website.....
    So I thought out a way to use I/O redirection
    I redirect the output stream of telnet into the JTextArea to show the output,
    and I can see the output.
    Next I wait for the output of '>', but failed in my program.
    I don't know why.....
    I want to wait for the '>', so I can input using the directed input I/O.
    1.Exe_test.java
    public class Exe_test extends JTextArea {
        private boolean keepRunning = true;
        OutputStream shellstream;
        public Exe_test(InputStream[] inStreams,OutputStream mystream) {
            for(int i = 0; i < inStreams.length; ++i)
                startConsoleReaderThread(inStreams);
    shellstream = mystream;
    private void startConsoleReaderThread(
    InputStream inStream){
    final BufferedReader br =
    new BufferedReader(new InputStreamReader(inStream));
    new Thread(new Runnable() {
    public void run() {
    try {
    Thread.sleep(6000);
    } catch (InterruptedException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    StringBuffer sb = new StringBuffer();
    OutputStreamWriter my = new OutputStreamWriter(shellstream);
    try {
    my.write("ping bbs.fudan.edu.cn");
    System.out.println("dasdad");
    } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    while(keepRunning)
    try {
    String s;
    Document doc = getDocument();
    while((s = br.readLine()) != null) {
    System.out.println("hello");
    boolean caretAtEnd = false;
    caretAtEnd = getCaretPosition() == doc.getLength() ?
    true : false;
    sb.setLength(0);
    append(sb.append(s).append("\n").toString());
    System.out.println(s);
    if(caretAtEnd)
    setCaretPosition(doc.getLength());
    catch(IOException e) {
    JOptionPane.showMessageDialog(null,
    "from BufferedReader error:" + e);
    System.exit(1);
    }).start();
    2.AppOutputCapture.java
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    public class AppOutputCapture {
        private static Process process;
        public static void main(String[] args) {
            try {
                process = Runtime.getRuntime().exec("nslookup");
                        //"C:\\agfl_2.3.0\\epforir-2.3\\epforir.exe");
            } catch (IOException e) {
                System.err.println("init error...\n" + e);
                System.exit(1);
            InputStream[] inStreams = new InputStream[] { process.getInputStream()};//,
                    //process.getErrorStream() };
            OutputStream sentence = process.getOutputStream();
            Exe_test cta = new Exe_test(inStreams,sentence);
            cta.setFont(java.awt.Font.decode("monospaced"));
            JFrame frame = new JFrame("console output");
            frame.getContentPane().add(new JScrollPane(cta), BorderLayout.CENTER);
            frame.setBounds(50, 50, 400, 400);
            frame.setVisible(true);
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    process.destroy();
                    try {
                        process.waitFor();
                    } catch (InterruptedException e) {
                    System.exit(0);
        } // main()
    } // AppOutputCapture

    I just get confused about the I/O redirection of the
    telnet , why can't I get what I want.
    I just don't uinderstand why you would want a kuldgy solution....
    If you really feel you must then look at this: When Runtime.exec() won't: Navigate yourself around pitfalls related to the Runtime.exec() method

  • Access network path from within servlet

    I'm trying to copy some files from a network path from within a servlet. I realize that I cannot use drive letter mappings as they are profile specific. Instead I'm trying to use the unc path. I'm getting the following error when I read the error inputstream from the process:
    String cmd = "XCOPY \\SERVER\SHARE\File.DAT C:\FOLDER /Y"
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(cmd);
    p.waitFor(); //execute process and wait for it to finish
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream());0 File(s) copied
    Invalid drive specification
    Exit code: 4
    It works from the command line, the problem I'm guessing is that Tomcat runs at as service under the SYSTEM account. What permissions should I put on the shared folder to allow this, or is it a path problem?
    Any help would be appreciated.

    Starting the Tomcat service under the Administrator account fixes the problem, is there any reason I shouldn't use the Administrator account for this?

  • Runexec Can't Load Library - Help Please!!!

    I am running the following code on AIX 4.3.3 (just snippets):
    ->
    String line;
    String line2;
    String inCmd = {"/path/command -l " + strInParam};
    Process p = Runtime.getRuntime().exec(inCmd);
    p.waitFor();
    BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream()));
    BufferedReader error = new BufferedReader (new InputStreamReader(p.getErrorStream()));
    while ((line2 = error.readLine()) != null)
    System.out.println(line2);
    error.close();
    while ((line = input.readLine()) != null)
    System.out.println(line);
    input.close();
    <-
    The command I'm executing works fine when it's executed from the command line with the same user, but the java error stream kicks out the following error when I run the code:
    "SERVERERROR] Error from Server: Error Loading Library 'libsybase'"
    I checked the path in java.library.path, and the path to the libraries are there. I can also run other commands and not get this error, such as the DB2 command.
    Any ideas of what the problem could be? Any help would be greatly appreciated!!! Thanks.

    Thanks for your response. I'm not sure what you mean by application server. I was able to put the same command in Perl and it worked fine. Could it be an environment variable or something not being set? I can see all of the paths under java.library.path.
    Thanks for your help.

  • APT Difficulties

    Is it possible to start APT from another Java Program? If so, how? Runtime.getRuntime().exec(bla) doesn't seem to do it.
    import java.io.*;
    * @author laughingman
    public class Test {
        public static void main(String args[]) throws Exception{
            Process p = Runtime.getRuntime().exec("apt");
            InputStream in=p.getInputStream();
            OutputStream out=p.getOutputStream();
            InputStream err=p.getErrorStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(in));
            BufferedWriter write = new BufferedWriter(new OutputStreamWriter(out));
            BufferedReader error = new BufferedReader(new InputStreamReader(err));
            while(read.ready()){
                System.out.println(read.readLine());
            while(error.ready()){
                System.out.println(error.readLine());
    }And yes I realize 'Process p = Runtime.getRuntime().exec("apt");' won't actually make it process anything (it doesn't matter, because I'm just trying to get it to output ANYTHING right now. I'm trying to keep things simple)
    Process p = Runtime.getRuntime().exec("echo bla"); does work, and Process p = Runtime.getRuntime().exec("ECHO bla"); doesn't (which it shouldn't) and it generates an exception (which it should)
    So, again, is it possible to start up APT from Java, and if so, how is it possible?

    A mix of stuff.
    read() Returns false not if the stream is closed, but if it does not have a complete line.
    You don't wait for the proccess to end before quiting
    import java.io.*;
    * @author laughingman
    public class Test2 {
        public static void main(String args[]) throws Exception{
            Process p = Runtime.getRuntime().exec("apt");
            InputStream in=p.getInputStream();
            OutputStream out=p.getOutputStream();
            InputStream err=p.getErrorStream();
            final BufferedReader read = new BufferedReader(new InputStreamReader(in));
            BufferedWriter write = new BufferedWriter(new OutputStreamWriter(out));
            final BufferedReader error = new BufferedReader(new InputStreamReader(err));
         (new Thread() {
              public void run() {
                  String o = null;
                  try {
                   while( (o = read.readLine()) != null ) {
                       System.out.println( "SOUT: " + o );
                  } catch( IOException t ) {
                   System.err.println( t );
             }).start();
         (new Thread() {
              public void run() {
                  String o = null;
                  try {
                   while( (o = error.readLine()) != null ) {
                       System.out.println( "ERROR" + o );
                  } catch( IOException t ) {
                   System.err.println( t );
             }).start();
         System.out.println( p.waitFor() );
           

  • Feedback from runtime.exec(command)

    Hi,
    I hope someone can point out the problem with the following. I have a method that is supposed to execute a shell command. The shell command would look something like the following:
    serctl add 351 password [email protected]
    However when this command is executed in a shell/command line a prompt is shown ("MySql password:")asking for a password. Once the user enters the password, the user is added. My code currently executes the first half of the command but gets stuck on the password prompt. My code stops by the line "before the loop" and never enters the inner loop. So obviously my code isn't working properly to say that if the response is a password prompt, to pass it the password variable.
    Any ideas?
    Many Thanks.
    void addUser(String username, String password, String email, String passwd, HttpServletResponse response) throws IOException {
       String[] command = {"serctl", "add", username, password, email};
       //String[] command = {"pstree"};
       Runtime runtime = Runtime.getRuntime();
       Process process = null;
       response.setContentType(CONTENT_TYPE);
       PrintWriter out = response.getWriter();
       String s = "something";
       try {
         process = runtime.exec(command);
         System.out.println("Process is: " + process);
         System.out.println("Command is: " + command);
         BufferedReader in =
         new BufferedReader(new InputStreamReader(process.getInputStream()));
         BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
         OutputStream stdout = process.getOutputStream();
         System.out.println("before the loop");
         s=in.readLine();
         System.out.println(s);
         System.out.println(s);
         System.out.println(in);
         System.out.println(stdout);
         //while((s=in.readLine())!= null)
         while((s=in.readLine()).equals("MySql password: "))
           //s = in.readLine();
           System.out.println(in.readLine());
           System.out.println(s);
           out.println(s);
           if (s.equals("MySql password:  ")) {
             System.out.println("Must be equal to MySql password;");
             //stdout.write(passwd.getBytes());
             //stdout.write(adminpassword);
             //stdout.flush();
             //break;
        System.out.println("after the loop");
         System.out.println("Here is the standard error of the command(if any):\n");
         while ((s = error.readLine()) != null){
           System.out.println(s);
         stdout.close();
         in.close();
         error.close();
         out.println(in);
         out.println("<html>");
         out.println("<body bgcolor=\"#FFFCCC\">");
         out.println("You have successfully added a new user.<br><br>");
         out.println("User " + username + " has been created ");
         out.println("</body></html>");
        catch (Exception e) {
              System.out.println("Uh oh! Error adding new user.");
              e.printStackTrace();
    }

    Just a random observation:
    Sometimes programs that prompt for passwords do it in a way that is impossible to redirect (or at least requires special trickery, such as creating a pseudo-TTY). E.g. in Unix this involves opening /dev/tty and using that instead of stdout & stdin. This is done to make sure there really is a person who knows the password sitting there in front of the teletype.
    I don't know if the "serctl" program does that. If stdout&stdin redirection does not appear to work then it is a possibility.
    A quick googling for "serctl" reveals:
    Commands labeled with (*) will prompt for a MySQL password.
    If the variable PW is set, the password will not be prompted.
    which might or might not be an easier way to deal with this particular program. If it indeed is the same "serctl" program.

  • Error response: "java.io.BufferedReader@69d02b"

    Hi,
    I am trying the following code and encountered the error mentioned in the subject.This piece of code read a file online and prints its content into a web page. Can any one explain me what is causing it? I think it could be because my buffer is over loaded. if it is so then can some one show me how to crease the buffer size?
    or any help will be appreciated.
    Thank you.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package cgSkewPackage;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.net.MalformedURLException;
    import java.net.URL;
    * @author Owner
    public class CgSkew extends HttpServlet {
        public String getcgskew;
        public String url1;
        public String url2;
        public String getURL;
        public String inputLine;
        public BufferedReader in;
        * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
        * @param request servlet request
        * @param response servlet response
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            //Getting the user input.
            getcgskew = request.getParameter("cgskew");
            // Check for null value.
            if((getcgskew == null ) || (getcgskew.trim().equals(""))){
                response.sendRedirect("http://www.genomecalculator.org/cg-skew/cg-skew.html");
                else{
                    getcgskew = getcgskew.trim();
                    url1 = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=genome&id=NC_";
                    url2 = "&rettype=gb";
                    getURL= url1+getcgskew+url2;
                    // Opening buffer reader
                 try{  
                    URL geneBankLink = new URL(getURL);
                    in = new BufferedReader( new InputStreamReader
                            (geneBankLink.openStream()));
                 catch(MalformedURLException e) {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet CgSkew</title>"); 
                out.println("</head>");
                out.println("<body>");
                // Printing out here the file content.
                out.println(in);
                out.println("</body>");
                out.println("</html>");
            } finally {
                out.close();
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        * Handles the HTTP <code>GET</code> method.
        * @param request servlet request
        * @param response servlet response
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        * Handles the HTTP <code>POST</code> method.
        * @param request servlet request
        * @param response servlet response
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
    }

    I see. This is indeed not the way to download a file.
    You should not print it as a String to the outputStream, but you should be rather streaming the whole inputStream contents to the outputStream inside a loop. Learn the Java IO basics: [http://google.com/search?q=java+io+tutorial+site:sun.com].
    If you rather want to download it as an independent file instead of copying its content inside a HTML response, then rather write a servlet which does the task independently. Here is an example of such a servlet: [http://balusc.blogspot.com/2007/07/fileservlet.html].

  • BufferedReader == reader.mark()  ERROR

    This is a basice i/o program. It reads data, stores it in an array and then writes a file based on a filtering system.
    The code:
    import java.io.*;
    import java.util.StringTokenizer;
    import java.util.NoSuchElementException;
    import java.util.ArrayList;
    import java.lang.String;
    import java.lang.IndexOutOfBoundsException;
    public class bigbook{
         public bigbook()
              Day = 0;
              Open = 0;
              High = 0;
              Low = 0;
              Close = 0;
              Vol = 0;
              Trade = 0;
              Shares = 0;
              TradingDay = 0;
              PL = 0;
              ExitDay = 0;     
         public void enterDay(double date)
              Day = date;
         public void enterOpen(double open)
              Open = open;
         public void enterHigh(double high)
              High = high;
         public void enterLow(double low)
              Low = low;
         public void enterClose(double close)
              Close = close;
         public void enterTradingDay(int day)
              TradingDay = day;
         public void enterPL(double pandl)
              PL = pandl;
         public void enterVol(double vol)
              Vol = vol;
         public void enterExit(double dayfive)
              ExitDay = dayfive;
         public void enterExitPrice(double exitspot)
              ExitPrice = exitspot;
         public double getExitPrice()
              return ExitPrice;
         public double getExit()
              return ExitDay;
         public double getHigh()
              return High;
         public double getPL()
              return PL;
         public double getClose()
              return Close;
         public double getShares()
              return Shares;
         public double getDate()
              return Day;
         public double getPosition()
              return Trade;
         public int getTradingDay()
              return TradingDay;
         public double getVolume()
              return Vol;
         public void numShares()
              Shares = 100000/Close;
         public void goLong()
              Trade = 1;
         public void sellShort()
              Trade = -1;
         private double Day;
         private double Open;
         private double High;
         private double Low;
         private double Close;
         private double Vol;
         private double Trade;
         private double Shares;
         private int TradingDay;
         private double PL;
         private double ExitDay;
         private double ExitPrice;
         private static void ReadFile(BufferedReader reader) throws IOException {
              String nextLine = reader.readLine(); // read first line from br
              int runCount = 0;
              int closeCount = 0;
              ArrayList theDayList = new ArrayList();
              ArrayList theResultsList = new ArrayList();
              StringTokenizer td;
              do
                   while ( runCount<2500 && nextLine != null) {
                        int roc = 10;
                        // roc == run overlap count
                        runCount++;
                        bigbook Zbigbook = new bigbook();
                        td = new StringTokenizer(nextLine, ",");
                        while (td.hasMoreTokens()){
                        Zbigbook.enterDay(Double.parseDouble((String)td.nextToken()));
                        Zbigbook.enterOpen(Double.parseDouble((String)td.nextToken()));
                        Zbigbook.enterHigh(Double.parseDouble((String)td.nextToken()));
                        Zbigbook.enterLow(Double.parseDouble((String)td.nextToken()));
                        td.nextToken();
                        Zbigbook.enterVol(Double.parseDouble((String)td.nextToken()));
                        Zbigbook.enterClose(Double.parseDouble((String)td.nextToken()));
                        Zbigbook.enterTradingDay(closeCount);
                        theDayList.add(Zbigbook);
                        nextLine = reader.readLine();
                        if(runCount == 2000)
                                  reader.mark(roc);
                        if(runCount == 2500 || nextLine == null)
                                  reader.reset();
                                  closeCount += runCount;
                                  ArrayList theInterimList = (ArrayList)Test(theDayList);
                                  for (int i=0; i<theInterimList.size(); i++) {
                                       try{
                                            bigbook Xbigbook = (bigbook)theInterimList.get(i);
                                            theResultsList.add(Xbigbook);
                                       catch (IndexOutOfBoundsException e){
                                            break;
                                  if(nextLine == null){
                                       PrintWriter pw;
                                       System.out.print("Send output where? ");
                                       String dest = (new BufferedReader (new InputStreamReader(System.in))).readLine();
                                       if (dest.equals("System.out"))
                                            pw = new PrintWriter(System.out);
                                       else
                                            pw = new PrintWriter(new FileWriter(dest));
                                       pw.println("Runs " + closeCount + " closes.");
                                       for (int i=0; i<theResultsList.size(); i++) {
                                            try{
                                            bigbook Ybigbook = (bigbook)theResultsList.get(i);
                                            pw.println(Ybigbook.getDate()+ "," + Ybigbook.getVolume()+ ","
                                            +Ybigbook.getClose());
                                            catch (IndexOutOfBoundsException e){
                                                 break;
                                       pw.close();     
                                  runCount = 0;
                                  theDayList = new ArrayList();
              while(nextLine != null);
         private static ArrayList Test(ArrayList list) throws IOException {
              ArrayList theRelayedList  = list;
              ArrayList theVolList  = new ArrayList();
              for ( int i = 0; i<theRelayedList.size(); i++)
                        try{
                             bigbook Abigbook = (bigbook)theRelayedList.get(i);
                             double volume = Abigbook.getVolume();
                             if(volume > 1000)     
                                       theVolList.add(Abigbook);
                        catch (IndexOutOfBoundsException e){
                             break;
              return theVolList;
         public static void main(String[] args) {
              String filename;
              // Prompt user for file name
              System.out.print("Enter file name: " );          
              // Read user's input from System.in
              InputStreamReader isr = new InputStreamReader(System.in);          
              BufferedReader br = new BufferedReader(isr);
              FileReader fr;
              // Iteratively prompt user until file found
              try {
                   while (true) {
                        filename = br.readLine();
                        try {
                             fr = new FileReader(filename);
                             break;
                        catch (FileNotFoundException e) {
                             System.out.print("Re-enter file name: ");
                   ReadFile(new BufferedReader (fr));
              catch (IOException e) {
                   System.out.println(e);          
                   return;
    }The problem is that the mark() method is becoming invalidated.
    This is the first time I've tried to implement the mark method. I know that the reset() method is supposed to start the reader back at the place where I called mark().
    Does it have something to do with the if statement where the mark() call is?

    private static void ReadFile(BufferedReader reader) throws IOException {
              String nextLine = reader.readLine(); // read first line from br
              int runCount = 0;
              int closeCount = 0;
              ArrayList theDayList = new ArrayList();
              ArrayList theResultsList = new ArrayList();
              StringTokenizer td;
              do
                   while ( runCount<2500 && nextLine != null) {
                        int roc = 1000;
                        // roc == run overlap count
                        runCount++;
                        bigbook Zbigbook = new bigbook();
                        td = new StringTokenizer(nextLine, ",");
                        while (td.hasMoreTokens()){
                        Zbigbook.enterDay(Double.parseDouble((String)td.nextToken()));
                        Zbigbook.enterOpen(Double.parseDouble((String)td.nextToken()));
                        Zbigbook.enterHigh(Double.parseDouble((String)td.nextToken()));
                        Zbigbook.enterLow(Double.parseDouble((String)td.nextToken()));
                        td.nextToken();
                        Zbigbook.enterVol(Double.parseDouble((String)td.nextToken()));
                        Zbigbook.enterClose(Double.parseDouble((String)td.nextToken()));
                        Zbigbook.enterTradingDay(closeCount);
                        theDayList.add(Zbigbook);
                        nextLine = reader.readLine();
                        if(runCount == 2000)
                                  reader.mark(roc);
                        if(runCount == 2500 || nextLine == null)
                                  reader.reset();This is where the problem occurs.
    In the previous post the readAheadLimit was set at 10, now I have it at 1000.
    All that's happening between the mark() and reset() really is tokenizing each line and storing it to the the DayList ArrayList.
    The way I understand it is that - each time the reader reads a line, that counts as 1 .................................
    OH! this is defined it terms of Characters, not lines from the reader!
    This may make a difference.

  • File not found error

    I get the following error, but don't know why it can't find the file. Is there anything in this script that would call "\" instead of "/"? Is there any line of code that will switch a wayward "\" back?
    01-09-24 09:37:02 - path="" :jsp: init
    2001-09-24 09:43:42 - path="" :LoginServlet: init
    2001-09-24 09:44:15 - path="" :CourseServlet: init
    2001-09-24 09:46:48 - path="" :LessonServlet: init
    2001-09-24 09:46:54 - path="" :Error: /usr/local/apache/sites/tesco.spinweb.net/htdocs/cmi/courses\Food Service/Intro/AU00.html (No such file or directory)
    The script is below. Thanks for any help anyone can provide me.
    import cmi.xml.AU;
    import cmi.xml.Block;
    import cmi.xml.CourseReader;
    import cmi.xml.CSFElement;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Enumeration;
    import java.util.Hashtable;
    import java.util.Vector;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import javax.servlet.http.HttpServlet;
    import org.jdom.JDOMException;
    public class LessonServlet extends HttpServlet
    public void init (ServletConfig config) throws ServletException
    super.init (config);
    try {
                   Class.forName (GlobalData.DatabaseDriverName);
                   _jdbcConnection = DriverManager.getConnection (GlobalData.DatabaseName, "tesco", "scorm");
    _jdbcConnection.setAutoCommit (true);
    //should I do this?
    //_jdbcConnection.setAutoCommit (false);
    //load serialized course data
    loadCourseData();
              catch (Exception xcp) {
                   xcp.printStackTrace();     
                   getServletContext().log("Error: " + xcp.getMessage());     
    public void doGet( HttpServletRequest request,
                             HttpServletResponse response)
              throws ServletException, IOException
    boolean normalMode = true;
    try {
    HttpSession session = request.getSession (true);
    //can I load the session given the id??
    //System.out.println ("Lesson.valid session " + session.getId() + ": " + request.isRequestedSessionIdValid());
    response.setContentType ("text/html");
    JDBCHelper dbHelper = new JDBCHelper (_jdbcConnection);
    //get student ID
    Integer studentID = (Integer) session.getAttribute ("studentID");
    //get course ID
    Integer courseID = (Integer) session.getAttribute ("courseID");
    //get lesson ID
    String lessonID = request.getParameter ("lessonID");
    if (lessonID == null) {
    lessonID = (String) session.getAttribute ("lessonID");
    if (studentID == null || courseID == null || lessonID == null) {
    //reset session data by re-logging the user
    sendProfileError (response.getOutputStream());
    return;
    //store lesson ID in session
    session.setAttribute ("lessonID", lessonID);
    String auID = request.getParameter ("auID");
    String mode = request.getParameter ("mode");
    if (mode != null) {
    session.setAttribute ("mode", mode);
    else {
    mode = (String) session.getAttribute ("mode");
    if (mode.equalsIgnoreCase ("review")) {
    normalMode = false;
    else {
    normalMode = true;
    //synchronize access to course hash table
    synchronized (_courseHash)
    //make sure _courseHash is in tact
    if (_courseHash == null) {
    //try reloading it....
    loadCourseData();
    if (_courseHash == null) {
    //error
    response.getOutputStream().close();
    throw new IOException ("Corrupt course data");
    if (! _courseHash.containsKey (courseID.toString())) {
    //try reloading it....
    loadCourseData();
    if (! _courseHash.containsKey (courseID.toString())) {
    //error
    response.getOutputStream().close();
    throw new IOException ("Corrupt course data (course not found)");
    if (auID == null) {
    //show course menu
    Hashtable hash = (Hashtable) _courseHash.get (courseID.toString());
    sendAvailableAUs (hash, studentID.intValue(), courseID.intValue(), lessonID, response.getOutputStream(), response, dbHelper);
    return;
    //if AU has not been attempted, initialize it
    Integer auDataID = new Integer (getAUDataID (studentID.intValue(), courseID.intValue(), lessonID, auID, dbHelper));
    //if (getAUDataID (studentID.intValue(), courseID.intValue(), lessonID, auID, dbHelper) == -1) {
    if (auDataID.intValue() == -1) {
    int newID = initializeAUData (studentID.intValue(), courseID.intValue(), lessonID, auID, dbHelper);
    dbHelper.addAUToPath (studentID.intValue(), courseID.intValue(), lessonID, auID);
    auDataID = new Integer (newID);
    session.setAttribute ("AUID", auID);
    session.setAttribute ("AUDataID", auDataID);
    sendAU (studentID.intValue(), courseID.intValue(), lessonID, auID, auDataID.intValue(), normalMode, response.getOutputStream(), dbHelper);
    //to do: detailed messages should be sent to the client depending on which
    // exception was thrown. Don't have one try/catch....have one for each situation
    catch (Exception e) {
    e.printStackTrace();
                   getServletContext().log("Error: " + e.getMessage());
    public void destroy()
              try {
                   if (_jdbcConnection != null) {
                        _jdbcConnection.close();
              catch (Exception ignored) {}
    private int initializeAUData (int studentID, int courseID, String lessonID, String auID, JDBCHelper dbHelper)
    String sqlQuery = null;
    ResultSet results = null;
    try {
    //get student's name
    sqlQuery = "SELECT Full_Name" +
    " FROM " + GlobalData.StudentTable +
    " WHERE Student_ID = " + studentID;
    results = dbHelper.doQuery (sqlQuery);
    if (! results.next()) {
    //error
    return -1;
    String studentName = results.getString (1);
    results.close();
    //the lock prevents CMIServlet from reading AU_ID before it's committed
    //sqlQuery = "LOCK TABLES " + GlobalData.AUDataTable + " WRITE;";
    //System.out.println (sqlQuery);
    //dbHelper.executeUpdate (sqlQuery);
    sqlQuery = "Insert Into " + GlobalData.AUDataTable +
    "(Course_ID, Lesson_ID, AU_ID, student_id, student_name, lesson_location, credit," +
    " lesson_status, entry, exit, score_raw, score_max, score_min, total_time," +
    " session_time, lesson_mode, suspend_data, launch_data, Evaluation_ID, Objective_ID)" +
    " Values (" + courseID + ", '" + lessonID + "', '" + auID + "', " + studentID + ", '" + studentName + "'," +
    " 'NA', 'credit'," + " 'not attempted', 'ab-initio', " + "'NA', " + 0 + ", " + 0 + ", " + 0 +
    ", '00:00:00.0', '00:00:00.0', " + " 'normal'" + ", 'NA', " + "'NA', " + 0 + ", " + 0 + ");";
    dbHelper.executeUpdate (sqlQuery);
    return getAUDataID (studentID, courseID, lessonID,auID, dbHelper);
    //sqlQuery = "UNLOCK TABLES;";
    //System.out.println (sqlQuery);
    //dbHelper.executeUpdate (sqlQuery);
    catch (Exception e) {
    e.printStackTrace();
                   getServletContext().log("Error: " + e.getMessage());
    return -1;
    private int getAUDataID (int studentID, int courseID, String lessonID, String auID, JDBCHelper dbHelper)
    throws SQLException
    String sqlQuery = "SELECT AUData_ID, lesson_status, lesson_mode, exit" +
                                  " FROM " + GlobalData.AUDataTable +
                                  " WHERE student_id = " + studentID +
                                  " AND Course_ID = " + courseID +
    " AND Lesson_ID = " + "'" + lessonID + "'" +
    " AND AU_ID = '" + auID + "';";
    ResultSet results = dbHelper.doQuery (sqlQuery);
    if (results.next()) {
    return results.getInt ("AUData_ID");
    return -1;
    private void sendAU (int studentID, int courseID, String lessonID, String auID, int auDataID, boolean normalMode, ServletOutputStream htmlOut, JDBCHelper dbHelper)
    throws IOException, ClassNotFoundException
    Hashtable hash = null;
    synchronized (_courseHash)
    hash = (Hashtable) _courseHash.get (String.valueOf (courseID));       
    if (hash == null) {
    loadCourseData();
    hash = (Hashtable) _courseHash.get (String.valueOf (courseID));
    if (hash == null) {
    throw new IOException ("Corrupt course data (course not found)");
    AU au = (AU) hash.get (auID);
    try {
    if (! normalMode) {
    dbHelper.setReviewMode (auDataID);
    String courseFileName = getFileName (String.valueOf (courseID), dbHelper);
    File file = new File (courseFileName);
    //create absolute path to file so we can resolve relative URLs
    String newFileName = file.getParent() + "\\" + au.getLaunchParams();
                   BufferedReader buf = new BufferedReader (new FileReader (newFileName));
    PrintWriter htmlWriter = new PrintWriter (htmlOut);
                   String temp;
    htmlWriter.write (getAUHtml (au.getLaunchParams()));
    htmlWriter.flush();
    htmlWriter.close();
    catch (Exception e) {
    e.printStackTrace();
                   getServletContext().log("Error: " + e.getMessage());
    private String getAUHtml (String path){
    path = path.replace ('\\','/');
    String response;
    response = "<html>\n" +
                        "<head>\n" +
    "</head>\n" +
    "<body>\n" +
    "<script language=\"JavaScript\">\n" +
    "document.location = \"/cmi/courses/" + path + "\"\n" +
    //"win = window.open ('','displayWindow','menubar=yes,scrollbars=yes,status=yes,width=300,height=300');\n" +
    //"window.onload = \"win.close();\"" +
    "</script>\n" +
    "</body>\n" +
    "</html>\n";
    return response;
    private void sendAvailableAUs (Hashtable hash, int studentID, int courseID, String lessonID, ServletOutputStream out, HttpServletResponse response, JDBCHelper dbHelper)
    StringBuffer buf = new StringBuffer (200);
    Block block = (Block) hash.get (lessonID);
    AU au = null;
    try {
    Vector completedAUs = dbHelper.getCompletedAUs (studentID, courseID, lessonID);
    buf.append ("<html>\n" +
                        "<head>\n" +
    "<title>" + block.getTitle() + " units</title>\n" +
    "<script language=\"JavaScript\">\n" +
    "function go() {\n" +
    " var form = document.goForm;\n" +
    " var index = form.gotoSelect.selectedIndex;\n" +
    " if (index == 0) {\n" +
    " document.location = \"/servlet/CourseServlet?courseID=" + courseID + "\";\n" +
    " }\n" +
    " else if (index == 1) {\n" +
    " top.restart();\n" +
    " }\n" +
    "}\n" +
    "</script>\n" +
    "</head>\n" +
    "<body background=\"/cmi/images/marble.jpg\">\n" +
    "<center><h1><b><u>" + block.getTitle() + "</u></b></h1></center>\n" +
    "<p></p>\n<p></p>\n" +
    "<b>" + block.getTitle() + " contains the following units: </b>\n" +
    "<dl>\n");
    Enumeration enum = block.getChildren();
    while (enum.hasMoreElements()) {
    String temp = (String) enum.nextElement();
    CSFElement element = (CSFElement) hash.get (temp);
    if (element.getType().equals ("au")) {
    au = (AU) element;
    if (completedAUs.contains (au.getID())) {
    buf.append ("<dt><p><img src=\"/cmi/images/node2.gif\"><a href=\"/servlet/LessonServlet?lessonID=" + block.getID() + "&auID=" + au.getID() + "&mode=review\">" + au.getTitle() + " (<i>review</i>) </a></p></dt>\n");
    else {
    buf.append ("<dt><p><img src=\"/cmi/images/node.gif\"><a href=\"" + response.encodeURL ("/servlet/LessonServlet?lessonID=" + block.getID() + "&auID=" + au.getID() + "&mode=normal") + "\">" + au.getTitle() + "</a></p></dt>\n");
    else if (element.getType().equals ("block")) {
    buf.append ("<dt><p><img src=\"/cmi/images/folder.gif\"><a href=\"" + response.encodeURL ("/servlet/LessonServlet?lessonID=" + element.getID() + "&mode=normal") + "\">" + element.getTitle() + "</a></p></dt>\n");
    buf.append ("</dl>\n" +
    "<br><br>\n" +
    "<form name=\"goForm\">\n" +
    "<select name=\"gotoSelect\">\n" +
    " <option value=\"lesson\">Lesson Menu</option>\n" +
    " <option value=\"exit\">Exit LMS</option>\n" +
    "</select>\n" +
    "<input type=\"button\" value=\"Go\" onClick=\"go()\">\n" +
    "</form>\n" +
    "</body>\n" +
    "</html>");
    PrintWriter writer = new PrintWriter (out);
    writer.write (buf.toString());
    writer.flush();
    writer.close();
    catch (Exception e) {
    e.printStackTrace();
                   getServletContext().log("Error: " + e.getMessage());
    private String getFileName (String courseID, JDBCHelper dbHelper)
    throws ClassNotFoundException, SQLException
              ResultSet results = null;
              String fileName = null;
    String sqlQuery = "SELECT CourseFile" +
                                  " FROM Course" +
                                  " WHERE Course_ID = " + Integer.parseInt (courseID) + ";";
    results = dbHelper.doQuery (sqlQuery);
              if (results.next()) {
                   fileName = results.getString (1);
              else {
    //need to do more than this :)
                   System.out.println("crap");
    results.close();
    return fileName;
    private void loadCourseData()
    throws IOException, ClassNotFoundException
    //load serialized course data
    File file = new File (GlobalData.DataFileName);
    if (! file.exists()) {
    //error
    throw new FileNotFoundException (GlobalData.DataFileName + " not found.");
    FileInputStream fis = new FileInputStream (GlobalData.DataFileName);
    ObjectInputStream ois = new ObjectInputStream (fis);
    _courseHash = (Hashtable) ois.readObject();
    ois.close();
    private void sendProfileError (ServletOutputStream out)
    String html = "<html>\n" +
    "<body>\n" +
    "<p>An error has occurred with your profile. Please " +
    "<a href=\"\" onClick=\"top.restart(); return true\">login again</a>" +
    "</body>\n" +
    "</html>\n";
    PrintWriter writer = new PrintWriter (out);
    writer.write (html);
    writer.flush();
    writer.close();
    private Connection _jdbcConnection;
    private Hashtable _courseHash;

    I know that is where my error is, but why and where is
    the script calling it up way?You wrote it right? check out the sendAU() method, there is line
    String newFileName = file.getParent() + "\\" + au.getLaunchParams();

  • Print error report

    Hello!
    When I compile the java pgm i have an error report, which is more then one page.
    Is there are a way to print it out.
    Thanks

    javac -Xstdout
    Send error messages to stdout instead of stderr. This makes them easier to redirect to a file in Windows. For some reason this is no longer supported under JDK 1.3, (a result of intercorporate sniping at Microsoft?) It is supported with oldjavac.exe.
    You can write your own java solution:
    import java.io.*;
    public class Errout
    {  public static void main(String[] args) throws IOException
    {  Process p = Runtime.getRuntime().exec(args);
    BufferedReader err
    = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    String line;
    while ((line = err.readLine()) != null)
    System.out.println(line);
    Then execute the following command:
    java Errout javac MyProg.java | more
    java Errout javac MyProg.java > errors.txt
    if you want to log all errors, then change the
    System.out.println(line);
    BufferedWriter bw = new BufferedWriter( new FileWriter("log.err") );
    bw.write( line );
    bw.newLine();
    and later on, bw.flush(); and bw.close();
    and catch exceptions.
    good luck!

  • Error in creating a process using runtime class - please help

    Hi,
    I am experimenting with the following piece of code. I tried to run it in one windows machine and it works fine. But i tried to run it in a different windows machine i get error in creating a process. The error is attached below the code. I don't understand why i couldn't create a process with the 'exec' command in the second machine. Can anyone please help?
    CODE:
    import java.io.*;
    class test{
    public static void main(String[] args){
    try{
    Runtime r = Runtime.getRuntime();
         Process p = null;
         p= r.exec("dir");
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
         System.out.println(br.readLine());
    catch(Exception e){e.printStackTrace();}
    ERROR (when run in the dos prompt):
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:63)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:550)
    at java.lang.Runtime.exec(Runtime.java:416)
    at java.lang.Runtime.exec(Runtime.java:358)
    at java.lang.Runtime.exec(Runtime.java:322)
    at test.main(test.java:16)
    thanks,
    Divya

    As much as I understand from the readings in the forums, Runtime.exec can only run commands that are in files, not native commands.
    Hmm how do I explain that again?
    Here:
    Assuming a command is an executable program
    Under the Windows operating system, many new programmers stumble upon Runtime.exec() when trying to use it for nonexecutable commands like dir and copy. Subsequently, they run into Runtime.exec()'s third pitfall. Listing 4.4 demonstrates exactly that:
    Listing 4.4 BadExecWinDir.java
    import java.util.*;
    import java.io.*;
    public class BadExecWinDir
    public static void main(String args[])
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("dir");
    InputStream stdin = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdin);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    System.out.println("<OUTPUT>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    System.out.println("</OUTPUT>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
    A run of BadExecWinDir produces:
    E:\classes\com\javaworld\jpitfalls\article2>java BadExecWinDir
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at BadExecWinDir.main(BadExecWinDir.java:12)
    As stated earlier, the error value of 2 means "file not found," which, in this case, means that the executable named dir.exe could not be found. That's because the directory command is part of the Windows command interpreter and not a separate executable. To run the Windows command interpreter, execute either command.com or cmd.exe, depending on the Windows operating system you use. Listing 4.5 runs a copy of the Windows command interpreter and then executes the user-supplied command (e.g., dir).
    Taken from:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Error while executing a process - it hangs!

    Hi there, please help me with this problem:
    I'm executing a CMD file with the next code and it hangs
    File file = new file("E:\\NDM_TEST\\UPLOAD_ENC\\CA210105.001.zip")
    Vector response = null;
    Log.debugLog("File to transport as a response " + getFileAbsolutePath());
    if (NDM.executeCMD(file.getFileAbsolutePath(), file.getFileName()) == 0) {
    public static int executeCMD(String fileAbsolutePath, String fileName) {
      int exitValue = 1;
      String chainn = "";
      try {
        Log.debugLog("starting CMD execution");
        String arguments[] = new String[1];
        arguments[0] = "\"" + getNDM_BATCH() + "\" " + fileAbsolutePath + " " + fileName;
        exitValue = WindowsExec.execute(arguments);
      } catch (Exception e) {
        Log.log("[ERROR] NDM.ejecutaBatch ==> " + e);
      } finally {
        return exitValue;
    public class WindowsExec {
      public static int execute(String args[]) {
        int exitVal = 1;
        if(args.length < 1) {
          Log.log("USAGE; java WindowsExec <cmd>");
          System.exit(1);
        try {
          String osName = System.getProperty("os.name");
          String[] cmd = new String[3];
          Runtime rt = Runtime.getRuntime();
          String toExecute = cmd[0] + " " + cmd[1] + " " + cmd[2];
          Log.debugLog(toExecute);
          Process proc = rt.exec(toExecute);
          Streammer errorStreammer = new Streammer(proc.getErrorStream(), "ERROR");
          Streammer outPutStreammer = new Streammer(proc.getInputStream(), "OUTPUT");
          errorStreammer.start();
          outPutStreammer.start();
          exitVal = proc.waitFor();
        } catch(Throwable t) {
          t.printStackTrace();
        } finally {
          return exitVal;
    public class Streammer extends Thread {
      InputStream is;
      String type;
      Streammer(InputStream is, String type) {
        this.is = is;
        this.type = type;
      public void run() {
        try {
          InputStreamReader isr = new InputStreamReader(is);
          BufferedReader br = new BufferedReader(isr);
          String line = null;
          while ((line = br.readLine()) != null) {
            Log.log(type + " > " + line);
        } catch (Exception ioe) {
          ioe.printStackTrace();
    }The output of the line Log.debugLog(toExecute); is:
    cmd.exe /C "E:\NDM_TEST\PROCESS\TX_TEST.CMD" E:\NDM_TEST\UPLOAD_ENC\CA210105.001.zip CA210105.001.zip
    If i run this output from a command prompt it runs ok, but when invoked from my java program it hangs and never ends

    You are right, at the moment I paste my code, I delete three important lines, here is the right code:
    File file = new file("E:\\NDM_TEST\\UPLOAD_ENC\\CA210105.001.zip")
    Vector response = null;
    Log.debugLog("File to transport as a response " + getFileAbsolutePath());
    if (NDM.executeCMD(file.getFileAbsolutePath(), file.getFileName()) == 0) {
    public static int executeCMD(String fileAbsolutePath, String fileName) {
      int exitValue = 1;
      String chainn = "";
      try {
        Log.debugLog("starting CMD execution");
        String arguments[] = new String[1];
        arguments[0] = "\"" + getNDM_BATCH() + "\" " + fileAbsolutePath + " " + fileName;
        exitValue = WindowsExec.execute(arguments);
      } catch (Exception e) {
        Log.log("[ERROR] NDM.ejecutaBatch ==> " + e);
      } finally {
        return exitValue;
    public class WindowsExec {
      public static int execute(String args[]) {
        int exitVal = 1;
        if(args.length < 1) {
          Log.log("USAGE; java WindowsExec <cmd>");
          System.exit(1);
        try {
          Runtime rt = Runtime.getRuntime();
          String[] cmd = new String[3];
          cmd[0] = "cmd.exe";
          cmd[1] = "/C";
          cmd[2] = args[0];
          String toExecute = cmd[0] + " " + cmd[1] + " " + cmd[2];
          Log.debugLog(toExecute);
          Process proc = rt.exec(toExecute);
          Streammer errorStreammer = new Streammer(proc.getErrorStream(), "ERROR");
          Streammer outPutStreammer = new Streammer(proc.getInputStream(), "OUTPUT");
          errorStreammer.start();
          outPutStreammer.start();
          exitVal = proc.waitFor();
        } catch(Throwable t) {
          t.printStackTrace();
        } finally {
          return exitVal;
    public class Streammer extends Thread {
      InputStream is;
      String type;
      Streammer(InputStream is, String type) {
        this.is = is;
        this.type = type;
      public void run() {
        try {
          InputStreamReader isr = new InputStreamReader(is);
          BufferedReader br = new BufferedReader(isr);
          String line = null;
          while ((line = br.readLine()) != null) {
            Log.log(type + " > " + line);
        } catch (Exception ioe) {
          ioe.printStackTrace();
    }I hope you can help me know... thanks!.

  • Getting Error while decrypt a file using Blowfish algorithm

    I am using blowfish algorithm for encrypt and decrypt my file. this is my code for encrypting decrypting .
    while i am running program i am getting an Exception
    Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA12275)
    at Blowfishexe.main(Blowfishexe.java:65)
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.io.*;
    import org.bouncycastle.crypto.CryptoException;
    import org.bouncycastle.crypto.KeyGenerationParameters;
    import org.bouncycastle.crypto.engines.DESedeEngine;
    import org.bouncycastle.crypto.generators.DESedeKeyGenerator;
    import org.bouncycastle.crypto.modes.CBCBlockCipher;
    import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
    import org.bouncycastle.crypto.params.DESedeParameters;
    import org.bouncycastle.crypto.params.KeyParameter;
    import org.bouncycastle.util.encoders.Hex;
    public class Blowfishexe {
    public static void main(String[] args) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
              kgen.init(128);
              String keyfile="C:\\Encryption\\BlowfishKey.dat";
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
              System.out.println("key"+raw);
                   byte[] keyBytes = skey.getEncoded();
                   byte[] keyhex = Hex.encode(keyBytes);
                   BufferedOutputStream keystream =
    new BufferedOutputStream(new FileOutputStream(keyfile));
                        keystream.write(keyhex, 0, keyhex.length);
    keystream.flush();
    keystream.close();
    Cipher cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
              System.out.println("secretKey"+skeySpec);
    FileOutputStream fos=new FileOutputStream("C:\\Encryption\\credit11.txt");
              BufferedReader br=new BufferedReader(new FileReader("C:\\Encryption\\credit.txt"));
              String text=null;
              byte[] plainText=null;
              byte[] cipherText=null;
              while((text=br.readLine())!=null)
              System.out.println(text);
              plainText = text.getBytes();
              cipherText = cipher.doFinal(plainText);
              fos.write(cipherText);
              br.close();
              fos.close();
              cipher.init(Cipher.DECRYPT_MODE, skeySpec);
              FileOutputStream fos1=new FileOutputStream("C:\\Encryption\\BlowfishOutput.txt");
              BufferedReader br1=new BufferedReader(new FileReader("C:\\Encryption\\credit11.txt"));
              String text1=null;
              /*while((text1=br1.readLine())!=null)
                   System.out.println("text is"+text1);
                   plainText=text1.getBytes("UTF8");
                   cipherText=cipher.doFinal(plainText);
                   fos1.write(cipherText);
              br1.close();
              fos1.close();
    //byte[] encrypted = cipher.doFinal("This is just an example".getBytes());
              //System.out.println("encrypted value"+encrypted);*/
    Any one pls tell me how to slove my problem
    thanks in advance

    hi
    i got the solution. its working now
    but blowfish key ranges from 56 to448
    while i am writing the code as
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(448);
    this code is generating the key upto 448 bits
    but coming to encoding or decode section key length is not accepting
    cipher.init(Cipher.ENCRYPT_MODE, key);
    Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at Blowfish1.main(Blowfish1.java:46)
    i am getting this error
    what is the solution for this type of exception.
    thank you

  • Error trying to create https connection from Web Dynpro

    Hi experts!!
    I am trying to create a WD view with an actionButton and a form template, when the user fills the data in the form and presses the button, i want to create an Https connect and post some parameters to the URL.
    HttpsURLConnection cannot be resolved,
    com.sun.net.ssl.internal.ssl.Provider() does't not exist in the package com.sun.net.ssl.internal.ssl.Provider()
    do i need to add any jars?? I've already added the jsse.jar
    The code i use is the following.
    private void sendHttp(){
          String response = "";
          HttpsURLConnection connection = null;
          try {
                      System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
                      java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                      URL url = new URL(<your_url>);
                      connection = (HttpsURLConnection) url.openConnection();
                      connection.setDoInput(true);
                      connection.setDoOutput(true);
                      connection.setAllowUserInteraction(true);
                      connection.setUseCaches(false);
                }     catch(Exception e) {
                      response = response +  "Error in getting connection: " ;
                      response = response +  e ;
                if (connection != null){
                      try {
                            connection.setRequestMethod("POST");
                            connection.setFollowRedirects(true);
                            //build all the parameters into 1 string
                            String query = "parameter1name=" + URLEncoder.encode(parameter1value);
                                  query += "&";
                                  query += "parameter2name=" + URLEncoder.encode(parameter2value);
                            connection.setRequestProperty("Content-length",String.valueOf (query.length()));
                            connection.setRequestProperty("Content-Type","application/x-www- form-urlencoded");
                            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)");
                            // open up the output stream of the connection
                            DataOutputStream output = new DataOutputStream( connection.getOutputStream() );
                            // write out the data
                            int queryLength = query.length();
                            output.writeBytes( query );
                            output.close();
                            //if responsecode <> 200 you should stop: should always be 200
                            String responsecode = connection.getResponseCode();
                            if (responsecode.equalsIgnoreCase("200")){
                                  String inputLine;
                                  StringBuffer input = new StringBuffer();
                                  BufferedReader in =     new BufferedReader(     new InputStreamReader(connection.getInputStream()));
                                                                                    //Get site response
                                  while ((inputLine = in.readLine()) != null) {
                                        input.append(inputLine);
                                  in.close();
                                  response = response + input.toString();
                      }     catch(Exception e) {
                          response = response +  "Error in using connection: " ;
                          response = response +  e ;
              wdContext.currentContextElement().setResponse(response);

    Hai ,
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/526bd490-0201-0010-038e-d3ff7eb1d16e
    please check above link .
    application server u have take load balancing click on next  there u take click on radio button of Msg server .
    Regards ,
    venkat

Maybe you are looking for