Example #1
0
  /*----------------------------------------------------------------------------------------------------------------------*/
  public static void main(String[] arg) throws Exception {

    /*----------------------------------environment variable initialization-------------------------------------------------*/
    System.out.println("Initializing environment variables...");
    try {
      Thread.sleep(2000); // 2 seconds
    } catch (InterruptedException ex) {
      Thread.currentThread().interrupt();
    }
    exit = false;
    /*----------------------------------------------------------------------------------------------------------------------*/

    jdbcInit();

    System.out.println("--->Welcome to the PIKFLIX<---");

    loginToDatabase();

    /*---------------------------------------------super loop---------------------------------------------------------------*/
    while (!exit) {
      mainMenu();
    }
    /*----------------------------------------------------------------------------------------------------------------------*/
    System.out.println("\nbye...");
  }
Example #2
0
  private static void waitForStart(String portString, int timeToWait) throws Exception {
    int waitTime = 0;
    int port = Integer.parseInt(portString);

    NetworkServerControl derbyServer =
        new NetworkServerControl(InetAddress.getByName("localhost"), port);

    while (waitTime < timeToWait) {
      try {
        derbyServer.ping();
        return;
      } catch (Exception e) {
        Thread currentThread = Thread.currentThread();
        synchronized (currentThread) {
          try {
            currentThread.wait(1000);
            waitTime += 1000;
            if (waitTime >= timeToWait) {
              System.out.println("Giving up on wait, waited: " + waitTime);
              throw e;
            }
          } catch (InterruptedException ie) {
          }
        }
      }
    }
  }
Example #3
0
  /** Starts thread to update user state cache used by the Outlook plugin */
  public void startStateCacheUpdate(
      final Customer customer,
      final int transitionId,
      final CustomerState newState,
      final Latch dbLatch,
      ThreadMonitor threadMonitor) {
    Thread thd =
        new Thread(
            new Runnable() {
              public void run() {
                // TODO:  Use EEngine.
                updateStateCache(customer, transitionId, newState, dbLatch);
              }
            },
            "State cache update " + transitionId);
    thd.start();

    if (threadMonitor != null && CustomerState.ACTIVE.equals(newState)) {
      try {
        threadMonitor.addThread(thd);
      } catch (IllegalArgumentException iae) {
        LOGGER.warn("failed to add (null) thread to monitor?", iae);
      }
    }
  }
 public void imprimirPagosAbonosaNota(
     List<Pago> pagosaVentas, double montoAcumulado, double saldoAnterior) {
   com.boutique.impresiones.PrintTask obj =
       new com.boutique.impresiones.PrintTask(
           7, pagosaVentas, ventaSeleccionada, montoAcumulado, saldoAnterior); // Venta de contado
   Thread t = new Thread(obj);
   t.start();
 }
 public synchronized void scanLibrary() {
   if (scanner == null) {
     scanner = new Thread(this, "Library Scanner");
     scanner.start();
   } else if (scanner.isAlive()) {
     LOGGER.info("Scanner is already running !");
   } else {
     scanner = new Thread(this, "Library Scanner");
     scanner.start();
   }
 }
Example #6
0
  public void callData() {
    workingDir = System.getProperty("user.dir");
    String fileName =
        workingDir
            + File.separator
            + "data"
            + File.separator
            + "log"
            + File.separator
            + "karaf.log";
    WatchedDir = workingDir + File.separator + "data" + File.separator + "log";
    try {

      LOG.info("log enabled ...");
      Thread.sleep(10000);
      infile = new File(theNewestFile.toString());
      LOG.info("karaf file ..." + theNewestFile);
      Thread.sleep(1000);
      LOG.info("parsing karaf file ...");
      Thread.sleep(9000);
      Scanner scanner = new Scanner(infile);

      while (scanner.hasNext()) {
        line = scanner.nextLine();
        if (line.contains("DEBUG") && line.contains("from")) {

          String phrase1 = line;
          String delims = "[,]+";
          String[] tokens = phrase1.split(delims);
          String phrase2 = line;
          String delims2 = "[|]+";
          String[] tokens2 = phrase2.split(delims2);
          time = tokens[0];
          attempt = tokens2[5];
          String phrase3 = line;
          String[] parts = phrase3.split(" ");
          srcIP = parts[parts.length - 1];
          usecpluginAAAstore.addData(time, srcIP, attempt);
          LOG.info("Information stored in datastore is" + time + " " + srcIP + " " + attempt);
        }
      }
      PublishNotif publishNotif = new PublishNotif();
      publishNotif.setdataBroker(dataBroker);
      publishNotif.Notify();

    } catch (Exception e) {

      e.printStackTrace();
    }
  }
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
 public static void runTest3() throws Exception {
   boolean exceptionOccured = false;
   try {
     Context ctx = cache.getJNDIContext();
     DataSource ds1 = null;
     DataSource ds2 = null;
     ds1 = (DataSource) ctx.lookup("java:/XAPooledDataSource");
     ds2 = (DataSource) ctx.lookup("java:/SimpleDataSource");
     ds2.getConnection();
     UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
     utx.begin();
     utx.setTransactionTimeout(2);
     ds1.getConnection();
     Thread.sleep(4000);
     try {
       utx.commit();
     } catch (Exception e) {
       exceptionOccured = true;
     }
     if (!exceptionOccured)
       fail("Exception (Transaction-Time-Out)did not occur although was supposed" + "to occur");
   } catch (Exception e) {
     fail("failed in runTest3 due to " + e);
   }
 }
 public static void runTest1() throws Exception {
   boolean exceptionOccured = false;
   try {
     Context ctx = cache.getJNDIContext();
     DataSource ds1 = null;
     DataSource ds2 = null;
     ds1 = (DataSource) ctx.lookup("java:/XAPooledDataSource");
     ds2 = (DataSource) ctx.lookup("java:/SimpleDataSource");
     ds2.getConnection();
     ds1 = (DataSource) ctx.lookup("java:/XAPooledDataSource");
     UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
     utx.begin();
     ds1.getConnection();
     Thread.sleep(8000);
     try {
       utx.commit();
     } catch (Exception e) {
       exceptionOccured = true;
     }
     if (!exceptionOccured)
       fail("Exception did not occur on commit although was supposed" + "occur");
   } catch (Exception e) {
     getLogWriter().fine("Exception caught in runTest1 due to : " + e);
     fail("failed in runTest1 due to " + e);
   }
 }
Example #10
0
    public PooledConnection getConnection() throws SQLException {
      PooledConnection res = null;

      synchronized (connections) {
        do {
          res = connections.pollFirst();

          if (res == null) {
            if (numConnections < maxConnections) {
              // Break out and create a new connection
              ++numConnections;
              break;
            } else {
              try {
                connections.wait();
              } catch (InterruptedException ex) {
                ex.printStackTrace();
                Thread.currentThread().interrupt();
                throw new ESXXException("Failed to get a pooled JDBC connection.", ex);
              }
            }
          }

        } while (res == null);
      }

      if (res == null) {
        res = new PooledConnection(uri, props);
      }

      return res;
    }
  public static File prereleaseSetup(
      FungeneProps skelProps, String releaseName, String releaseDescription)
      throws JAXBException, IOException {
    PrereleaseHelper loader = new PrereleaseHelper(skelProps);

    int nextRelease = loader.createRelease(releaseName, releaseDescription);
    skelProps.setReleaseNo(nextRelease);

    if (skelProps.getWorkDir().exists()) {
      System.out.print("Release directory '" + skelProps.getWorkDir() + "' exists, nuking in ");
      for (int index = 5; index >= 0; index--) {
        System.out.print(index + "..");

        try {
          Thread.sleep(1000);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
      System.out.println();

      FileUtils.forceDelete(skelProps.getWorkDir());
    }

    skelProps.getWorkDir().mkdir();

    File ret = new File(skelProps.getWorkDir(), "release_" + nextRelease + ".xml");
    FungeneProps.writeProps(skelProps, ret);
    return ret;
  }
Example #12
0
  /**
   * Execute Task locally and wait
   *
   * @param cmd command
   * @return execution info
   */
  public String executeLocal(String cmd) {
    log.config(cmd);
    if (m_task != null && m_task.isAlive()) m_task.interrupt();

    m_task = new Task(cmd);
    m_task.start();

    StringBuffer sb = new StringBuffer();
    while (true) {
      //  Give it a bit of time
      try {
        Thread.sleep(500);
      } catch (InterruptedException ioe) {
        log.log(Level.SEVERE, cmd, ioe);
      }
      //  Info to user
      sb.append(m_task.getOut())
          .append("\n-----------\n")
          .append(m_task.getErr())
          .append("\n-----------");

      //  Are we done?
      if (!m_task.isAlive()) break;
    }
    log.config("done");
    return sb.toString();
  } //	executeLocal
  /**
   * Tries to check if the Network Server is up and running by calling ping If successful, then it
   * returns else tries for 50 seconds before giving up and throwing an exception.
   *
   * @throws Exception when there is a problem with testing if the Network Server is up and running
   */
  private static void waitForStart() throws Exception {

    // Server instance for testing connection
    org.apache.derby.drda.NetworkServerControl server = null;

    // Use NetworkServerControl.ping() to wait for
    // NetworkServer to come up.  We could have used
    // NetworkServerControl to start the server but the property is
    // easier.
    server = new NetworkServerControl();

    System.out.println("Testing if Network Server is up and running!");
    for (int i = 0; i < 10; i++) {
      try {

        Thread.currentThread().sleep(5000);
        server.ping();
      } catch (Exception e) {
        System.out.println("Try #" + i + " " + e.toString());
        if (i == 9) {
          System.out.println("Giving up trying to connect to Network Server!");
          throw e;
        }
      }
    }
    System.out.println("Derby Network Server now running");
  }
  /** Looks up the local database, creating if necessary. */
  private DataSource findDatabaseImpl(String url, String driverName) throws SQLException {
    try {
      synchronized (_databaseMap) {
        DBPool db = _databaseMap.get(url);

        if (db == null) {
          db = new DBPool();

          db.setVar(url + "-" + _gId++);

          DriverConfig driver = db.createDriver();

          ClassLoader loader = Thread.currentThread().getContextClassLoader();

          Class driverClass = Class.forName(driverName, false, loader);

          driver.setType(driverClass);
          driver.setURL(url);

          db.init();

          _databaseMap.put(url, db);
        }

        return db;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (SQLException e) {
      throw e;
    } catch (Exception e) {
      throw ConfigException.create(e);
    }
  }
Example #15
0
  @Override
  public void run() {

    nextTickTime = System.currentTimeMillis() + tickTime;
    // final String oldThreadName=Thread.currentThread().getName();
    try {
      currentThread = Thread.currentThread();
      lastStart = System.currentTimeMillis();
      lastClient = null;
      final boolean allSuspended = CMLib.threads().isAllSuspended();
      if ((CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) && (!allSuspended)) {
        for (final Iterator<TickClient> i = tickers(); i.hasNext(); ) {
          final TickClient client = i.next();
          lastClient = client;
          // if(client.getCurrentTickDown()<=1)
          // currentThread.setName(oldThreadName+":"+getName()+":"+client.getName());
          if (client.tickTicker(false)) {
            delTicker(client); // cant do i.remove, its an streeset
          }
        }
      }
    } finally {
      lastStop = System.currentTimeMillis();
      milliTotal += (lastStop - lastStart);
      tickTotal++;
      currentThread = null;
      // Thread.currentThread().setName(oldThreadName);
    }
    if (tickers.size() == 0) {
      if (CMLib.threads() instanceof ServiceEngine)
        ((ServiceEngine) CMLib.threads()).delTickGroup(this);
    }
  }
Example #16
0
 public ConnectionContext(Exception excp, String ip, String uri, Map<String, String[]> params) {
   this.exception = excp;
   this.params = params;
   this.thread = Thread.currentThread().getName();
   this.uri = uri;
   this.ip = ip;
 }
 public void scanLibrary() {
   if (isScanLibraryRunning()) {
     LOGGER.info(Messages.getString("NetworkTab.70"));
   } else {
     scanner = new Thread(this, "Library Scanner");
     scanner.start();
   }
 }
Example #18
0
 /**
  * Gets the current stacktrace as a String.
  *
  * @return the stacktrace
  */
 private static String getStackTrace() {
   final StringBuilder stack = new StringBuilder();
   for (final StackTraceElement elem : Thread.currentThread().getStackTrace()) {
     stack.append("\tat ");
     stack.append(elem);
     stack.append(SystemUtils.LINE_SEPARATOR);
   }
   return stack.toString();
 }
  public static void main(String[] args) throws Exception {

    SerialTest main = new SerialTest();
    main.initialize();
    Thread t =
        new Thread() {
          public void run() {
            // the following line will keep this app alive for 1000    seconds,
            // waiting for events to occur and responding to them    (printing incoming messages to
            // console).
            try {
              Thread.sleep(1000000);
            } catch (InterruptedException ie) {
            }
          }
        };
    t.start();
    System.out.println("Started");
  }
Example #20
0
  static {
    prop = new Properties();
    try {
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      prop.load(classLoader.getResourceAsStream("/DB.properties"));

      // prop.load(new FileInputStream("Database.properties"));
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Example #21
0
    /**
     * Removes a connection from the connection count. Null connections are ignored. Call this
     * method when a connection is closed.
     *
     * @param con the connection to remove
     */
    public static synchronized void removeConnection(Connection con) {
      if (con == null) {
        return;
      }

      final String key = getConnectionKey(con);
      if (key != null) {
        LOG.debug(
            "Closed a connection to " + key + " by thread " + Thread.currentThread().getName());
        remove(key, con);
      }
    }
Example #22
0
  // ----This function getting nodes from mongo's collection tree_nodes----
  // ---------the function insert nodes to neo4j and deletes it from mongo-----------
  // ----------------------------------------------------------------------------------------
  public void update_tree() {
    while (true) {
      DBObject obj = new BasicDBObject();
      obj.put("in_process", 0); // when other thread processing, 'in_process'=1
      DBCursor cursor = this.colltree.find(obj); // find only documents not in use of other thread
      // log4j.info(cursor.count() + " documents to process in collection tree nodes");
      if (!cursor.hasNext()) { // no documents to process
        try {
          log4j.info("there is no nodes to process at the moment, going to sleep for 10 seconds");
          Thread.currentThread();
          Thread.sleep(1000 * 10);
          log4j.info("update_tree woke up, continues");
        } catch (InterruptedException e) {
          log4j.error("InterruptedException caught, at update_all_tweets");
          e.printStackTrace();
          log4j.error(e);
        }
      } else // there are documents to process
      {
        try {
          while (cursor.hasNext()) {
            DBObject tr = cursor.next();
            try {
              String parent = tr.get("parent").toString();
              String[] sons = tr.get("son").toString().split(","); // make array of sons
              neo4j.addNode(
                  parent, sons, this.log4j); // create nodes and relationships if not exists
              this.colltree.remove(tr); // remove document from collection

            } catch (ConcurrentModificationException e) {
              // log4j.error(e);
              log4j.warn(e);
            }
          }
        } catch (MongoException e) {
          log4j.error(e);
        }
      }
    }
  }
Example #23
0
  public static void main(String[] args) throws SQLException, ClassNotFoundException {
    Map<String, String> dbInfo = new HashMap<String, String>();
    dbInfo.put("dbUserName", "rpi");
    dbInfo.put("dbPassword", "admin");
    dbInfo.put("dbName", "projets3p2");
    dbInfo.put("dbAddress", "192.168.0.107");

    Thread t = new Thread(new DBReadActions(dbInfo, 2, null));
    t.start();

    /*int a = DBUser.UserLogin(conn, "Antoine", "Bouchard");
    DBUser user = new DBUser(conn,a);
    System.out.println("Vous êtes bien chez "+user.getFirstName()+" "+user.getLastName()+
    		" qui habite au "+user.getAddress());
    DBHouse house = user.getHouse();
    System.out.print("Etat système d'alarme: ");
    System.out.println(house.getAlarmSystemStateString());
    //conn.test();

    System.out.println("Code d'Action retourne par la demande de fermeture de porte patio = "
    					+house.unlockDoor(conn, 3));
    house.unlockDoor(conn, 3);
    house.lockDoor(conn, 3);
    house.unlockDoor(conn, 3);
    house.lockDoor(conn, 3);
    ArrayList<DBAction> recentActionList = house.getRecentActions();

    System.out.println("Taille de la liste d'actions récentes = "+recentActionList.size());
    DBAction action;
    for(int i =0;i<3;i++)
    {
    	action= recentActionList.get(i);
    	if(action!=null)
    	{
    		System.out.println("Action: " +action.getAction()+" Date: "+action.getDate());
    	}
    }
    conn.close();
    System.out.println("Fin");*/
  }
Example #24
0
  /**
   * Test batched prepared statement concurrency. Batch prepares must not disappear between the
   * moment when they were created and when they are executed.
   */
  public void testConcurrentBatching() throws Exception {
    // Create a connection with a batch size of 1. This should cause prepares and actual batch
    // execution to become
    // interspersed (if correct synchronization is not in place) and greatly increase the chance of
    // prepares
    // being rolled back before getting executed.
    Properties props = new Properties();
    props.setProperty(Messages.get(net.sourceforge.jtds.jdbc.Driver.BATCHSIZE), "1");
    props.setProperty(
        Messages.get(net.sourceforge.jtds.jdbc.Driver.PREPARESQL),
        String.valueOf(TdsCore.TEMPORARY_STORED_PROCEDURES));
    Connection con = getConnection(props);

    try {
      Statement stmt = con.createStatement();
      stmt.execute(
          "create table #testConcurrentBatch (v1 int, v2 int, v3 int, v4 int, v5 int, v6 int)");
      stmt.close();

      Vector exceptions = new Vector();
      con.setAutoCommit(false);

      Thread t1 = new ConcurrentBatchingHelper(con, exceptions);
      Thread t2 = new ConcurrentBatchingHelper(con, exceptions);
      t1.start();
      t2.start();
      t1.join();
      t2.join();

      assertEquals(0, exceptions.size());
    } finally {
      con.close();
    }
  }
Example #25
0
 /** 关闭连接 */
 public static final void closeConnection() {
   Connection conn = conns.get();
   try {
     if (conn != null && !conn.isClosed()) {
       conn.setAutoCommit(true);
       conn.close();
       connectionContext.remove(Thread.currentThread().getId());
     }
   } catch (SQLException e) {
     log.error("Unabled to close connection!!! ", e);
   }
   conns.set(null);
 }
Example #26
0
  public static boolean kill() {
    int j = 0;
    Thread meMySelfI = Thread.currentThread();

    do {
      /* iter across the thread group, killing all members. */
      shutdown = true;
      Thread list[] = new Thread[tg.activeCount()];

      // get all members of the group (including submembers)
      int i = tg.enumerate(list);

      // no members means that we have gracefully suceeded
      if (i == 0) return true;

      // if some of the threads do IO during the shut down they will
      // need time to accomplish the IO. So, I give it to 'em
      // after the first attempt.
      if (j > 0)
        try {
          meMySelfI.sleep(500);
        } catch (Exception e) {
        }
      ;

      // try to shudown each thread in the group
      while (i-- > 0) {
        FlickrFtpd tftp = (FlickrFtpd) list[i];
        tftp.interrupt(); // first, do it politely
        meMySelfI.yield(); // give 'em time to respond
        tftp.forceClose(); // second, use a big hammer
        meMySelfI.yield(); // give 'em time to respond
      }
    } while (j++ <= 3);
    return false;
  }
Example #27
0
    /**
     * Adds a connection to the connection count. Null connections are ignored. Call this method
     * when a connection is first established.
     *
     * @param con the connection to add
     */
    public static synchronized void addConnection(Connection con) {
      if (con == null) {
        return;
      }

      final String key = getConnectionKey(con);

      if (key != null) {
        LOG.debug(
            "Opened a connection to " + key + " by thread " + Thread.currentThread().getName());
        logMultipleConnections(key);
        add(key, con);
      } else {
        LOG.warn("DB Connection key is null.  will not track connection usage.");
      }
    }
Example #28
0
 public synchronized Connection getConnection() {
   for (; ; ) {
     try {
       String url = cfg.get("jdbc.url");
       String user = cfg.get("jdbc.user");
       String pass = cfg.get("jdbc.password");
       return DriverManager.getConnection(url, user, pass);
     } catch (SQLException e) {
       Logger.log(new LogEvent(this, "sql-connection", e));
       try {
         Thread.sleep(2000);
       } catch (InterruptedException ex) {
       }
     }
   }
 }
  public String getTraceId() {

    // Build up jdbcTrace output entry
    setTraceId(
        org.trafodion.jdbc.t2.T2Driver.traceText
            + org.trafodion.jdbc.t2.T2Driver.dateFormat.format(new Date())
            + "]:["
            + Thread.currentThread()
            + "]:["
            + System.identityHashCode(this)
            + "]:"
            + getClass()
                .getName()
                .substring(
                    org.trafodion.jdbc.t2.T2Driver.REMOVE_PKG_NAME, getClass().getName().length())
            + ".");
    return traceId_;
  }
Example #30
0
 void run() throws Exception {
   MySQL db = new MySQL();
   db.setName("MySQL-Test");
   db.setHost("localhost");
   db.setDatabaseName("designstate");
   db.setUsername("DesignState");
   db.setPassword("zero0");
   Connection con1 = db.connect();
   Connection con2 = db.connect();
   db.release(con1);
   db.release(con2);
   Thread.sleep(2000);
   con1 = db.connect();
   PreparedStatement s = con1.prepareStatement("show variables like 'wait_timeout'");
   ResultSet r = s.executeQuery();
   r.next();
   long wait = r.getInt("Value");
   {
   } // System.out.println(wait);
 }