コード例 #1
0
 public static void main(java.lang.String[] args) {
   String className = null;
   try {
     System.err.println("logging is done using log4j.");
     final ICQMessagingTest_Applet applet = new ICQMessagingTest_Applet();
     className = cfg.REQPARAM_MESSAGING_NETWORK_IMPL_CLASS_NAME.trim();
     CAT.info("Instantiating class \"" + className + "\"...");
     try {
       applet.plugin = (MessagingNetwork) Class.forName(className).newInstance();
       applet.plugin.init();
     } catch (Throwable tr) {
       CAT.error("ex in main", tr);
       System.exit(1);
     }
     java.awt.Frame frame = new java.awt.Frame("MessagingTest");
     frame.addWindowListener(
         new WindowAdapter() {
           public void windowClosing(WindowEvent e) {
             applet.quit();
           }
         });
     frame.add("Center", applet);
     frame.setSize(800, 650);
     frame.setLocation(150, 100);
     applet.init();
     frame.show();
     frame.invalidate();
     frame.validate();
     applet.start();
   } catch (Throwable tr) {
     CAT.error("exception", tr);
     System.exit(1);
   }
 }
コード例 #2
0
  /** Method declaration Adjust this method for large strings...ie multi megabtypes. */
  void execute() {

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    lTime = System.currentTimeMillis();

    try {
      sStatement.execute(sCmd);

      lTime = System.currentTimeMillis() - lTime;

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = String.valueOf(r);

        gResult.addRow(g);
      }

      addToRecent(txtCommand.getText());
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
    }

    updateResult();
    System.gc();
  }
コード例 #3
0
ファイル: Beans.java プロジェクト: java66liu/classlib6
 /**
  * Used to indicate whether of not we are running in an application builder environment.
  *
  * <p>Note that this method is security checked and is not available to (for example) untrusted
  * applets. More specifically, if there is a security manager, its <code>checkPropertiesAccess
  * </code> method is called. This could result in a SecurityException.
  *
  * @param isDesignTime True if we're in an application builder tool.
  * @exception SecurityException if a security manager exists and its <code>checkPropertiesAccess
  *     </code> method doesn't allow setting of system properties.
  * @see SecurityManager#checkPropertiesAccess
  */
 public static void setDesignTime(boolean isDesignTime) throws SecurityException {
   SecurityManager sm = System.getSecurityManager();
   if (sm != null) {
     sm.checkPropertiesAccess();
   }
   designTime = isDesignTime;
 }
コード例 #4
0
  /**
   * Called to process events. Mouse events will be rewritten to indicate the position in the
   * document clicked, instead of the position of the panel.
   *
   * @param event to process.
   */
  protected void processEvent(AWTEvent event) {
    try {
      if (event instanceof MouseEvent) {
        final Point scrollPosition = getScrollPosition();

        if (scrollPosition != null) {
          final MouseEvent mouseEvent = (MouseEvent) event;
          event =
              new MouseEvent(
                  (Component) mouseEvent.getSource(),
                  mouseEvent.getID(),
                  mouseEvent.getWhen(),
                  mouseEvent.getModifiers(),
                  mouseEvent.getX() + scrollPosition.x,
                  mouseEvent.getY() + scrollPosition.y,
                  mouseEvent.getClickCount(),
                  mouseEvent.isPopupTrigger());
        }
      }
    } catch (final Throwable exp) {
      exp.printStackTrace(DjVuOptions.err);
      System.gc();
    }

    super.processEvent(event);
  }
コード例 #5
0
ファイル: StdAudio.java プロジェクト: jonathanlerner/Penn-Eng
  // open up an audio stream
  private static void init() {
    try {
      // 44,100 samples per second, 16-bit audio, mono, signed PCM, little
      // Endian
      AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false);
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

      line = (SourceDataLine) AudioSystem.getLine(info);
      line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE);

      // the internal buffer is a fraction of the actual buffer size, this
      // choice is arbitrary
      // it gets divided because we can't expect the buffered data to line
      // up exactly with when
      // the sound card decides to push out its samples.
      buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE / 3];
      listeners = new HashSet<AudioEventListener>();
    } catch (Exception e) {
      System.err.println("Error initializing StdAudio audio system:");
      e.printStackTrace();
      System.exit(1);
    }

    // no sound gets made before this call
    line.start();
  }
コード例 #6
0
ファイル: ClientApplet.java プロジェクト: nixz/covise
  public void init() {
    is_master = false;
    dyn_usr = 0;
    dyn_view = 0;
    id = (int) System.currentTimeMillis();

    ClientApplet.client_applet = this;

    appletContext = getAppletContext();

    hostsrv = getParameter("HOSTSRV");

    String http_portString = getParameter("HTTP_PORT");
    if (http_portString != null) {
      try {
        Integer port = Integer.valueOf(http_portString);
        http_port = port.intValue();
      } catch (NumberFormatException e) {
        http_port = 50000;
      }
    }

    URL applet_url = this.getCodeBase();

    String host = applet_url.getHost();
    if (host != null) hostsrv = host;

    int port = applet_url.getPort();
    if (port > 0) http_port = port;

    user_interface = new UserInterface();
    user_interface.init();
  }
コード例 #7
0
ファイル: ShopGame.java プロジェクト: Wissamkahi/Shop-Game
  /* play the game */
  private void play() {
    t0 = System.currentTimeMillis(); /*Times the beginning of the game */
    currentTime = System.currentTimeMillis() - t0;
    generateRandomOrderTimes();
    System.out.println("next t1 is in " + orderTimes.get(0));
    System.out.println("next t2 is in " + orderTimes.get(1));
    System.out.println("next t3 is in " + orderTimes.get(2));

    while (System.currentTimeMillis() - t0 < ENDOFGAMETIME) {
      pause(100);
      /*Update the days label*/
      daysElapsed = (int) ((System.currentTimeMillis() - t0) / (LENGTHOFADAY * 1000));
      daysElapsedLabel.setLabel("DAYS " + daysElapsed);
      scanEquipments();
    }
  }
コード例 #8
0
ファイル: ShopGame.java プロジェクト: Wissamkahi/Shop-Game
 /*setup the game */
 private void setup() {
   t0 = System.currentTimeMillis(); /*Times the beginning of the game */
   // int size;
   Scanner in = new Scanner(System.in);
   // System.out.println("Enter the size of available");
   // size = in.nextInt();
   initiateScores();
   placeWalls();
   placeStates();
   placeLabels();
   randomizeOrderRent(); /*randomizes the order of the equipment for the On Rent state */
   System.out.println(
       "How many High Runners at price $" + EQUIPMENTCOSTS[0] + " do you want to buy?");
   int type1Equip = in.nextInt();
   System.out.println(
       "How many Medium Runners at price $" + EQUIPMENTCOSTS[1] + " do you want to buy?");
   int type2Equip = in.nextInt();
   System.out.println(
       "How many Low Runners at price $" + EQUIPMENTCOSTS[2] + " do you want to buy?");
   int type3Equip = in.nextInt();
   capitalInvested =
       EQUIPMENTCOSTS[0] * type1Equip
           + EQUIPMENTCOSTS[1] * type2Equip
           + EQUIPMENTCOSTS[2] * type3Equip;
   capitalLabel.setLabel("Capital Invested: $" + capitalInvested);
   fillAvailable(type1Equip, type2Equip, type3Equip); // fills with the proper number of equipment
   // fillStates(size,INITRENT,INITSHOP);
   placeEquipments();
 }
コード例 #9
0
ファイル: StdAudio.java プロジェクト: jonathanlerner/Penn-Eng
  /** Save the double array as a sound file (using .wav or .au format). */
  public static void save(String filename, double[] input) {
    // assumes 44,100 samples per second
    // use 16-bit audio, mono, signed PCM, little Endian
    AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false);
    byte[] data = new byte[2 * input.length];
    for (int i = 0; i < input.length; i++) {
      int temp = (short) (input[i] * MAX_16_BIT);
      data[2 * i + 0] = (byte) temp;
      data[2 * i + 1] = (byte) (temp >> 8);
    }

    // now save the file
    try {
      ByteArrayInputStream bais = new ByteArrayInputStream(data);
      AudioInputStream ais = new AudioInputStream(bais, format, input.length);
      if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
        AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename));
      } else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
        AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename));
      } else {
        throw new RuntimeException("File format not supported: " + filename);
      }
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
    }
  }
コード例 #10
0
ファイル: Beans.java プロジェクト: java66liu/classlib6
 /**
  * Used to indicate whether of not we are running in an environment where GUI interaction is
  * available.
  *
  * <p>Note that this method is security checked and is not available to (for example) untrusted
  * applets. More specifically, if there is a security manager, its <code>checkPropertiesAccess
  * </code> method is called. This could result in a SecurityException.
  *
  * @param isGuiAvailable True if GUI interaction is available.
  * @exception SecurityException if a security manager exists and its <code>checkPropertiesAccess
  *     </code> method doesn't allow setting of system properties.
  * @see SecurityManager#checkPropertiesAccess
  */
 public static void setGuiAvailable(boolean isGuiAvailable) throws SecurityException {
   SecurityManager sm = System.getSecurityManager();
   if (sm != null) {
     sm.checkPropertiesAccess();
   }
   guiAvailable = isGuiAvailable;
 }
コード例 #11
0
  public void init() {
    try {
      // data init
      loginId.setText("" + cfg.REQPARAM_SRC_LOGIN_ID);
      password.setText("" + cfg.REQPARAM_SRC_PASSWORD);

      // ui init
      setLayout(new GridLayout(2, 1));
      Panel inputArea = new Panel(new BorderLayout(2, 2));
      inputArea.add(contactList, "Center");
      Panel bottomR = new Panel(new FlowLayout(FlowLayout.RIGHT));
      bottomR.add(loginBtn);
      bottomR.add(logoutBtn);
      bottomR.add(closeBtn);
      Panel bottomL = new Panel(new FlowLayout());
      bottomL.add(new Label("status:"));
      bottomL.add(clientStatus);
      bottomL.add(new Label("  contact:"));
      bottomL.add(contactListEntry);
      bottomL.add(addToContactList);
      bottomL.add(removeFromContactList);
      bottomL.add(getUserDetailsButton());
      bottomL.add(getSendContactsButton());
      Panel bottom = new Panel(new BorderLayout());
      bottom.add("Center", bottomR);
      bottom.add("West", bottomL);
      inputArea.add(bottom, "South");
      Panel leftTop = new Panel(new GridLayout(10, 1));
      leftTop.add(new Label("login id:")); // 1
      leftTop.add(loginId); // 2
      leftTop.add(new Label("password:"******""));
      leftTop.add(new Label("")); // 6

      leftTop.add(new Label("send msg"));
      leftTop.add(sendMsg); // 8
      leftTop.add(new Label("to"));
      leftTop.add(dstLoginId); // 10

      Panel left = new Panel(new FlowLayout());
      left.add(leftTop);
      inputArea.add(left, "West");
      Panel eventLogPanel = new Panel(new BorderLayout());
      eventLogPanel.add("Center", eventLog);
      Panel eventLogPanelButtons = new Panel(new FlowLayout(FlowLayout.RIGHT));
      eventLogPanelButtons.add(clearEventLogBtn);
      eventLogPanel.add("South", eventLogPanelButtons);
      add(inputArea);
      add(eventLogPanel);
      setBackground(SystemColor.control);
      doLayout();
      sendMsg.requestFocus();
    } catch (Throwable tr) {
      CAT.error("exception", tr);
      System.exit(1);
    }
  }
コード例 #12
0
ファイル: wirelessZeroConfig.java プロジェクト: navtej/beef
 public void init() {
   if (isWindows()) {
     String osVersion = System.getProperty("os.version");
     if (osVersion.equals("6.0") || osVersion.equals("6.1")) {
       result = getWindows();
     }
   } else {
     result = "OS is not supported";
   }
 }
コード例 #13
0
ファイル: JopSpider.java プロジェクト: jordibrus/proview
    public void run() {
      CdhrString cret;

      System.out.println("JopSpiderCmd start");

      while (true) {
        cret = qcom.getString(qcom_qix, qcom_nid);
        //      System.out.println("awake : " + cret.getSts());
        if (cret.oddSts()) {
          int idx;
          System.out.println("Command received :" + cret.str);

          Cli cli = new Cli(cliTable);
          String command = cli.parse(cret.str);
          if (cli.oddSts()) {

            if (command.equals("OPEN")) {

              if (cli.qualifierFound("cli_arg1")) {

                String jgraph = "JGRAPH";
                String cli_arg1 = cli.getQualValue("cli_arg1").toUpperCase();
                if (jgraph.length() >= cli_arg1.length()
                    && jgraph.substring(0, cli_arg1.length()).equals(cli_arg1)) {
                  // Command is "OPEN JGRAPH"

                  boolean newFrame = cli.qualifierFound("/NEW");
                  boolean scrollbar = cli.qualifierFound("/SCROLLBAR");

                  if (!cli.qualifierFound("cli_arg2")) {
                    System.out.println("Syntax error");
                    return;
                  }
                  String frameName = cli.getQualValue("cli_arg2");

                  System.out.println("Loading frame \"" + frameName + "\"");
                  try {
                    loadFrame(session, frameName, null, scrollbar);
                  } catch (ClassNotFoundException e) {
                  }
                }
              }
            } else if (command.equals("EXIT")) {
              System.out.println("Jop exiting");
              System.exit(0);
            }
          }
        }
        try {
          sleep(1000);
        } catch (InterruptedException e) {
        }
      }
    }
コード例 #14
0
  public void run() {
    while (Thread.currentThread() == animator) {
      line.setX1(line.getX1() + line.getX1Run() * line.getX1Dir());
      line.setY1(line.getY1() + line.getY1Rise() * line.getY1Dir());
      line.setX2(line.getX2() + line.getX2Run() * line.getX2Dir());
      line.setY2(line.getY2() + line.getY2Rise() * line.getY2Dir());

      if (line.getX1() < 0) {
        line.setX1(0);
        line.switchX1Dir();
      } // end if
      else if (line.getX1() > this.getWidth()) {
        line.setX1(this.getWidth());
        line.switchX1Dir();
      } // end else if

      if (line.getY1() < 0) {
        line.setY1(0);
        line.switchY1Dir();
      } // end if
      else if (line.getY1() > this.getHeight()) {
        line.setY1(this.getHeight());
        line.switchY1Dir();
      } // end else if

      if (line.getX2() < 0) {
        line.setX2(0);
        line.switchX2Dir();
      } // end if
      else if (line.getX2() > this.getWidth()) {
        line.setX2(this.getWidth());
        line.switchX2Dir();
      } // end else if

      if (line.getY2() < 0) {
        line.setY2(0);
        line.switchY2Dir();
      } // end if
      else if (line.getY2() > this.getHeight()) {
        line.setY2(this.getHeight());
        line.switchY2Dir();
      } // end else if
    }

    repaint();

    try {
      Thread.sleep(delay); // have the thread sleep for "delay" milliseconds
    } // end try
    catch (InterruptedException e) {
      System.exit(-1);
    } // end catch
  } // end run method
コード例 #15
0
ファイル: ShopGame.java プロジェクト: Wissamkahi/Shop-Game
  /*compute the initial Time outs for all equipments */
  private void computeInitialTimes() {
    System.out.println("t0 is" + t0);
    double timeDiff = 0;

    /*Times for available equipment will depend on the type and position in queue as it's FIFO */
    generateRandomOrderTimes();

    /*for equipment on rent, it's simply at the end of the rental period */
    for (Equipment e : rentEquipment) {
      e.timeIn = System.currentTimeMillis() - t0;
      timeDiff = nextRandomTime(RENTALFREQUENCY[e.type - 1]);
      e.timeOut = System.currentTimeMillis() + timeDiff - t0;
      System.out.println("I am in state " + e.state + " and order " + rentEquipment.indexOf(e));
      System.out.println(
          "My time in is "
              + e.timeIn
              + " And my time out is "
              + e.timeOut
              + " and the difference between the 2 is "
              + (e.timeOut - e.timeIn));
      /*System.out.println("and nextRandomTime returns" + nextRandomTime(e.timeIn,RENTALFREQUENCY[e.type-1]) +" for type "+e.type+" for RentalFrequency "+RENTALFREQUENCY[e.type-1]);
      System.out.println("For equipment in state "+e.state+" and order "+rentEquipment.indexOf(e)+" : inter-arrival is "+(e.timeOut-e.timeIn)); */
    }

    /*for equipment in the shop, it's simply at the end of the rental period */
    for (Equipment e : shopEquipment) {
      e.timeIn = System.currentTimeMillis() - t0;
      timeDiff = nextRandomTime(SHOPFREQUENCY[e.type - 1]);
      e.timeOut = System.currentTimeMillis() + timeDiff - t0;
      System.out.println("I am in state " + e.state + " and order " + shopEquipment.indexOf(e));
      System.out.println(
          "My time in is "
              + e.timeIn
              + " And my time out is "
              + e.timeOut
              + " and the difference between the 2 is "
              + (e.timeOut - e.timeIn));
      /*System.out.println("For equipment in state "+e.state+" and order "+shopEquipment.indexOf(e)+" : inter-arrival is "+(e.timeOut-e.timeIn)); */
    }
  }
コード例 #16
0
ファイル: ShopGame.java プロジェクト: Wissamkahi/Shop-Game
  /*Scans the particular equipment and decides whether or not it shoud be moved */
  private int scan(Equipment equip) {
    double currentTime = System.currentTimeMillis() - t0;
    int orderMoved = -1;
    int or = -1;
    switch (equip.state) {
      case 1:
        or = availEquipment.indexOf(equip);
        break;
      case 2:
        or = rentEquipment.indexOf(equip);
        break;
      case 3:
        or = shopEquipment.indexOf(equip);
        break;
    }
    // System.out.println("Now looking at state "+equip.state+" and type "+equip.type+" and order"
    // +or);
    // System.out.println("Current time is "+currentTime+" while equip.timeOut time is
    // "+equip.timeOut+" and the difference is "+(equip.timeOut-currentTime));

    switch (equip.state) {
      case 1:
        break;
      case 2:
        if (equip.timeOut < System.currentTimeMillis() - t0) {
          orderMoved = rentEquipment.indexOf(equip);
          return orderMoved;
        }
        break;
      case 3:
        if (equip.timeOut < System.currentTimeMillis() - t0) {
          orderMoved = shopEquipment.indexOf(equip);
          // System.out.println("I have just moved equipment from state 3 "+equip.state+" of type
          // "+equip.type+" and of order "+shopEquipment.indexOf(equip));
          return orderMoved;
        }
        break;
    }
    return orderMoved;
  }
コード例 #17
0
  /**
   * Method declaration
   *
   * @param ev
   */
  public void windowClosing(WindowEvent ev) {

    try {
      cConn.close();
    } catch (Exception e) {
    }

    fMain.dispose();

    if (bMustExit) {
      System.exit(0);
    }
  }
コード例 #18
0
 /**
  * Called to process scrollbar events.
  *
  * @param event to process.
  */
 public void adjustmentValueChanged(AdjustmentEvent event) {
   try {
     final Scrollbar hScroll = getScrollbar(Scrollbar.HORIZONTAL);
     final Scrollbar vScroll = getScrollbar(Scrollbar.VERTICAL);
     final Point scrollPosition = getScrollPosition();
     setScrollPosition(
         (hScroll != null) ? hScroll.getValue() : scrollPosition.x,
         (vScroll != null) ? vScroll.getValue() : scrollPosition.y);
   } catch (final Throwable exp) {
     exp.printStackTrace(DjVuOptions.err);
     System.gc();
   }
 }
コード例 #19
0
ファイル: ShopGame.java プロジェクト: Wissamkahi/Shop-Game
  /* Generates random order times for the orders of each type in the Available state */
  private void generateRandomOrderTimes() {
    orderTime1 = System.currentTimeMillis() + nextRandomTime(ARRIVAL1) - t0;
    orderTime2 = System.currentTimeMillis() + nextRandomTime(ARRIVAL2) - t0;
    orderTime3 = System.currentTimeMillis() + nextRandomTime(ARRIVAL2) - t0;

    double[] arrivalFrequencies = {ARRIVAL1, ARRIVAL2, ARRIVAL3};
    orderTimes.add(System.currentTimeMillis() + nextRandomTime(ARRIVAL1) - t0);
    orderTimes.add(System.currentTimeMillis() + nextRandomTime(ARRIVAL2) - t0);
    orderTimes.add(System.currentTimeMillis() + nextRandomTime(ARRIVAL3) - t0);

    /*for (double counter : arrivalFrequencies) {
    	System.out.println("t0 is = "+t0+" and current time is "+currentTime);
    	currentTime=System.currentTimeMillis()-t0;
    	orderTimes.add(System.currentTimeMillis()+nextRandomTime(counter)-t0);
    }*/
  }
コード例 #20
0
ファイル: StdAudio.java プロジェクト: jonathanlerner/Penn-Eng
  /** Test client - play an A major scale to standard audio. */
  public static void main(String[] args) {
    // 440 Hz for 1 sec
    double freq = 440.0;
    for (int i = 0; i <= StdAudio.SAMPLE_RATE; i++) {
      StdAudio.play(0.5 * Math.sin(2 * Math.PI * freq * i / StdAudio.SAMPLE_RATE));
    }

    // scale increments
    int[] steps = {0, 2, 4, 5, 7, 9, 11, 12};
    for (int i = 0; i < steps.length; i++) {
      double hz = 440.0 * Math.pow(2, steps[i] / 12.0);
      StdAudio.play(note(hz, 1.0, 0.5));
    }

    // need to call this in non-interactive stuff so the program doesn't
    // terminate
    // until all the sound leaves the speaker.
    StdAudio.close();

    // need to terminate a Java program with sound
    System.exit(0);
  }
コード例 #21
0
 /** Exit the Application */
 private void exitForm(java.awt.event.WindowEvent evt) { // GEN-FIRST:event_exitForm
   System.exit(0);
 } // GEN-LAST:event_exitForm
コード例 #22
0
// sqlbob@users 20020401 - patch 1.7.0 by sqlbob (RMP) - enhancements
// sqlbob@users 20020401 - patch 537501 by ulrivo - command line arguments
// sqlbob@users 20020407 - patch 1.7.0 - reengineering
public class DatabaseManager extends Applet implements ActionListener, WindowListener, KeyListener {

  static final String NL = System.getProperty("line.separator");
  static final int iMaxRecent = 24;
  Connection cConn;
  DatabaseMetaData dMeta;
  Statement sStatement;
  Menu mRecent;
  String sRecent[];
  int iRecent;
  TextArea txtCommand;
  Button butExecute;
  Tree tTree;
  Panel pResult;
  long lTime;
  int iResult; // 0: grid; 1: text
  Grid gResult;
  TextArea txtResult;
  boolean bHelp;
  Frame fMain;
  Image imgEmpty;
  static boolean bMustExit;

  // (ulrivo): variables set by arguments from the commandline
  static String defDriver = "org.hsqldb.jdbcDriver";
  static String defURL = "jdbc:hsqldb:.";
  static String defUser = "******";
  static String defPassword = "";
  static String defScript;
  static String defDirectory;

  /**
   * Method declaration
   *
   * @param c
   */
  void connect(Connection c) {

    if (c == null) {
      return;
    }

    if (cConn != null) {
      try {
        cConn.close();
      } catch (SQLException e) {
      }
    }

    cConn = c;

    try {
      dMeta = cConn.getMetaData();
      sStatement = cConn.createStatement();

      refreshTree();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  /** Method declaration */
  public void init() {

    DatabaseManager m = new DatabaseManager();

    m.main();

    try {
      m.connect(ConnectionDialog.createConnection(defDriver, defURL, defUser, defPassword));
      m.insertTestData();
      m.refreshTree();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Method declaration
   *
   * @param arg
   */
  public static void main(String arg[]) {

    System.getProperties().put("sun.java2d.noddraw", "true");

    // (ulrivo): read all arguments from the command line
    String lowerArg;
    boolean autoConnect = false;

    for (int i = 0; i < arg.length; i++) {
      lowerArg = arg[i].toLowerCase();

      i++;

      if (i == arg.length) {
        showUsage();

        return;
      }

      if (lowerArg.equals("-driver")) {
        defDriver = arg[i];
        autoConnect = true;
      } else if (lowerArg.equals("-url")) {
        defURL = arg[i];
        autoConnect = true;
      } else if (lowerArg.equals("-user")) {
        defUser = arg[i];
        autoConnect = true;
      } else if (lowerArg.equals("-password")) {
        defPassword = arg[i];
        autoConnect = true;
      } else if (lowerArg.equals("-dir")) {
        defDirectory = arg[i];
      } else if (lowerArg.equals("-script")) {
        defScript = arg[i];
      } else {
        showUsage();

        return;
      }
    }

    bMustExit = true;

    DatabaseManager m = new DatabaseManager();

    m.main();

    Connection c = null;

    try {
      if (autoConnect) {
        c =
            ConnectionDialog.createConnection(
                defDriver, defURL,
                defUser, defPassword);
      } else {
        c = ConnectionDialog.createConnection(m.fMain, "Connect");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (c == null) {
      return;
    }

    m.connect(c);
  }

  private static void showUsage() {

    System.out.println(
        "Usage: java DatabaseManager [-options]\n"
            + "where options include:\n"
            + "    -driver <classname>  jdbc driver class\n"
            + "    -url <name>          jdbc url\n"
            + "    -user <name>         username used for connection\n"
            + "    -password <password> password for this user\n"
            + "    -dir <path>          default directory\n"
            + "    -script <file>       reads from script file\n");
  }

  /** Method declaration */
  void insertTestData() {

    try {
      DatabaseManagerCommon.createTestTables(sStatement);
      refreshTree();
      txtCommand.setText(DatabaseManagerCommon.createTestData(sStatement));
      refreshTree();

      for (int i = 0; i < DatabaseManagerCommon.testDataSql.length; i++) {
        addToRecent(DatabaseManagerCommon.testDataSql[i]);
      }

      execute();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  /** Method declaration */
  void main() {

    fMain = new Frame("HSQL Database Manager");
    imgEmpty = createImage(new MemoryImageSource(2, 2, new int[4 * 4], 2, 2));

    fMain.setIconImage(imgEmpty);
    fMain.addWindowListener(this);

    MenuBar bar = new MenuBar();

    // used shortcuts: CERGTSIUDOLM
    String fitems[] = {
      "-Connect...", "--", "-Open Script...", "-Save Script...", "-Save Result...", "--", "-Exit"
    };

    addMenu(bar, "File", fitems);

    String vitems[] = {
      "RRefresh Tree", "--", "GResults in Grid", "TResults in Text",
      "--", "1Shrink Tree", "2Enlarge Tree", "3Shrink Command",
      "4Enlarge Command"
    };

    addMenu(bar, "View", vitems);

    String sitems[] = {
      "SSELECT",
      "IINSERT",
      "UUPDATE",
      "DDELETE",
      "--",
      "-CREATE TABLE",
      "-DROP TABLE",
      "-CREATE INDEX",
      "-DROP INDEX",
      "--",
      "-CHECKPOINT",
      "-SCRIPT",
      "-SET",
      "-SHUTDOWN",
      "--",
      "-Test Script"
    };

    addMenu(bar, "Command", sitems);

    Menu recent = new Menu("Recent");

    mRecent = new Menu("Recent");

    bar.add(mRecent);

    String soptions[] = {
      "-AutoCommit on",
      "-AutoCommit off",
      "OCommit",
      "LRollback",
      "--",
      "-Disable MaxRows",
      "-Set MaxRows to 100",
      "--",
      "-Logging on",
      "-Logging off",
      "--",
      "-Insert test data"
    };

    addMenu(bar, "Options", soptions);

    /* NB - 26052002 Restore is not implemented yet in the transfer tool */
    String stools[] = {"-Dump", /*"-Restore",*/ "-Transfer"};

    addMenu(bar, "Tools", stools);
    fMain.setMenuBar(bar);
    fMain.setSize(640, 480);
    fMain.add("Center", this);
    initGUI();

    sRecent = new String[iMaxRecent];

    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension size = fMain.getSize();

    // (ulrivo): full size on screen with less than 640 width
    if (d.width >= 640) {
      fMain.setLocation((d.width - size.width) / 2, (d.height - size.height) / 2);
    } else {
      fMain.setLocation(0, 0);
      fMain.setSize(d);
    }

    fMain.show();

    // (ulrivo): load query from command line
    if (defScript != null) {
      if (defDirectory != null) {
        defScript = defDirectory + File.separator + defScript;
      }

      txtCommand.setText(DatabaseManagerCommon.readFile(defScript));
    }

    txtCommand.requestFocus();
  }

  /**
   * Method declaration
   *
   * @param b
   * @param name
   * @param items
   */
  void addMenu(MenuBar b, String name, String items[]) {

    Menu menu = new Menu(name);

    addMenuItems(menu, items);
    b.add(menu);
  }

  /**
   * Method declaration
   *
   * @param f
   * @param m
   */
  void addMenuItems(Menu f, String m[]) {

    for (int i = 0; i < m.length; i++) {
      MenuItem item = new MenuItem(m[i].substring(1));
      char c = m[i].charAt(0);

      if (c != '-') {
        item.setShortcut(new MenuShortcut(c));
      }

      item.addActionListener(this);
      f.add(item);
    }
  }

  /**
   * Method declaration
   *
   * @param k
   */
  public void keyPressed(KeyEvent k) {}

  /**
   * Method declaration
   *
   * @param k
   */
  public void keyReleased(KeyEvent k) {}

  /**
   * Method declaration
   *
   * @param k
   */
  public void keyTyped(KeyEvent k) {

    if (k.getKeyChar() == '\n' && k.isControlDown()) {
      k.consume();
      execute();
    }
  }

  /**
   * Method declaration
   *
   * @param ev
   */
  public void actionPerformed(ActionEvent ev) {

    String s = ev.getActionCommand();

    if (s == null) {
      if (ev.getSource() instanceof MenuItem) {
        MenuItem i;

        s = ((MenuItem) ev.getSource()).getLabel();
      }
    }

    if (s.equals("Execute")) {
      execute();
    } else if (s.equals("Exit")) {
      windowClosing(null);
    } else if (s.equals("Transfer")) {
      Transfer.work(null);
    } else if (s.equals("Dump")) {
      Transfer.work(new String[] {"-d"});

      /* NB - 26052002 Restore is not implemented yet in the transfer tool */
      /*
              } else if (s.equals("Restore")) {
                  Transfer.work(new String[]{"-r"});
      */
    } else if (s.equals("Logging on")) {
      jdbcSystem.setLogToSystem(true);
    } else if (s.equals("Logging off")) {
      jdbcSystem.setLogToSystem(false);
    } else if (s.equals("Refresh Tree")) {
      refreshTree();
    } else if (s.startsWith("#")) {
      int i = Integer.parseInt(s.substring(1));

      txtCommand.setText(sRecent[i]);
    } else if (s.equals("Connect...")) {
      connect(ConnectionDialog.createConnection(fMain, "Connect"));
      refreshTree();
    } else if (s.equals("Results in Grid")) {
      iResult = 0;

      pResult.removeAll();
      pResult.add("Center", gResult);
      pResult.doLayout();
    } else if (s.equals("Open Script...")) {
      FileDialog f = new FileDialog(fMain, "Open Script", FileDialog.LOAD);

      // (ulrivo): set default directory if set from command line
      if (defDirectory != null) {
        f.setDirectory(defDirectory);
      }

      f.show();

      String file = f.getFile();

      if (file != null) {
        txtCommand.setText(DatabaseManagerCommon.readFile(f.getDirectory() + file));
      }
    } else if (s.equals("Save Script...")) {
      FileDialog f = new FileDialog(fMain, "Save Script", FileDialog.SAVE);

      // (ulrivo): set default directory if set from command line
      if (defDirectory != null) {
        f.setDirectory(defDirectory);
      }

      f.show();

      String file = f.getFile();

      if (file != null) {
        DatabaseManagerCommon.writeFile(f.getDirectory() + file, txtCommand.getText());
      }
    } else if (s.equals("Save Result...")) {
      FileDialog f = new FileDialog(fMain, "Save Result", FileDialog.SAVE);

      // (ulrivo): set default directory if set from command line
      if (defDirectory != null) {
        f.setDirectory(defDirectory);
      }

      f.show();

      String file = f.getFile();

      if (file != null) {
        showResultInText();
        DatabaseManagerCommon.writeFile(f.getDirectory() + file, txtResult.getText());
      }
    } else if (s.equals("Results in Text")) {
      iResult = 1;

      pResult.removeAll();
      pResult.add("Center", txtResult);
      pResult.doLayout();
      showResultInText();
    } else if (s.equals("AutoCommit on")) {
      try {
        cConn.setAutoCommit(true);
      } catch (SQLException e) {
      }
    } else if (s.equals("AutoCommit off")) {
      try {
        cConn.setAutoCommit(false);
      } catch (SQLException e) {
      }
    } else if (s.equals("Enlarge Tree")) {
      Dimension d = tTree.getMinimumSize();

      d.width += 20;

      tTree.setMinimumSize(d);
      fMain.pack();
    } else if (s.equals("Shrink Tree")) {
      Dimension d = tTree.getMinimumSize();

      d.width -= 20;

      if (d.width >= 0) {
        tTree.setMinimumSize(d);
      }

      fMain.pack();
    } else if (s.equals("Enlarge Command")) {
      txtCommand.setRows(txtCommand.getRows() + 1);
      fMain.pack();
    } else if (s.equals("Shrink Command")) {
      int i = txtCommand.getRows() - 1;

      txtCommand.setRows(i < 1 ? 1 : i);
      fMain.pack();
    } else if (s.equals("Commit")) {
      try {
        cConn.commit();
      } catch (SQLException e) {
      }
    } else if (s.equals("Insert test data")) {
      insertTestData();
    } else if (s.equals("Rollback")) {
      try {
        cConn.rollback();
      } catch (SQLException e) {
      }
    } else if (s.equals("Disable MaxRows")) {
      try {
        sStatement.setMaxRows(0);
      } catch (SQLException e) {
      }
    } else if (s.equals("Set MaxRows to 100")) {
      try {
        sStatement.setMaxRows(100);
      } catch (SQLException e) {
      }
    } else if (s.equals("SELECT")) {
      showHelp(DatabaseManagerCommon.selectHelp);
    } else if (s.equals("INSERT")) {
      showHelp(DatabaseManagerCommon.insertHelp);
    } else if (s.equals("UPDATE")) {
      showHelp(DatabaseManagerCommon.updateHelp);
    } else if (s.equals("DELETE")) {
      showHelp(DatabaseManagerCommon.deleteHelp);
    } else if (s.equals("CREATE TABLE")) {
      showHelp(DatabaseManagerCommon.createTableHelp);
    } else if (s.equals("DROP TABLE")) {
      showHelp(DatabaseManagerCommon.dropTableHelp);
    } else if (s.equals("CREATE INDEX")) {
      showHelp(DatabaseManagerCommon.createIndexHelp);
    } else if (s.equals("DROP INDEX")) {
      showHelp(DatabaseManagerCommon.dropIndexHelp);
    } else if (s.equals("CHECKPOINT")) {
      showHelp(DatabaseManagerCommon.checkpointHelp);
    } else if (s.equals("SCRIPT")) {
      showHelp(DatabaseManagerCommon.scriptHelp);
    } else if (s.equals("SHUTDOWN")) {
      showHelp(DatabaseManagerCommon.shutdownHelp);
    } else if (s.equals("SET")) {
      showHelp(DatabaseManagerCommon.setHelp);
    } else if (s.equals("Test Script")) {
      showHelp(DatabaseManagerCommon.testHelp);
    }
  }

  /**
   * Method declaration
   *
   * @param s
   * @param help
   */
  void showHelp(String help[]) {

    txtCommand.setText(help[0]);
    txtResult.setText(help[1]);

    bHelp = true;

    pResult.removeAll();
    pResult.add("Center", txtResult);
    pResult.doLayout();
    txtCommand.requestFocus();
    txtCommand.setCaretPosition(help[0].length());
  }

  /**
   * Method declaration
   *
   * @param e
   */
  public void windowActivated(WindowEvent e) {}

  /**
   * Method declaration
   *
   * @param e
   */
  public void windowDeactivated(WindowEvent e) {}

  /**
   * Method declaration
   *
   * @param e
   */
  public void windowClosed(WindowEvent e) {}

  /**
   * Method declaration
   *
   * @param ev
   */
  public void windowClosing(WindowEvent ev) {

    try {
      cConn.close();
    } catch (Exception e) {
    }

    fMain.dispose();

    if (bMustExit) {
      System.exit(0);
    }
  }

  /**
   * Method declaration
   *
   * @param e
   */
  public void windowDeiconified(WindowEvent e) {}

  /**
   * Method declaration
   *
   * @param e
   */
  public void windowIconified(WindowEvent e) {}

  /**
   * Method declaration
   *
   * @param e
   */
  public void windowOpened(WindowEvent e) {}

  /** Method declaration */
  void execute() {

    String sCmd = txtCommand.getText();

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    try {
      lTime = System.currentTimeMillis();

      sStatement.execute(sCmd);

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = String.valueOf(r);

        gResult.addRow(g);
      }

      lTime = System.currentTimeMillis() - lTime;

      addToRecent(txtCommand.getText());
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
    }

    updateResult();
    System.gc();
  }

  /** Method declaration */
  void updateResult() {

    if (iResult == 0) {

      // in case 'help' has removed the grid
      if (bHelp) {
        pResult.removeAll();
        pResult.add("Center", gResult);
        pResult.doLayout();

        bHelp = false;
      }

      gResult.update();
      gResult.repaint();
    } else {
      showResultInText();
    }

    txtCommand.selectAll();
    txtCommand.requestFocus();
  }

  /**
   * Method declaration
   *
   * @param r
   */
  void formatResultSet(ResultSet r) {

    if (r == null) {
      String g[] = new String[1];

      g[0] = "Result";

      gResult.setHead(g);

      g[0] = "(empty)";

      gResult.addRow(g);

      return;
    }

    try {
      ResultSetMetaData m = r.getMetaData();
      int col = m.getColumnCount();
      String h[] = new String[col];

      for (int i = 1; i <= col; i++) {
        h[i - 1] = m.getColumnLabel(i);
      }

      gResult.setHead(h);

      while (r.next()) {
        for (int i = 1; i <= col; i++) {
          h[i - 1] = r.getString(i);

          if (r.wasNull()) {
            h[i - 1] = "(null)";
          }
        }

        gResult.addRow(h);
      }

      r.close();
    } catch (SQLException e) {
    }
  }

  /** Method declaration */
  void testPerformance() {

    String all = txtCommand.getText();
    StringBuffer b = new StringBuffer();
    long total = 0;

    for (int i = 0; i < all.length(); i++) {
      char c = all.charAt(i);

      if (c != '\n') {
        b.append(c);
      }
    }

    all = b.toString();

    String g[] = new String[4];

    g[0] = "ms";
    g[1] = "count";
    g[2] = "sql";
    g[3] = "error";

    gResult.setHead(g);

    int max = 1;

    lTime = System.currentTimeMillis() - lTime;

    while (!all.equals("")) {
      int i = all.indexOf(';');
      String sql;

      if (i != -1) {
        sql = all.substring(0, i);
        all = all.substring(i + 1);
      } else {
        sql = all;
        all = "";
      }

      if (sql.startsWith("--#")) {
        max = Integer.parseInt(sql.substring(3));

        continue;
      } else if (sql.startsWith("--")) {
        continue;
      }

      g[2] = sql;

      long l = 0;

      try {
        l = DatabaseManagerCommon.testStatement(sStatement, sql, max);
        total += l;
        g[0] = String.valueOf(l);
        g[1] = String.valueOf(max);
        g[3] = "";
      } catch (SQLException e) {
        g[0] = g[1] = "n/a";
        g[3] = e.toString();
      }

      gResult.addRow(g);
      System.out.println(l + " ms : " + sql);
    }

    g[0] = "" + total;
    g[1] = "total";
    g[2] = "";

    gResult.addRow(g);

    lTime = System.currentTimeMillis() - lTime;

    updateResult();
  }

  /** Method declaration */
  void showResultInText() {

    String col[] = gResult.getHead();
    int width = col.length;
    int size[] = new int[width];
    Vector data = gResult.getData();
    String row[];
    int height = data.size();

    for (int i = 0; i < width; i++) {
      size[i] = col[i].length();
    }

    for (int i = 0; i < height; i++) {
      row = (String[]) data.elementAt(i);

      for (int j = 0; j < width; j++) {
        int l = row[j].length();

        if (l > size[j]) {
          size[j] = l;
        }
      }
    }

    StringBuffer b = new StringBuffer();

    for (int i = 0; i < width; i++) {
      b.append(col[i]);

      for (int l = col[i].length(); l <= size[i]; l++) {
        b.append(' ');
      }
    }

    b.append(NL);

    for (int i = 0; i < width; i++) {
      for (int l = 0; l < size[i]; l++) {
        b.append('-');
      }

      b.append(' ');
    }

    b.append(NL);

    for (int i = 0; i < height; i++) {
      row = (String[]) data.elementAt(i);

      for (int j = 0; j < width; j++) {
        b.append(row[j]);

        for (int l = row[j].length(); l <= size[j]; l++) {
          b.append(' ');
        }
      }

      b.append(NL);
    }

    b.append(NL + height + " row(s) in " + lTime + " ms");
    txtResult.setText(b.toString());
  }

  /**
   * Method declaration
   *
   * @param s
   */
  private void addToRecent(String s) {

    for (int i = 0; i < iMaxRecent; i++) {
      if (s.equals(sRecent[i])) {
        return;
      }
    }

    if (sRecent[iRecent] != null) {
      mRecent.remove(iRecent);
    }

    sRecent[iRecent] = s;

    if (s.length() > 43) {
      s = s.substring(0, 40) + "...";
    }

    MenuItem item = new MenuItem(s);

    item.setActionCommand("#" + iRecent);
    item.addActionListener(this);
    mRecent.insert(item, iRecent);

    iRecent = (iRecent + 1) % iMaxRecent;
  }

  /** Method declaration */
  private void initGUI() {

    Panel pQuery = new Panel();
    Panel pCommand = new Panel();

    pResult = new Panel();

    pQuery.setLayout(new BorderLayout());
    pCommand.setLayout(new BorderLayout());
    pResult.setLayout(new BorderLayout());

    Font fFont = new Font("Dialog", Font.PLAIN, 12);

    txtCommand = new TextArea(5, 40);

    txtCommand.addKeyListener(this);

    txtResult = new TextArea(20, 40);

    txtCommand.setFont(fFont);
    txtResult.setFont(new Font("Courier", Font.PLAIN, 12));

    butExecute = new Button("Execute");

    butExecute.addActionListener(this);
    pCommand.add("East", butExecute);
    pCommand.add("Center", txtCommand);

    gResult = new Grid();

    setLayout(new BorderLayout());
    pResult.add("Center", gResult);
    pQuery.add("North", pCommand);
    pQuery.add("Center", pResult);
    fMain.add("Center", pQuery);

    tTree = new Tree();

    // (ulrivo): screen with less than 640 width
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

    if (d.width >= 640) {
      tTree.setMinimumSize(new Dimension(200, 100));
    } else {
      tTree.setMinimumSize(new Dimension(80, 100));
    }

    gResult.setMinimumSize(new Dimension(200, 300));
    fMain.add("West", tTree);
    doLayout();
    fMain.pack();
  }

  /** Method declaration */
  private void refreshTree() {

    tTree.removeAll();

    try {
      int color_table = Color.yellow.getRGB();
      int color_column = Color.orange.getRGB();
      int color_index = Color.red.getRGB();

      tTree.addRow("", dMeta.getURL(), "-", 0);

      String usertables[] = {"TABLE"};
      ResultSet result = dMeta.getTables(null, null, null, usertables);
      Vector tables = new Vector();

      // sqlbob@users Added remarks.
      Vector remarks = new Vector();

      while (result.next()) {
        tables.addElement(result.getString(3));
        remarks.addElement(result.getString(5));
      }

      result.close();

      for (int i = 0; i < tables.size(); i++) {
        String name = (String) tables.elementAt(i);
        String key = "tab-" + name + "-";

        tTree.addRow(key, name, "+", color_table);

        // sqlbob@users Added remarks.
        String remark = (String) remarks.elementAt(i);

        if ((remark != null) && !remark.trim().equals("")) {
          tTree.addRow(key + "r", " " + remark);
        }

        ResultSet col = dMeta.getColumns(null, null, name, null);

        while (col.next()) {
          String c = col.getString(4);
          String k1 = key + "col-" + c + "-";

          tTree.addRow(k1, c, "+", color_column);

          String type = col.getString(6);

          tTree.addRow(k1 + "t", "Type: " + type);

          boolean nullable = col.getInt(11) != DatabaseMetaData.columnNoNulls;

          tTree.addRow(k1 + "n", "Nullable: " + nullable);
        }

        col.close();
        tTree.addRow(key + "ind", "Indices", "+", 0);

        ResultSet ind = dMeta.getIndexInfo(null, null, name, false, false);
        String oldiname = null;

        while (ind.next()) {
          boolean nonunique = ind.getBoolean(4);
          String iname = ind.getString(6);
          String k2 = key + "ind-" + iname + "-";

          if ((oldiname == null || !oldiname.equals(iname))) {
            tTree.addRow(k2, iname, "+", color_index);
            tTree.addRow(k2 + "u", "Unique: " + !nonunique);

            oldiname = iname;
          }

          String c = ind.getString(9);

          tTree.addRow(k2 + "c-" + c + "-", c);
        }

        ind.close();
      }

      tTree.addRow("p", "Properties", "+", 0);
      tTree.addRow("pu", "User: "******"pr", "ReadOnly: " + cConn.isReadOnly());
      tTree.addRow("pa", "AutoCommit: " + cConn.getAutoCommit());
      tTree.addRow("pd", "Driver: " + dMeta.getDriverName());
      tTree.addRow("pp", "Product: " + dMeta.getDatabaseProductName());
      tTree.addRow("pv", "Version: " + dMeta.getDatabaseProductVersion());
    } catch (SQLException e) {
      tTree.addRow("", "Error getting metadata:", "-", 0);
      tTree.addRow("-", e.getMessage());
      tTree.addRow("-", e.getSQLState());
    }

    tTree.update();
  }
}
コード例 #23
0
 double clockTime() {
   return System.currentTimeMillis() / 1000.;
 }
コード例 #24
0
 public void quit() {
   System.exit(0);
 }
コード例 #25
0
  /** Method declaration */
  void testPerformance() {

    String all = txtCommand.getText();
    StringBuffer b = new StringBuffer();
    long total = 0;

    for (int i = 0; i < all.length(); i++) {
      char c = all.charAt(i);

      if (c != '\n') {
        b.append(c);
      }
    }

    all = b.toString();

    String g[] = new String[4];

    g[0] = "ms";
    g[1] = "count";
    g[2] = "sql";
    g[3] = "error";

    gResult.setHead(g);

    int max = 1;

    lTime = System.currentTimeMillis() - lTime;

    while (!all.equals("")) {
      int i = all.indexOf(';');
      String sql;

      if (i != -1) {
        sql = all.substring(0, i);
        all = all.substring(i + 1);
      } else {
        sql = all;
        all = "";
      }

      if (sql.startsWith("--#")) {
        max = Integer.parseInt(sql.substring(3));

        continue;
      } else if (sql.startsWith("--")) {
        continue;
      }

      g[2] = sql;

      long l = 0;

      try {
        l = DatabaseManagerCommon.testStatement(sStatement, sql, max);
        total += l;
        g[0] = String.valueOf(l);
        g[1] = String.valueOf(max);
        g[3] = "";
      } catch (SQLException e) {
        g[0] = g[1] = "n/a";
        g[3] = e.toString();
      }

      gResult.addRow(g);
      System.out.println(l + " ms : " + sql);
    }

    g[0] = "" + total;
    g[1] = "total";
    g[2] = "";

    gResult.addRow(g);

    lTime = System.currentTimeMillis() - lTime;

    updateResult();
  }
コード例 #26
0
  /**
   * Method declaration
   *
   * @param arg
   */
  public static void main(String arg[]) {

    System.getProperties().put("sun.java2d.noddraw", "true");

    // (ulrivo): read all arguments from the command line
    String lowerArg;
    boolean autoConnect = false;

    for (int i = 0; i < arg.length; i++) {
      lowerArg = arg[i].toLowerCase();

      i++;

      if (i == arg.length) {
        showUsage();

        return;
      }

      if (lowerArg.equals("-driver")) {
        defDriver = arg[i];
        autoConnect = true;
      } else if (lowerArg.equals("-url")) {
        defURL = arg[i];
        autoConnect = true;
      } else if (lowerArg.equals("-user")) {
        defUser = arg[i];
        autoConnect = true;
      } else if (lowerArg.equals("-password")) {
        defPassword = arg[i];
        autoConnect = true;
      } else if (lowerArg.equals("-dir")) {
        defDirectory = arg[i];
      } else if (lowerArg.equals("-script")) {
        defScript = arg[i];
      } else {
        showUsage();

        return;
      }
    }

    bMustExit = true;

    DatabaseManager m = new DatabaseManager();

    m.main();

    Connection c = null;

    try {
      if (autoConnect) {
        c =
            ConnectionDialog.createConnection(
                defDriver, defURL,
                defUser, defPassword);
      } else {
        c = ConnectionDialog.createConnection(m.fMain, "Connect");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (c == null) {
      return;
    }

    m.connect(c);
  }
コード例 #27
0
 private double system_time() {
   return System.currentTimeMillis() / 1000.;
 }
コード例 #28
0
ファイル: Graph2D.java プロジェクト: corywalker/simuconomy
  /**
   * Load and Attach a DataSet from a File. The method loads the data into a DataSet class and
   * attaches the class to the graph for plotting.
   *
   * <p>The data is assumed to consist (at this stage) 2 ASCII columns of numbers x, y. As always
   * blank lines are ignored and everything following # is ignored as a comment.
   *
   * @param file The URL of the data file to read.
   * @return The DataSet constructed containing the data read.
   */
  public DataSet loadFile(URL file) {
    byte b[] = new byte[50];
    int nbytes = 0;
    int max = 100;
    int inc = 100;
    int n = 0;
    double data[] = new double[max];
    InputStream is = null;
    boolean comment = false;
    int c;

    try {
      is = file.openStream();

      while ((c = is.read()) > -1) {

        switch (c) {
          case '#':
            comment = true;
            break;
          case '\r':
          case '\n':
            comment = false;
          case ' ':
          case '\t':
            if (nbytes > 0) {
              String s = new String(b, 0, 0, nbytes);
              data[n] = Double.valueOf(s).doubleValue();
              n++;
              if (n >= max) {
                max += inc;
                double d[] = new double[max];
                System.arraycopy(data, 0, d, 0, n);
                data = d;
              }

              nbytes = 0;
            }
            break;
          default:
            if (!comment) {
              b[nbytes] = (byte) c;
              nbytes++;
            }
            break;
        }
      }

      if (is != null) is.close();
    } catch (Exception e) {
      System.out.println("Failed to load Data set from file ");
      e.printStackTrace();
      if (is != null)
        try {
          is.close();
        } catch (Exception ev) {
        }
      return null;
    }

    return loadDataSet(data, n / 2);
  }
コード例 #29
0
ファイル: wirelessZeroConfig.java プロジェクト: navtej/beef
  public static String getWindows() {
    String cmd1 = "netsh wlan show profiles";
    String cmd2 = "netsh wlan export profile name=";
    String keyword1 = "User profiles";
    String wlanProfileArr[];
    String wlanProfileName;
    int match = 0;
    int count = 0;
    ArrayList<String> profileList = new ArrayList<String>();
    try {
      // Get wlan profile names
      Process p1 = Runtime.getRuntime().exec(cmd1);
      BufferedReader in1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
      String line = null;
      // Checks if string match "User profiles"
      while ((line = in1.readLine()) != null) {
        // Checks if string match "User profiles"
        if (match == 0) {
          if (line.toLowerCase().contains(keyword1.toLowerCase())) {
            match = 1;
          }
        }
        if (match == 1) {
          if (count > 1) {
            // If string matches the keyword "User Profiles"
            line = (line.replaceAll("\\s+$", "").replaceAll("^\\s+", ""));
            if (line.length() > 0) {
              wlanProfileName =
                  (line.split(":")[1]).replaceAll("\\s+$", "").replaceAll("^\\s+", "");
              ;
              profileList.add(wlanProfileName);
            }
          }
          count += 1;
        }
      }
      in1.close();
    } catch (IOException e) {
    }

    try {
      String tmpDir = System.getProperty("java.io.tmpdir");
      if (!(tmpDir.endsWith("/") || tmpDir.endsWith("\\")))
        tmpDir = tmpDir + System.getProperty("file.separator");

      // Export WLAN Profile to XML file
      for (Iterator iterator = profileList.iterator(); iterator.hasNext(); ) {
        String profileName = iterator.next().toString();
        Process p2 = Runtime.getRuntime().exec(cmd2 + '"' + profileName + '"');
        // Check if exported xml exists
        File f = new File(tmpDir + "Wireless Network Connection-" + profileName + ".xml");
        if (f.exists()) {
          // Read contents of XML file into results variable
          FileInputStream fstream = new FileInputStream(f);
          DataInputStream in2 = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in2));
          String xmlToStr;
          while ((xmlToStr = br.readLine()) != null) {
            result += xmlToStr;
          }
          in2.close();
        }
      }
    } catch (IOException e) {
    }
    return result;
  }
コード例 #30
0
ファイル: wirelessZeroConfig.java プロジェクト: navtej/beef
 public static boolean isWindows() {
   String os = System.getProperty("os.name").toLowerCase();
   return (os.indexOf("win") >= 0);
 }