/**
   * Constructs a configuration file from a map.
   *
   * @param map - the map that holds the configuration settings
   */
  public Configuration(final Map<String, Object> map) {
    loadConfig(map);

    // Check to make sure necessary fields were filled
    boolean crash = false;
    if ((this.inputFileDirName == null && this.inputFileName == null)
        || (this.inputFileDirName != null && this.inputFileName != null)) {
      LOG.fatal("An input file OR directory must be selected");
      crash = true;
    } else if (this.outDirName == null) {
      LOG.fatal("An output directory must be selected");
      crash = true;
    } else if (this.execPath == null) {
      crash = true;
      LOG.fatal("An executable must be selected");
    } else if (this.mergeMethod == -1) {
      crash = true;
      LOG.fatal("A merge method must be selected");
    }

    if (crash) {
      System.exit(1);
    } else if (this.save) {
      saveConfig();
    }
  }
Esempio n. 2
0
  /**
   * Given an interface, instantiate a class implementing that interface.
   *
   * <p>The classname to instantiate is obtained by looking in the runtime {@link Config
   * configuration}, under the factory.impl.&lt;interface name&gt; key.
   *
   * @param <T> the interface type.
   * @param interfaz the interface to instantiate an implementation for.
   * @return an Object which implements the given interface.
   * @throws SystemException if no implementing class is registered in the {@link Config
   *     configuration}.
   */
  public static <T> T newInstance(final Class<T> interfaz) {
    Configuration config = Config.getInstance();
    String classname = config.getString(PREFIX + interfaz.getName());

    if (classname == null) {
      // Hmmm - this is bad. For the time being let's dump the parameters.
      log.fatal("No implementing class for " + interfaz.getName());
      log.fatal("There needs to be a parameter defined for " + PREFIX + interfaz.getName());

      throw new SystemException(
          "No implementing class for "
              + interfaz.getName()
              + "; "
              + "There needs to be a parameter defined for "
              + PREFIX
              + interfaz.getName());
    }

    try {
      Class<T> clas = (Class<T>) Class.forName(classname.trim());
      return clas.newInstance();
    } catch (Exception ex) {
      throw new SystemException("Failed to instantiate object of class " + classname, ex);
    }
  }
Esempio n. 3
0
  public Object doSync() throws Exception {
    String reqMsg = XxtXmlHandler.toXxtRequestXml(userInfo);
    msgLog.fatal(reqMsg); // 记录同步日志

    try {
      String retMsg = null;

      // 如果能够成功地转化报文,那么就修改数据状态,并向Misc发起同步请求
      // 将数据信息与入到misc_order_relation
      if (reqMsg != null) { // && dao.addUserInfoToMiscOrderTab(userInfo)
        retMsg = syncOrderInfo(reqMsg);
      } else {
        log.error("无法完成反向同步数据的准备,不能发起请求!");
        return null;
      }

      if (log.isDebugEnabled()) log.debug("校讯通反向同步时,服务器的响应报文:\n" + retMsg.toString());

      MiscRespBean bean = null;
      if (retMsg != null) {
        msgLog.fatal(retMsg); // 记录MISC返回日志
        bean = XxtXmlHandler.parseMiscRespMsg(retMsg);
      }

      handleResponse(bean);
    } catch (Throwable t) {
      log.error(t);
    }

    return null;
  }
Esempio n. 4
0
  protected synchronized void addToCache(String elastic, String manager, IDMap map, int type)
      throws Exception {

    if (elastic == null) {
      throw new IllegalArgumentException("elastic may not be null");
    }
    if (manager == null) {
      throw new IllegalArgumentException("manager may not be null");
    }
    if (map == null) {
      throw new IllegalArgumentException("map may not be null");
    }

    if (this.cacheElasticKeys.isKeyInCache(elastic)) {
      final String err = "illegal, already mapped " + elastic;
      logger.fatal(err);
      throw new Exception(err);
    }
    final Element el = new Element(elastic, map);
    this.cacheElasticKeys.put(el);
    this.cacheElasticKeys.flush();

    final String id2 = type + manager;
    if (this.cacheManageKeys.isKeyInCache(id2)) {
      final String err = "illegal, already mapped " + id2;
      logger.fatal(err);
      throw new Exception(err);
    }
    final Element el2 = new Element(id2, map);
    this.cacheManageKeys.put(el2);
    this.cacheManageKeys.flush();
  }
  /**
   * Creates proxy basing on the given configurable target class.
   *
   * @param targetClass the given configurable target class.
   * @param argsType the args type
   * @param args the args
   * @return returns the <code>proxy instance</code>.
   */
  @SuppressWarnings("unchecked")
  public static <T extends Configurable> T createProxy(
      Class<T> targetClass, Class<?>[] argsType, Object[] args) {

    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(targetClass);
    enhancer.setInterfaces(new Class[] {ConfigModule.class});
    // Kiểm tra interface cài đặt
    Set<Class<?>> interfaceList = ReflectUtils.getAllInterfaces(targetClass, true);
    if (AbstractConfig.class.isAssignableFrom(targetClass)) {
      interfaceList.remove(SystemConfig.class);
    }
    HashMap<String, Object> optionsList = new HashMap<String, Object>();
    HashMap<Class<?>, Object> configObjList = new HashMap<Class<?>, Object>();
    for (Class<?> interfaze : interfaceList) {
      if (JGentle.containsConfigClass(interfaze)) {
        Class<?> clazz = JGentle.getConfigClass(interfaze);
        Object obj = null;
        obj = ReflectUtils.createInstance(clazz);
        // Nếu config class extends từ AbstractConfigModule
        if (AbstractConfigModule.class.isAssignableFrom(clazz)) {
          try {
            ((AbstractConfigModule) obj)
                .setOptionsList(
                    optionsList, ReflectUtils.getSupportedMethod(targetClass, "configure", null));
          } catch (NoSuchMethodException e) {
            if (log.isFatalEnabled()) {
              log.fatal(
                  "Could not found 'configure' method on configurable class [" + targetClass + "]",
                  e);
            }
          }
        }
        configObjList.put(interfaze, obj);
      }
    }
    enhancer.setCallback(new ConfigurationProxy(targetClass, optionsList, configObjList));
    Object result = null;
    if (argsType != null && args != null) {
      result = enhancer.create(argsType, args);
    } else {
      result = enhancer.create();
    }
    // thiết lập optionsList trong trường hợp targetClass kế thừa từ
    // AbstractConfig
    if (AbstractConfig.class.isAssignableFrom(targetClass)) {
      try {
        ((AbstractConfig) result)
            .setOptionsList(
                optionsList, ReflectUtils.getSupportedMethod(targetClass, "configure", null));
      } catch (NoSuchMethodException e) {
        if (log.isFatalEnabled()) {
          log.fatal(
              "Could not found 'configure' method on configurable class [" + targetClass + "]", e);
        }
      }
    }
    return (T) result;
  }
Esempio n. 6
0
  @Override
  public String createVolume(int sizeGB, String snapshotId) {
    IaasProvider iaasInfo = getIaasProvider();

    ComputeServiceContext context = iaasInfo.getComputeService().getContext();

    String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
    String zone = ComputeServiceBuilderUtil.extractZone(iaasInfo);

    if (region == null || zone == null) {
      log.fatal(
          "Cannot create a new volume in the [region] : "
              + region
              + ", [zone] : "
              + zone
              + " of Iaas : "
              + iaasInfo);
      return null;
    }

    ElasticBlockStoreApi blockStoreApi =
        context.unwrapApi(AWSEC2Api.class).getElasticBlockStoreApiForRegion(region).get();

    Volume volume;
    if (StringUtils.isEmpty(snapshotId)) {
      if (log.isDebugEnabled()) {
        log.info("Creating a volume in the zone " + zone);
      }
      volume = blockStoreApi.createVolumeInAvailabilityZone(zone, sizeGB);
    } else {
      if (log.isDebugEnabled()) {
        log.info("Creating a volume in the zone " + zone + " from the shanpshot " + snapshotId);
      }
      volume = blockStoreApi.createVolumeFromSnapshotInAvailabilityZone(zone, snapshotId);
    }

    if (volume == null) {
      log.fatal(
          "Volume creation was unsuccessful. [region] : "
              + region
              + ", [zone] : "
              + zone
              + " of Iaas : "
              + iaasInfo);
      return null;
    }

    log.info(
        "Successfully created a new volume [id]: "
            + volume.getId()
            + " in [region] : "
            + region
            + ", [zone] : "
            + zone
            + " of Iaas : "
            + iaasInfo);
    return volume.getId();
  }
Esempio n. 7
0
 /** @syncpriority 90 */
 public void abort() {
   log.fatal("Mina instance ABORTING!");
   ccm.prepareForShutdown();
   scm.abort();
   ccm.abort();
   netMgr.stop();
   started = false;
   log.fatal("Mina instance stopped");
 }
Esempio n. 8
0
  /**
   * Parse ZooKeeper's zoo.cfg, injecting HBase Configuration variables in. This method is used for
   * testing so we can pass our own InputStream.
   *
   * @param conf HBaseConfiguration to use for injecting variables.
   * @param inputStream InputStream to read from.
   * @return Properties parsed from config stream with variables substituted.
   * @throws IOException if anything goes wrong parsing config
   */
  public static Properties parseZooCfg(Configuration conf, InputStream inputStream)
      throws IOException {
    Properties properties = new Properties();
    try {
      properties.load(inputStream);
    } catch (IOException e) {
      final String msg = "fail to read properties from " + HConstants.ZOOKEEPER_CONFIG_NAME;
      LOG.fatal(msg);
      throw new IOException(msg, e);
    }
    for (Entry<Object, Object> entry : properties.entrySet()) {
      String value = entry.getValue().toString().trim();
      String key = entry.getKey().toString().trim();
      StringBuilder newValue = new StringBuilder();
      int varStart = value.indexOf(VARIABLE_START);
      int varEnd = 0;
      while (varStart != -1) {
        varEnd = value.indexOf(VARIABLE_END, varStart);
        if (varEnd == -1) {
          String msg = "variable at " + varStart + " has no end marker";
          LOG.fatal(msg);
          throw new IOException(msg);
        }
        String variable = value.substring(varStart + VARIABLE_START_LENGTH, varEnd);

        String substituteValue = System.getProperty(variable);
        if (substituteValue == null) {
          substituteValue = conf.get(variable);
        }
        if (substituteValue == null) {
          String msg = "variable " + variable + " not set in system property " + "or hbase configs";
          LOG.fatal(msg);
          throw new IOException(msg);
        }

        newValue.append(substituteValue);

        varEnd += VARIABLE_END_LENGTH;
        varStart = value.indexOf(VARIABLE_START, varEnd);
      }
      // Special case for 'hbase.cluster.distributed' property being 'true'
      if (key.startsWith("server.")) {
        if (conf.get(HConstants.CLUSTER_DISTRIBUTED).equals(HConstants.CLUSTER_IS_DISTRIBUTED)
            && value.startsWith("localhost")) {
          String msg =
              "The server in zoo.cfg cannot be set to localhost "
                  + "in a fully-distributed setup because it won't be reachable. "
                  + "See \"Getting Started\" for more information.";
          LOG.fatal(msg);
          throw new IOException(msg);
        }
      }
      newValue.append(value.substring(varEnd));
      properties.setProperty(key, newValue.toString());
    }
    return properties;
  }
Esempio n. 9
0
 @Override
 protected Cipher initialValue() {
   try {
     return Cipher.getInstance(TRANSFORMATION);
   } catch (NoSuchAlgorithmException e) {
     LOG.fatal("AES Cipher init error", e);
     throw new RuntimeException(e);
   } catch (NoSuchPaddingException e) {
     LOG.fatal("AES Cipher init error", e);
     throw new RuntimeException(e);
   }
 }
  public void init(Map props) {
    storeFile = (String) props.get("storeFile");

    // check whether the file denoted by the storeFile property is a normal file.
    if (!new File(storeFile).isFile()) {
      log.fatal("storePath property should indicate a normal file");
    }

    // check wheter the directory containing the storeFile exist
    if (!new File(storeFile).getParentFile().exists()) {
      log.fatal("directory " + new File(storeFile).getParent() + " not found");
    }
  }
Esempio n. 11
0
 /** @syncpriority 200 */
 public void stop() throws MinaException {
   log.fatal("Mina instance stopping");
   ccm.prepareForShutdown();
   scm.closeAllStreamConns();
   streamMgr.stop();
   sourceMgr.stop();
   streamAdvertiser.cancel();
   ccm.stop();
   netMgr.stop();
   badNodes.clear();
   started = false;
   log.fatal("Mina instance stopped");
 }
Esempio n. 12
0
  public void init() throws ServletException {
    // 获取上传文件所保存到的相对路径配置
    appSubDir = this.getInitParameter("appSubDir");
    // if (StringUtils.isEmpty(appSubDir))
    // LocalizedTextUtil.findText(AttachAction.class,
    // "app.data.subPath", Locale.getDefault());
    if (StringUtils.isEmpty(appSubDir)) appSubDir = "uploads";
    File absoluteDir = new File(WebUtils.rootPath + File.separator + appSubDir);
    if (!absoluteDir.exists()) {
      if (logger.isFatalEnabled()) {
        logger.fatal("mkdir=" + appSubDir);
      }
      absoluteDir.mkdir(); // 自动创建目录
    }

    // 获取上传文件所保存到的绝对路径配置
    appRealDir = this.getInitParameter("appRealDir");
    // if (StringUtils.isEmpty(appRealDir))
    // LocalizedTextUtil.findText(AttachAction.class, "app.data.realPath",
    // Locale.getDefault());
    if (StringUtils.isEmpty(appRealDir)) appRealDir = "/bcdata";
    absoluteDir = new File(appRealDir);
    if (!absoluteDir.exists()) {
      if (logger.isFatalEnabled()) {
        logger.fatal("mkdir=" + appRealDir);
      }
      absoluteDir.mkdir(); // 自动创建目录
    }

    // 获取文件类型限制参数
    extensions = this.getInitParameter("extensions");

    // 获取文件大小限制参数
    String maxSize_str = this.getInitParameter("maxSize");
    if (StringUtils.isNotEmpty(maxSize_str)) {
      maxSize = new Long(maxSize_str);
    } else {
      maxSize = Long.valueOf(1024 * 1024 * 1024); // 1G
    }

    // debug
    if (logger.isFatalEnabled()) {
      logger.fatal("appSubDir=" + appSubDir);
      logger.fatal("appRealDir=" + appRealDir);
      logger.fatal("extensions=" + extensions);
      logger.fatal("maxSize=" + AttachUtils.getSizeInfo(maxSize));
    }
  }
Esempio n. 13
0
  /**
   * Guarda todos los mensajes en la BD
   *
   * @param from
   * @param to
   * @param body
   * @param direction
   * @throws Exception
   */
  public static void push(String from, String to, String body, String direction) {
    IGenericDao dao = null;
    try {
      dao = Utility.getDbConnection();

      Queue q = new Queue();
      q.setDelivered(new Integer(0));
      q.setMsgDirection(direction);
      q.setMsgBody(body);
      q.setMsgFrom(from);
      q.setMsgTime(new Timestamp(new Date().getTime()));
      q.setMsgTo(to);
      System.out.println("USUARIOS Q RECIBEN EL SMS Y SE VAN A INSERTAR EN LA BD ======> " + to);
      // de momento se deja a pelo hasta q este la muc
      q.setType("S");

      log.debug("new message " + direction + " from: " + from + " to: " + to + " body: " + body);

      IObjectMappingKey myObj =
          Utility.persistMan
              .getObjectMappingFactory()
              .createInstance(Queue.class, new AutoGeneratedColumnsMapper(true));
      dao.insert(myObj, q);
    } catch (Exception e) {
      log.error("mesage couldn't be written to db", e);
    } finally {
      try {
        JdbcUtil.close(dao);
      } catch (Exception e) {
        log.fatal("unable to close jdbc connection", e);
      }
      dao = null;
    }
  }
Esempio n. 14
0
  public void onException(ErrorMessage msg) throws MuleException {
    Class eClass = null;
    ExceptionHandler eh = null;

    try {
      eClass = msg.getException().toException().getClass();
      eh = getHandler(eClass);
      eh.onException(msg);
    } catch (Exception e) {
      logger.error(e);

      if (eh instanceof DefaultHandler) {
        logger.error(LocaleMessage.defaultFatalHandling(FatalHandler.class));
        handleFatal(e);

      } else if (eh instanceof FatalHandler) {
        logger.fatal(LocaleMessage.fatalHandling(e));
        MuleServer.getMuleContext().dispose();
        System.exit(-1);
      } else {
        logger.error(LocaleMessage.defaultHandling(DefaultHandler.class, eh, e));
        handleDefault(msg, e);
      }
    }
  }
Esempio n. 15
0
  @SuppressWarnings("unchecked")
  protected void dispatch(Event event) {
    // all events go thru this loop
    if (LOG.isDebugEnabled()) {
      LOG.debug("Dispatching the event " + event.getClass().getName() + "." + event.toString());
    }

    Class<? extends Enum> type = event.getType().getDeclaringClass();

    try {
      EventHandler handler = eventDispatchers.get(type);
      if (handler != null) {
        handler.handle(event);
      } else {
        throw new Exception("No handler for registered for " + type);
      }
    } catch (Throwable t) {
      // TODO Maybe log the state of the queue
      LOG.fatal("Error in dispatcher thread", t);
      // If serviceStop is called, we should exit this thread gracefully.
      if (exitOnDispatchException
          && (ShutdownHookManager.get().isShutdownInProgress()) == false
          && stopped == false) {
        Thread shutDownThread = new Thread(createShutDownThread());
        shutDownThread.setName("AsyncDispatcher ShutDown handler");
        shutDownThread.start();
      }
    }
  }
 /**
  * endTask() can fail and the only way to recover out of it is for the {@link
  * org.apache.hadoop.hbase.master.SplitLogManager} to timeout the task node.
  *
  * @param slt
  * @param ctr
  */
 @Override
 public void endTask(SplitLogTask slt, AtomicLong ctr, SplitTaskDetails details) {
   ZkSplitTaskDetails zkDetails = (ZkSplitTaskDetails) details;
   String task = zkDetails.getTaskNode();
   int taskZKVersion = zkDetails.getCurTaskZKVersion().intValue();
   try {
     if (ZKUtil.setData(watcher, task, slt.toByteArray(), taskZKVersion)) {
       LOG.info("successfully transitioned task " + task + " to final state " + slt);
       ctr.incrementAndGet();
       return;
     }
     LOG.warn(
         "failed to transistion task "
             + task
             + " to end state "
             + slt
             + " because of version mismatch ");
   } catch (KeeperException.BadVersionException bve) {
     LOG.warn(
         "transisition task " + task + " to " + slt + " failed because of version mismatch", bve);
   } catch (KeeperException.NoNodeException e) {
     LOG.fatal(
         "logic error - end task " + task + " " + slt + " failed because task doesn't exist", e);
   } catch (KeeperException e) {
     LOG.warn("failed to end task, " + task + " " + slt, e);
   }
   SplitLogCounters.tot_wkr_final_transition_failed.incrementAndGet();
 }
Esempio n. 17
0
 private void handleFatal(Throwable t) {
   // If this method has been called, all other handlers failed
   // this is all we can do
   logger.fatal(LocaleMessage.fatalException(t), t);
   MuleServer.getMuleContext().dispose();
   System.exit(-1);
 }
Esempio n. 18
0
  /**
   * Register.
   *
   * @param username the username
   * @param password the password
   * @param firstname the firstname
   * @param lastname the lastname
   * @param phone the phone
   * @param role the role
   * @param secid the secid
   * @param answer the answer
   * @return the user
   */
  @Override
  public User register(
      String username,
      String password,
      String firstname,
      String lastname,
      String phone,
      String role,
      int secid,
      String answer) {
    try {
      User user = new User();
      user.setUsername(username);
      user.setPassword(password);
      user.setFirstName(firstname);
      user.setLastName(lastname);
      user.setPhone(phone);
      user.setSecQuestionId(secid);
      user.setSecAnswer(answer);
      user.setRole("4");

      int res = userMapper.insertSelective(user);
      if (res > 0) {
        return user;
      }

    } catch (Exception e) {
      Logger.fatal(e.getMessage());
    }

    User user = new User();
    user.setUserId(-1L);
    return new User();
  }
Esempio n. 19
0
  /**
   * Executes the next step.
   *
   * @return True on success.
   */
  public boolean next() {
    if (stepIndex == -1) {
      log.debug("Starting test run.");
    }

    initRemoteWebDriver();

    log.debug(
        "Running step "
            + (stepIndex + 2)
            + ":"
            + script.steps.get(stepIndex + 1).getClass().getSimpleName()
            + " step.");
    boolean result = false;
    try {
      result = script.steps.get(++stepIndex).type.run(this);
    } catch (Exception e) {
      throw new RuntimeException(currentStep() + " failed.", e);
    }

    if (!result) {
      // If a verify failed, we just note this but continue.
      if (currentStep().type instanceof Verify) {
        log.error(currentStep() + " failed.");
        return false;
      }
      // In all other cases, we throw an exception to stop the run.
      RuntimeException e = new RuntimeException(currentStep() + " failed.");
      e.fillInStackTrace();
      log.fatal(e);
      throw e;
    } else {
      return true;
    }
  }
Esempio n. 20
0
  /**
   * Execute statement to remove entity with given identity from database using given JDBC
   * connection.
   *
   * @param conn CastorConnection holding connection and PersistenceFactory to be used to create
   *     statement.
   * @param identity Identity of the object to remove.
   * @throws PersistenceException If failed to remove object from database. This could happen if a
   *     database access error occurs, type of one of the values to bind is ambiguous or object to
   *     be deleted does not exist.
   */
  public void executeStatement(final CastorConnection conn, final Identity identity)
      throws PersistenceException {
    CastorStatement stmt = conn.createStatement();
    try {
      stmt.prepareStatement(_delete);

      // bind the identity of the row to be stored into the preparedStatement
      for (ColumnValue value : _tableInfo.toSQL(identity)) {
        stmt.bindParameter(value.getName(), value.getValue(), value.getType());
      }

      if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.format("jdo.removing", _type, stmt.toString()));
      }

      // execute prepared statement
      int result = stmt.executeUpdate();

      // throw exception if execute returned < 1
      if (result < 1) {
        throw new SQLException("Object to be deleted does not exist!");
      }
    } catch (SQLException ex) {
      LOG.fatal(Messages.format("jdo.deleteFatal", _type, stmt.toString()), ex);
      throw new PersistenceException(Messages.format("persist.nested", ex), ex);
    } finally {
      // close statement
      try {
        stmt.close();
      } catch (SQLException e) {
        LOG.warn("Problem closing JDBC statement", e);
      }
    }
  }
Esempio n. 21
0
  // Checks if the cache has already been localized and is fresh
  private static boolean ifExistsAndFresh(
      Configuration conf,
      FileSystem fs,
      URI cache,
      long confFileStamp,
      CacheStatus lcacheStatus,
      FileStatus fileStatus)
      throws IOException {
    // check for existence of the cache
    long dfsFileStamp;
    if (fileStatus != null) {
      dfsFileStamp = fileStatus.getModificationTime();
    } else {
      dfsFileStamp = getTimestamp(conf, cache);
    }

    // ensure that the file on hdfs hasn't been modified since the job started
    if (dfsFileStamp != confFileStamp) {
      LOG.fatal("File: " + cache + " has changed on HDFS since job started");
      throw new IOException("File: " + cache + " has changed on HDFS since job started");
    }

    if (dfsFileStamp != lcacheStatus.mtime) {
      // needs refreshing
      return false;
    }

    return true;
  }
Esempio n. 22
0
  static {
    InputStream is =
        BootStrapProperties.class.getClassLoader().getResourceAsStream(BOOT_STRAP_PROPERTIES_FILE);

    if (is == null) {
      log.fatal("Cannot load " + BOOT_STRAP_PROPERTIES_FILE);
    }

    properties = new java.util.Properties();

    try {
      properties.load(is);
    } catch (Exception e) {
      log.fatal(ExceptionUtil.getExceptionDetails(e));
    }
  }
Esempio n. 23
0
  @SuppressWarnings("unchecked")
  private void initTxMgr() throws ServletException {
    if (_odeConfig.getDbMode().equals(OdeConfigProperties.DatabaseMode.EXTERNAL)
        && _odeConfig
            .getTxFactoryClass()
            .equals(OdeConfigProperties.DEFAULT_TX_FACTORY_CLASS_NAME)) {
      throw new ServletException(
          "No external transaction manager factory configured. Please use the INTERNAL mode or configure an external transaction manager that is associated with external datasource.");
    }

    String txFactoryName = _odeConfig.getTxFactoryClass();
    __log.debug("Initializing transaction manager using " + txFactoryName);
    try {
      Class txFactClass = this.getClass().getClassLoader().loadClass(txFactoryName);
      Object txFact = txFactClass.newInstance();
      _txMgr =
          (TransactionManager)
              txFactClass.getMethod("getTransactionManager", (Class[]) null).invoke(txFact);
      if (__logTx.isDebugEnabled() && System.getProperty("ode.debug.tx") != null)
        _txMgr = new DebugTxMgr(_txMgr);
    } catch (Exception e) {
      __log.fatal("Couldn't initialize a transaction manager with factory: " + txFactoryName, e);
      throw new ServletException(
          "Couldn't initialize a transaction manager with factory: " + txFactoryName, e);
    }
  }
Esempio n. 24
0
  /** Remove bids */
  private void removeBids() {
    Connection con = null;
    try {
      con = L2DatabaseFactory.getInstance().getConnection(con);
      PreparedStatement statement;

      statement = con.prepareStatement("DELETE FROM auction_bid WHERE auctionId=?");
      statement.setInt(1, getId());
      statement.execute();

      statement.close();
    } catch (Exception e) {
      _log.fatal("Exception: Auction.deleteFromDB(): " + e.getMessage(), e);
    } finally {
      L2DatabaseFactory.close(con);
    }

    for (Bidder b : _bidders.values()) {
      if (ClanTable.getInstance().getClanByName(b.getClanName()).getHasHideout() == 0)
        returnItem(b.getClanName(), PcInventory.ADENA_ID, b.getBid(), true); // 10 % tax
      else {
        L2Player bidder = L2World.getInstance().getPlayer(b.getName());
        if (bidder != null) bidder.sendMessage("Congratulations! You have won a ClanHall!");
      }
      ClanTable.getInstance().getClanByName(b.getClanName()).setAuctionBiddedAt(0, true);
    }
    _bidders.clear();
  }
Esempio n. 25
0
  /** Cancel bid */
  public synchronized void cancelBid(int bidder) {
    Connection con = null;
    try {
      con = L2DatabaseFactory.getInstance().getConnection(con);
      PreparedStatement statement;

      statement = con.prepareStatement("DELETE FROM auction_bid WHERE auctionId=? AND bidderId=?");
      statement.setInt(1, getId());
      statement.setInt(2, bidder);
      statement.execute();

      statement.close();
    } catch (Exception e) {
      _log.fatal("Exception: Auction.cancelBid(String bidder): " + e.getMessage(), e);
    } finally {
      L2DatabaseFactory.close(con);
    }

    returnItem(
        _bidders.get(bidder).getClanName(),
        PcInventory.ADENA_ID,
        _bidders.get(bidder).getBid(),
        true);
    ClanTable.getInstance()
        .getClanByName(_bidders.get(bidder).getClanName())
        .setAuctionBiddedAt(0, true);
    _bidders.clear();
    loadBid();
  }
Esempio n. 26
0
 @Override
 public void fatal(Object message, Throwable t) {
   log.fatal(message, t);
   if (log.isFatalEnabled() && publisher != null) {
     publish(rosgraph_msgs.Log.FATAL, message, t);
   }
 }
  public void init() throws ServletException {
    log.debug("init() called, seller=" + seller + ", userMgmt=" + userMgmt);
    JNDIHelper jndi = null;
    ;
    try {
      // build a list of handlers for individual commands
      handlers.put(MAINMENU_COMMAND, new AdminMenu());
      handlers.put(CREATEACCOUNT_COMMAND, new CreateAccount());
      handlers.put(SELLPRODUCT_COMMAND, new SellProduct());
      handlers.put(GETITEMS_COMMAND, new GetItems());
      handlers.put(LOGOUT_COMMAND, new Logout());

      // verify local injected or replace with remote
      ServletContext ctx = getServletContext();
      // TODO: jndi = new JNDIHelper(ctx);
      if (seller == null) {
        seller = jndi.getSeller();
      }
      if (userMgmt == null) {
        userMgmt = jndi.getUserMgmt();
      }
    } catch (Exception ex) {
      log.fatal("error initializing handler", ex);
      throw new ServletException("error initializing handler", ex);
    } finally {
      if (jndi != null) {
        jndi.close();
      }
    }
  }
Esempio n. 28
0
  /** Confirm an auction */
  public void confirmAuction() {
    AuctionService.getInstance().getAuctions().add(this);
    Connection con = null;
    try {
      PreparedStatement statement;
      con = L2DatabaseFactory.getInstance().getConnection(con);

      statement =
          con.prepareStatement(
              "INSERT INTO auction (id, sellerId, sellerName, sellerClanName, itemType, itemId, itemObjectId, itemName, itemQuantity, startingBid, currentBid, endDate) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
      statement.setInt(1, getId());
      statement.setInt(2, _sellerId);
      statement.setString(3, _sellerName);
      statement.setString(4, _sellerClanName);
      statement.setString(5, _itemType);
      statement.setInt(6, _itemId);
      statement.setInt(7, _itemObjectId);
      statement.setString(8, _itemName);
      statement.setInt(9, _itemQuantity);
      statement.setInt(10, _startingBid);
      statement.setInt(11, _currentBid);
      statement.setLong(12, _endDate);
      statement.execute();
      statement.close();
      loadBid();
    } catch (Exception e) {
      _log.fatal("Exception: Auction.load(): " + e.getMessage(), e);
    } finally {
      L2DatabaseFactory.close(con);
    }
  }
Esempio n. 29
0
  @Override
  public void fetchFailed(
      String host, InputAttemptIdentifier srcAttemptIdentifier, boolean connectFailed) {
    // TODO NEWTEZ. Implement logic to report fetch failures after a threshold.
    // For now, reporting immediately.
    LOG.info(
        "Fetch failed for src: "
            + srcAttemptIdentifier
            + "InputIdentifier: "
            + srcAttemptIdentifier
            + ", connectFailed: "
            + connectFailed);
    failedShufflesCounter.increment(1);
    if (srcAttemptIdentifier == null) {
      String message = "Received fetchFailure for an unknown src (null)";
      LOG.fatal(message);
      inputContext.fatalError(null, message);
    } else {
      InputReadErrorEvent readError =
          new InputReadErrorEvent(
              "Fetch failure while fetching from "
                  + TezRuntimeUtils.getTaskAttemptIdentifier(
                      inputContext.getSourceVertexName(),
                      srcAttemptIdentifier.getInputIdentifier().getInputIndex(),
                      srcAttemptIdentifier.getAttemptNumber()),
              srcAttemptIdentifier.getInputIdentifier().getInputIndex(),
              srcAttemptIdentifier.getAttemptNumber());

      List<Event> failedEvents = Lists.newArrayListWithCapacity(1);
      failedEvents.add(readError);
      inputContext.sendEvents(failedEvents);
    }
  }
Esempio n. 30
0
 /** @see java.lang.Thread#run() */
 @Override
 public void run() {
   while (!stopRequested || (stopRequested && leaseQueue.size() > 0)) {
     Lease lease = null;
     try {
       lease = leaseQueue.poll(leaseCheckFrequency, TimeUnit.MILLISECONDS);
     } catch (InterruptedException e) {
       continue;
     } catch (ConcurrentModificationException e) {
       continue;
     } catch (Throwable e) {
       LOG.fatal("Unexpected exception killed leases thread", e);
       break;
     }
     if (lease == null) {
       continue;
     }
     // A lease expired.  Run the expired code before removing from queue
     // since its presence in queue is used to see if lease exists still.
     if (lease.getListener() == null) {
       LOG.error("lease listener is null for lease " + lease.getLeaseName());
     } else {
       lease.getListener().leaseExpired();
     }
     synchronized (leaseQueue) {
       leases.remove(lease.getLeaseName());
     }
   }
   close();
 }