/** {@inheritDoc} */
  @Override
  public void txEnd(GridCacheTx tx, boolean commit) throws GridException {
    init();

    Session ses = tx.removeMeta(ATTR_SES);

    if (ses != null) {
      Transaction hTx = ses.getTransaction();

      if (hTx != null) {
        try {
          if (commit) {
            ses.flush();

            hTx.commit();
          } else hTx.rollback();

          if (log.isDebugEnabled())
            log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']');
        } catch (HibernateException e) {
          throw new GridException(
              "Failed to end transaction [xid=" + tx.xid() + ", commit=" + commit + ']', e);
        } finally {
          ses.close();
        }
      }
    }
  }
  /**
   * Gets Hibernate session.
   *
   * @param tx Cache transaction.
   * @return Session.
   */
  Session session(@Nullable GridCacheTx tx) {
    Session ses;

    if (tx != null) {
      ses = tx.meta(ATTR_SES);

      if (ses == null) {
        ses = sesFactory.openSession();

        ses.beginTransaction();

        // Store session in transaction metadata, so it can be accessed
        // for other operations on the same transaction.
        tx.addMeta(ATTR_SES, ses);

        if (log.isDebugEnabled())
          log.debug("Hibernate session open [ses=" + ses + ", tx=" + tx.xid() + "]");
      }
    } else {
      ses = sesFactory.openSession();

      ses.beginTransaction();
    }

    return ses;
  }
  /** {@inheritDoc} */
  @SuppressWarnings({"unchecked", "RedundantTypeArguments"})
  @Override
  public V load(@Nullable GridCacheTx tx, K key) throws GridException {
    init();

    if (log.isDebugEnabled()) log.debug("Store load [key=" + key + ", tx=" + tx + ']');

    Session ses = session(tx);

    try {
      GridCacheHibernateBlobStoreEntry entry =
          (GridCacheHibernateBlobStoreEntry)
              ses.get(GridCacheHibernateBlobStoreEntry.class, toBytes(key));

      if (entry == null) return null;

      return fromBytes(entry.getValue());
    } catch (HibernateException e) {
      rollback(ses, tx);

      throw new GridException("Failed to load value from cache store with key: " + key, e);
    } finally {
      end(ses, tx);
    }
  }
  /** {@inheritDoc} */
  @Override
  public void put(@Nullable GridCacheTx tx, K key, @Nullable V val) throws GridException {
    init();

    if (log.isDebugEnabled())
      log.debug("Store put [key=" + key + ", val=" + val + ", tx=" + tx + ']');

    if (val == null) {
      remove(tx, key);

      return;
    }

    Session ses = session(tx);

    try {
      GridCacheHibernateBlobStoreEntry entry =
          new GridCacheHibernateBlobStoreEntry(toBytes(key), toBytes(val));

      ses.saveOrUpdate(entry);
    } catch (HibernateException e) {
      rollback(ses, tx);

      throw new GridException(
          "Failed to put value to cache store [key=" + key + ", val" + val + "]", e);
    } finally {
      end(ses, tx);
    }
  }
  /**
   * Ends hibernate session.
   *
   * @param ses Hibernate session.
   * @param tx Cache ongoing transaction.
   */
  private void end(Session ses, GridCacheTx tx) {
    // Commit only if there is no cache transaction,
    // otherwise txEnd() will do all required work.
    if (tx == null) {
      Transaction hTx = ses.getTransaction();

      if (hTx != null && hTx.isActive()) hTx.commit();

      ses.close();
    }
  }
  /** {@inheritDoc} */
  @Override
  public void onSessionStart(CacheStoreSession ses) {
    if (ses.attachment() == null) {
      try {
        Session hibSes = sesFactory.openSession();

        ses.attach(hibSes);

        if (ses.isWithinTransaction()) hibSes.beginTransaction();
      } catch (HibernateException e) {
        throw new CacheWriterException(
            "Failed to start store session [tx=" + ses.transaction() + ']', e);
      }
    }
  }
Ejemplo n.º 7
0
  /**
   * Constructor.
   *
   * @param session Session object for this service
   * @param urlname URLName object to be used for this service
   */
  protected Service(Session session, URLName urlname) {
    this.session = session;
    debug = session.getDebug();
    url = urlname;

    /*
     * Initialize the URLName with default values.
     * The URLName will be updated when connect is called.
     */
    String protocol = null;
    String host = null;
    int port = -1;
    String user = null;
    String password = null;
    String file = null;

    // get whatever information we can from the URL
    // XXX - url should always be non-null here, Session
    //       passes it into the constructor
    if (url != null) {
      protocol = url.getProtocol();
      host = url.getHost();
      port = url.getPort();
      user = url.getUsername();
      password = url.getPassword();
      file = url.getFile();
    }

    // try to get protocol-specific default properties
    if (protocol != null) {
      if (host == null) host = session.getProperty("mail." + protocol + ".host");
      if (user == null) user = session.getProperty("mail." + protocol + ".user");
    }

    // try to get mail-wide default properties
    if (host == null) host = session.getProperty("mail.host");

    if (user == null) user = session.getProperty("mail.user");

    // try using the system username
    if (user == null) {
      try {
        user = System.getProperty("user.name");
      } catch (SecurityException sex) {
        // XXX - it's not worth creating a MailLogger just for this
        // logger.log(Level.CONFIG, "Can't get user.name property", sex);
      }
    }

    url = new URLName(protocol, host, port, file, user, password);

    // create or choose the appropriate event queue
    String scope = session.getProperties().getProperty("mail.event.scope", "folder");
    Executor executor = (Executor) session.getProperties().get("mail.event.executor");
    if (scope.equalsIgnoreCase("application")) q = EventQueue.getApplicationEventQueue(executor);
    else if (scope.equalsIgnoreCase("session")) q = session.getEventQueue();
    else // if (scope.equalsIgnoreCase("store") ||
      //     scope.equalsIgnoreCase("folder"))
      q = new EventQueue(executor);
  }
Ejemplo n.º 8
0
  private DarkBotMCSpambot(MinecraftBotData data, String owner)
      throws AuthenticationException, UnsupportedProtocolException {
    super(data);
    synchronized (bots) {
      bots.add(this);
    }
    addOwner(owner);
    addBackend(new ChatBackend(this));

    TaskManager taskManager = bot.getTaskManager();
    taskManager.registerTask(new FallTask(bot));
    taskManager.registerTask(new FollowTask(bot));
    taskManager.registerTask(new DefendTask(bot));
    taskManager.registerTask(new AttackTask(bot));
    taskManager.registerTask(new HostileTask(bot));
    taskManager.registerTask(new EatTask(bot));

    commandManager.register(new AttackAllCommand(this));
    commandManager.register(new AttackCommand(this));
    commandManager.register(new CalcCommand(this));
    commandManager.register(new ChatDelayCommand(this));
    commandManager.register(new DropAllCommand(this));
    commandManager.register(new DropCommand(this));
    commandManager.register(new DropIdCommand(this));
    commandManager.register(new EquipCommand(this));
    commandManager.register(new FollowCommand(this));
    commandManager.register(new InteractCommand(this));
    commandManager.register(new OwnerCommand(this));
    commandManager.register(new QuitCommand(this));
    commandManager.register(new SayCommand(this));
    commandManager.register(new SetWalkCommand(this));
    commandManager.register(new SpamCommand(this));
    commandManager.register(new StatusCommand(this));
    commandManager.register(new StopCommand(this));
    commandManager.register(new SwitchCommand(this));
    commandManager.register(new ToolCommand(this));
    commandManager.register(new WalkCommand(this));

    connectionHandler = bot.getConnectionHandler();
    Session session = bot.getSession();
    System.out.println("[" + session.getUsername() + "] Done! (" + bots.size() + ")");
  }
  /** {@inheritDoc} */
  @SuppressWarnings({"JpaQueryApiInspection", "JpaQlInspection"})
  @Override
  public void remove(@Nullable GridCacheTx tx, K key) throws GridException {
    init();

    if (log.isDebugEnabled()) log.debug("Store remove [key=" + key + ", tx=" + tx + ']');

    Session ses = session(tx);

    try {
      Object obj = ses.get(GridCacheHibernateBlobStoreEntry.class, toBytes(key));

      if (obj != null) ses.delete(obj);
    } catch (HibernateException e) {
      rollback(ses, tx);

      throw new GridException("Failed to remove value from cache store with key: " + key, e);
    } finally {
      end(ses, tx);
    }
  }
  /** {@inheritDoc} */
  @Override
  public void onSessionEnd(CacheStoreSession ses, boolean commit) {
    Session hibSes = ses.attach(null);

    if (hibSes != null) {
      try {
        Transaction tx = hibSes.getTransaction();

        if (commit) {
          hibSes.flush();

          if (tx.isActive()) tx.commit();
        } else if (tx.isActive()) tx.rollback();
      } catch (HibernateException e) {
        throw new CacheWriterException(
            "Failed to end store session [tx=" + ses.transaction() + ']', e);
      } finally {
        hibSes.close();
      }
    }
  }
Ejemplo n.º 11
0
  @Override
  public int run() throws Exception {
    // Default values of command line arguments
    String host = DEFAULT_HOST;
    int port = DEFAULT_PORT;
    String user = DEFAULT_USER;
    String pass = DEFAULT_PASS;
    String destination = DEFAULT_DESTINATION;
    String file = ""; // No default -- if not given, don't read/write file
    int sleep = 0;
    boolean showpercent = false;
    int batchSize = 0;
    int length = 500; // Length of message generated internally
    String properties = "";
    String format = "short";
    String durable = null;

    int n = 1; // n is the number of messages to process, or a specific
    //   message number, depending on content
    String url = ""; // No default -- if not given, don't use it

    String[] nonSwitchArgs = cl.getArgs();
    if (nonSwitchArgs.length > 0) n = Integer.parseInt(nonSwitchArgs[0]);

    String _destination = cl.getOptionValue("destination");
    if (_destination != null) destination = _destination;

    String _host = cl.getOptionValue("host");
    if (_host != null) host = _host;

    String _port = cl.getOptionValue("port");
    if (_port != null) port = Integer.parseInt(_port);

    String _file = cl.getOptionValue("file");
    if (_file != null) file = _file;

    String _user = cl.getOptionValue("user");
    if (_user != null) user = _user;

    String _pass = cl.getOptionValue("password");
    if (_pass != null) pass = _pass;

    String _url = cl.getOptionValue("url");
    if (_url != null) url = _url;

    String _sleep = cl.getOptionValue("sleep");
    if (_sleep != null) sleep = Integer.parseInt(_sleep);

    if (cl.hasOption("percent")) showpercent = true;

    String _batchSize = cl.getOptionValue("batch");
    if (_batchSize != null) batchSize = Integer.parseInt(_batchSize);

    String _L = cl.getOptionValue("length");
    if (_L != null) length = Integer.parseInt(_L);

    String _properties = cl.getOptionValue("properties");
    if (_properties != null) properties = _properties;

    String _durable = cl.getOptionValue("durable");
    if (_durable != null) durable = _durable;

    boolean batch = false;
    if (batchSize != 0) batch = true;

    String _format = cl.getOptionValue("format");
    if (_format != null) format = _format;

    ActiveMQConnectionFactory factory = getFactory(host, port, url);

    Connection connection = factory.createConnection(user, pass);

    if (durable != null) connection.setClientID(durable);

    connection.start();

    Session session = connection.createSession(batch, Session.AUTO_ACKNOWLEDGE);

    Topic topic = session.createTopic(destination);

    MessageConsumer consumer = null;
    if (durable != null) consumer = session.createDurableSubscriber(topic, "amqutil");
    else consumer = session.createConsumer(topic);

    int oldpercent = 0;
    for (int i = 0; i < n; i++) {
      javax.jms.Message message = consumer.receive();

      if (batch) if ((i + 1) % batchSize == 0) session.commit();

      if (sleep != 0) Thread.sleep(sleep);

      JMSUtil.outputMessage(format, message, file);

      if (showpercent) {
        int percent = i * 100 / n;
        if (percent != oldpercent) System.out.println("" + percent + "%");
        oldpercent = percent;
      }
    }

    if (batch) session.commit();

    connection.close();

    return 0;
  }
Ejemplo n.º 12
0
  /**
   * Similar to connect(host, user, password) except a specific port can be specified.
   *
   * @param host the host to connect to
   * @param port the port to connect to (-1 means the default port)
   * @param user the user name
   * @param password this user's password
   * @exception AuthenticationFailedException for authentication failures
   * @exception MessagingException for other failures
   * @exception IllegalStateException if the service is already connected
   * @see #connect(java.lang.String, java.lang.String, java.lang.String)
   * @see javax.mail.event.ConnectionEvent
   */
  public synchronized void connect(String host, int port, String user, String password)
      throws MessagingException {

    // see if the service is already connected
    if (isConnected()) throw new IllegalStateException("already connected");

    PasswordAuthentication pw;
    boolean connected = false;
    boolean save = false;
    String protocol = null;
    String file = null;

    // get whatever information we can from the URL
    // XXX - url should always be non-null here, Session
    //       passes it into the constructor
    if (url != null) {
      protocol = url.getProtocol();
      if (host == null) host = url.getHost();
      if (port == -1) port = url.getPort();

      if (user == null) {
        user = url.getUsername();
        if (password == null) // get password too if we need it
        password = url.getPassword();
      } else {
        if (password == null && user.equals(url.getUsername()))
          // only get the password if it matches the username
          password = url.getPassword();
      }

      file = url.getFile();
    }

    // try to get protocol-specific default properties
    if (protocol != null) {
      if (host == null) host = session.getProperty("mail." + protocol + ".host");
      if (user == null) user = session.getProperty("mail." + protocol + ".user");
    }

    // try to get mail-wide default properties
    if (host == null) host = session.getProperty("mail.host");

    if (user == null) user = session.getProperty("mail.user");

    // try using the system username
    if (user == null) {
      try {
        user = System.getProperty("user.name");
      } catch (SecurityException sex) {
        // XXX - it's not worth creating a MailLogger just for this
        // logger.log(Level.CONFIG, "Can't get user.name property", sex);
      }
    }

    // if we don't have a password, look for saved authentication info
    if (password == null && url != null) {
      // canonicalize the URLName
      setURLName(new URLName(protocol, host, port, file, user, null));
      pw = session.getPasswordAuthentication(getURLName());
      if (pw != null) {
        if (user == null) {
          user = pw.getUserName();
          password = pw.getPassword();
        } else if (user.equals(pw.getUserName())) {
          password = pw.getPassword();
        }
      } else save = true;
    }

    // try connecting, if the protocol needs some missing
    // information (user, password) it will not connect.
    // if it tries to connect and fails, remember why for later.
    AuthenticationFailedException authEx = null;
    try {
      connected = protocolConnect(host, port, user, password);
    } catch (AuthenticationFailedException ex) {
      authEx = ex;
    }

    // if not connected, ask the user and try again
    if (!connected) {
      InetAddress addr;
      try {
        addr = InetAddress.getByName(host);
      } catch (UnknownHostException e) {
        addr = null;
      }
      pw = session.requestPasswordAuthentication(addr, port, protocol, null, user);
      if (pw != null) {
        user = pw.getUserName();
        password = pw.getPassword();

        // have the service connect again
        connected = protocolConnect(host, port, user, password);
      }
    }

    // if we're not connected by now, we give up
    if (!connected) {
      if (authEx != null) throw authEx;
      else if (user == null)
        throw new AuthenticationFailedException("failed to connect, no user name specified?");
      else if (password == null)
        throw new AuthenticationFailedException("failed to connect, no password specified?");
      else throw new AuthenticationFailedException("failed to connect");
    }

    setURLName(new URLName(protocol, host, port, file, user, password));

    if (save)
      session.setPasswordAuthentication(getURLName(), new PasswordAuthentication(user, password));

    // set our connected state
    setConnected(true);

    // finally, deliver the connection event
    notifyConnectionListeners(ConnectionEvent.OPENED);
  }
Ejemplo n.º 13
0
 public void onResponse(int msgid, MessagePackObject error, MessagePackObject result) {
   session.onResponse(msgid, result, error);
 }
Ejemplo n.º 14
0
  public Session _dc_run(String login, String password) throws InterruptedException {
    String authserver = (Config.authserv == null) ? address : Config.authserv;
    retry:
    do {
      byte[] cookie;
      AuthClient auth = null;
      try {
        try {
          auth = new AuthClient(authserver, login);
        } catch (UnknownHostException e) {
          _dc_log("Could not locate server");
          continue retry;
        }
        if (!auth.trypasswd(password)) {
          auth.close();
          password = "";
          _dc_log("Username or password incorrect");
          continue retry;
        }
        cookie = auth.cookie;

      } catch (java.io.IOException e) {
        ui.uimsg(1, "error", e.getMessage());
        continue retry;
      } finally {
        try {
          if (auth != null) auth.close();
        } catch (java.io.IOException e) {
        }
      }
      _dc_log("Connecting...");
      try {
        sess = new Session(InetAddress.getByName(address), login, cookie);
      } catch (UnknownHostException e) {
        _dc_log("Could not locate server");
        continue retry;
      }
      Thread.sleep(100);
      while (true) {
        if (sess.state == "") {
          break retry;
        } else if (sess.connfailed != 0) {
          String error;
          switch (sess.connfailed) {
            case 1:
              error = "Invalid authentication token";
              break;
            case 2:
              error = "Already logged in";
              break;
            case 3:
              error = "Could not connect to server";
              break;
            case 4:
              error = "This client is too old";
              break;
            case 5:
              error = "Authentication token expired";
              break;
            default:
              error = "Connection failed";
              break;
          }
          _dc_log(error);
          sess = null;
          continue retry;
        }
        synchronized (sess) {
          sess.wait();
        }
      }
    } while (true);
    return sess;
  }
Ejemplo n.º 15
0
 public Session run(HavenPanel hp) throws InterruptedException {
   ui = hp.newui(null);
   ui.setreceiver(this);
   ui.bind(new LoginScreen(ui.root), 1);
   String username;
   boolean savepw = false;
   Utils.setpref("password", "");
   byte[] token = null;
   if (Utils.getpref("savedtoken", "").length() == 64)
     token = Utils.hex2byte(Utils.getpref("savedtoken", null));
   username = Utils.getpref("username", "");
   String authserver = (Config.authserv == null) ? address : Config.authserv;
   retry:
   do {
     byte[] cookie;
     if (initcookie != null) {
       username = inituser;
       cookie = initcookie;
       initcookie = null;
     } else if (token != null) {
       savepw = true;
       ui.uimsg(1, "token", username);
       while (true) {
         Message msg;
         synchronized (msgs) {
           while ((msg = msgs.poll()) == null) msgs.wait();
         }
         if (msg.id == 1) {
           if (msg.name == "login") {
             break;
           } else if (msg.name == "forget") {
             token = null;
             Utils.setpref("savedtoken", "");
             continue retry;
           }
         }
       }
       ui.uimsg(1, "prg", "Authenticating...");
       AuthClient auth = null;
       try {
         auth = new AuthClient(authserver, username);
         if (!auth.trytoken(token)) {
           auth.close();
           token = null;
           Utils.setpref("savedtoken", "");
           ui.uimsg(1, "error", "Invalid save");
           continue retry;
         }
         cookie = auth.cookie;
       } catch (java.io.IOException e) {
         ui.uimsg(1, "error", e.getMessage());
         continue retry;
       } finally {
         try {
           if (auth != null) auth.close();
         } catch (java.io.IOException e) {
         }
       }
     } else {
       String password;
       ui.uimsg(1, "passwd", username, savepw);
       while (true) {
         Message msg;
         synchronized (msgs) {
           while ((msg = msgs.poll()) == null) msgs.wait();
         }
         if (msg.id == 1) {
           if (msg.name == "login") {
             username = (String) msg.args[0];
             password = (String) msg.args[1];
             savepw = (Boolean) msg.args[2];
             break;
           }
         }
       }
       ui.uimsg(1, "prg", "Authenticating...");
       AuthClient auth = null;
       try {
         try {
           auth = new AuthClient(authserver, username);
         } catch (UnknownHostException e) {
           ui.uimsg(1, "error", "Could not locate server");
           continue retry;
         }
         if (!auth.trypasswd(password)) {
           auth.close();
           password = "";
           ui.uimsg(1, "error", "Username or password incorrect");
           continue retry;
         }
         cookie = auth.cookie;
         if (savepw) {
           if (auth.gettoken()) Utils.setpref("savedtoken", Utils.byte2hex(auth.token));
         }
       } catch (java.io.IOException e) {
         ui.uimsg(1, "error", e.getMessage());
         continue retry;
       } finally {
         try {
           if (auth != null) auth.close();
         } catch (java.io.IOException e) {
         }
       }
     }
     ui.uimsg(1, "prg", "Connecting...");
     try {
       sess = new Session(InetAddress.getByName(address), username, cookie);
     } catch (UnknownHostException e) {
       ui.uimsg(1, "error", "Could not locate server");
       continue retry;
     }
     Thread.sleep(100);
     while (true) {
       if (sess.state == "") {
         Utils.setpref("username", username);
         ui.destroy(1);
         break retry;
       } else if (sess.connfailed != 0) {
         String error;
         switch (sess.connfailed) {
           case 1:
             error = "Invalid authentication token";
             break;
           case 2:
             error = "Already logged in";
             break;
           case 3:
             error = "Could not connect to server";
             break;
           case 4:
             error = "This client is too old";
             break;
           case 5:
             error = "Authentication token expired";
             break;
           default:
             error = "Connection failed";
             break;
         }
         ui.uimsg(1, "error", error);
         sess = null;
         continue retry;
       }
       synchronized (sess) {
         sess.wait();
       }
     }
   } while (true);
   haven.error.ErrorHandler.setprop("usr", sess.username);
   return (sess);
   // (new RemoteUI(sess, ui)).start();
 }