public boolean doSetup() {
    boolean okay = false;
    try {
      jndiContext = new InitialContext();
    } catch (NamingException e) {
      log.error("Could not create JNDI API " + "context: " + e.toString());
    }

    /*
     * Look up connection factory and queue. If either does not exist, exit.
     */
    try {
      queueConnectionFactory =
          (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
      if (queueConnectionFactory == null) log.error("null factory");
      queue = (Queue) jndiContext.lookup("manny");
      if (queue == null) log.error("null factory");
      log.debug("finished config");
      okay = true;

    } catch (NamingException e) {
      log.error("JNDI API lookup failed: " + e.toString());
    }
    return okay;
  }
  /**
   * Method getParticipant.
   *
   * @param aId - String
   * @return R4EParticipant
   */
  protected R4EParticipant getParticipant(String aId) {
    // First check if the participant already exist in the participant list
    for (R4EParticipant tmpPart : fParticipants) {
      if (aId.equalsIgnoreCase(tmpPart.getId())) {
        return null;
      }
    }
    final R4EParticipant participant = RModelFactory.eINSTANCE.createR4EParticipant();
    if (R4EUIModelController.isUserQueryAvailable()) {
      final IQueryUser query = new QueryUserFactory().getInstance();
      try {
        final List<IUserInfo> users = query.searchByUserId(aId);

        // Fill info with first user returned
        for (IUserInfo user : users) {
          if (user.getUserId().toLowerCase().equals(aId)) {
            participant.setId(user.getUserId().toLowerCase());
            participant.setEmail(user.getEmail());
            fParticipantsDetailsValues.add(UIUtils.buildUserDetailsString(user));
            return participant;
          }
        }
      } catch (NamingException e) {
        R4EUIPlugin.Ftracer.traceError("Exception: " + e.toString() + " (" + e.getMessage() + ")");
        R4EUIPlugin.getDefault().logError("Exception: " + e.toString(), e);
      } catch (IOException e) {
        R4EUIPlugin.getDefault().logWarning("Exception: " + e.toString(), e);
      }
    }
    participant.setId(aId);
    fParticipantsDetailsValues.add("");
    return participant;
  }
示例#3
0
 /** Creates a new BeanUtil object. */
 public BeanUtil() {
   try {
     if (ctx == null) {
       try {
         Context initContext = new InitialContext();
         Context envContext = (Context) initContext.lookup("java:comp");
         ctx = envContext;
       } catch (NamingException ne) {
         logger.debug("Error Getting Initial Context: <" + ne + ">");
         throw new Exception(ne.toString());
       }
     }
     if (dataSources.get(DATA_SOURCE_NAME) == null) {
       try {
         dataSources.put(DATA_SOURCE_NAME, ctx.lookup(DATA_SOURCE_NAME));
       } catch (NamingException ne) {
         logger.debug("Error Getting DataSource: <" + ne + ">");
         throw new Exception(ne.toString());
       }
     }
     utx = (UserTransaction) ctx.lookup("UserTransaction");
     utx.begin();
   } catch (Exception e) {
     logger.error("[BeanUtil:Error]:" + e.getMessage());
     e.printStackTrace();
   }
 }
示例#4
0
  /**
   * This postparses a name, after it has been returned from the jndi operation. It assumes that it
   * has got a jndi <i>CompositeName</i> that needs to be converted to a legal ldap dn (i.e. an ldap
   * <i>CompoundName</i>). If this is *not* the case, there will be trouble...
   *
   * @param name the post jndi operation name.
   * @return the re-formatted version used by the application, as a DN object.
   */
  public Name postParse(String name) {
    /* EMERGENCY HACK
     * (JNDI apparently does not handle terminating spaces correctly - it
     * retains the escape characters, but trims the actual space, resulting
     * in an illegal ldap dn)
     */
    if (name.charAt(name.length() - 1) == '\\') {
      name = NameUtility.checkEndSpaces(name);
    }

    try {
      Name cn = new CompositeName(name);
      if (cn.size() == 0) // if the name is empty ...
      return new DN(); // ... just return an empty DN

      return new DN(
          cn.get(
              cn.size()
                  - 1)); // get the last element of the composite name, which will be the ldap
                         // compound name, and init the DN with that.
    } catch (NamingException e) // should never happen :-) (ROTFL)
    {
      log.log(
          Level.WARNING,
          "unexpected error: bad name back from jndi ftn in CBOps.postParse("
              + name
              + ")?\n"
              + e.toString());
      e.printStackTrace();
      // System.exit(-1);
      return new DN(name); // bad server response?  return (possibly) corrupt name anyway...
    }
  }
  public RMIConnection createConnection() {
    RMIServerManager serverManager = null;
    Context initialNamingContext = null;
    try {
      initialNamingContext = new InitialContext();
    } catch (NamingException exception) {
      System.out.println("Naming Exception " + exception.toString());
    }
    ;
    // Set the client security manager
    try {
      System.setSecurityManager(new RMISecurityManager());
    } catch (Exception exception) {
      System.out.println("Security violation " + exception.toString());
    }

    // Get the remote factory object from the Registry
    try {
      serverManager = (RMIServerManager) initialNamingContext.lookup("SERVER-MANAGER");
    } catch (Exception exception) {
      throw new TestProblemException(exception.toString());
    }

    RMIConnection rmiConnection = null;
    try {
      rmiConnection = new RMIConnection(serverManager.createRemoteSessionController());
    } catch (RemoteException exception) {
      System.out.println("Error in invocation " + exception.toString());
    }

    return rmiConnection;
  }
  protected DirContext open() throws NamingException {
    try {
      Hashtable<String, String> env = new Hashtable<String, String>();
      env.put(Context.INITIAL_CONTEXT_FACTORY, getLDAPPropertyValue(INITIAL_CONTEXT_FACTORY));
      if (isLoginPropertySet(CONNECTION_USERNAME)) {
        env.put(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(CONNECTION_USERNAME));
      } else {
        throw new NamingException("Empty username is not allowed");
      }

      if (isLoginPropertySet(CONNECTION_PASSWORD)) {
        env.put(Context.SECURITY_CREDENTIALS, getLDAPPropertyValue(CONNECTION_PASSWORD));
      } else {
        throw new NamingException("Empty password is not allowed");
      }
      env.put(Context.SECURITY_PROTOCOL, getLDAPPropertyValue(CONNECTION_PROTOCOL));
      env.put(Context.PROVIDER_URL, getLDAPPropertyValue(CONNECTION_URL));
      env.put(Context.SECURITY_AUTHENTICATION, getLDAPPropertyValue(AUTHENTICATION));
      context = new InitialDirContext(env);

    } catch (NamingException e) {
      ActiveMQServerLogger.LOGGER.error(e.toString());
      throw e;
    }
    return context;
  }
示例#7
0
 /** Creates new NamespacePermission */
 public PermissionName(String name) throws IllegalArgumentException {
   try {
     this.name = new CompoundName(name, nameSyntax);
   } catch (NamingException e) {
     throw new IllegalArgumentException(e.toString(true));
   }
 }
 private void cleanUp(InitialContext initialContext) {
   try {
     initialContext.close();
   } catch (NamingException e) {
     LOG.unableToCloseInitialContext(e.toString());
   }
 }
示例#9
0
 public void produce(SearchResult result) throws SAXException {
   try {
     produce(result.getName(), result.getAttributes());
   } catch (NamingException except) {
     throw new SAXException(except.toString());
   }
 }
示例#10
0
  /**
   * Process all JNDI entries.
   *
   * @param contextName the context name
   */
  private void processJndiEntries(String contextName) {

    Context initialContext = null;
    try {
      initialContext = new InitialContext();
    } catch (NamingException ne) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, ne.toString(), ne);
      }
    }

    if (initialContext != null) {
      // process environment entries
      for (WebEnvironmentEntry entry : WebEnvironmentEntry.values()) {
        String entryName = entry.getQualifiedName();
        String value = null;

        try {
          value = (String) initialContext.lookup(entryName);
        } catch (NamingException root) {
          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine(root.toString());
          }
        }

        if (value != null) {
          if (LOGGER.isLoggable(Level.INFO)) {
            // special logic for ClientStateSavingPassword
            if (!entry.equals(WebEnvironmentEntry.ClientStateSavingPassword)) {
              if (LOGGER.isLoggable(loggingLevel)) {
                LOGGER.log(
                    loggingLevel,
                    "jsf.config.webconfig.enventryinfo",
                    new Object[] {contextName, entryName, value});
              }
            } else {
              if (LOGGER.isLoggable(loggingLevel)) {
                LOGGER.log(
                    loggingLevel, "jsf.config.webconfig.enventry.clientencrypt", contextName);
              }
            }
          }
          envEntries.put(entry, value);
        }
      }
    }
  }
示例#11
0
  /**
   * Creates a JNDI InitialContext object if none exists yet. Then looks up the string argument and
   * returns the associated object.
   *
   * @param name the name of the object to be looked up
   * @return the object bound to <code>name</code>
   * @throws javax.naming.NamingException if name cannot be found
   */
  public static Object jndiLookup(String name) throws NamingException {
    Object obj = null;

    if (jndiContext == null) {
      try {
        jndiContext = new InitialContext();
      } catch (NamingException e) {
        System.out.println("Could not create JNDI context: " + e.toString());
        throw e;
      }
    }
    try {
      obj = jndiContext.lookup(name);
    } catch (NamingException e) {
      System.out.println("JNDI lookup failed: " + e.toString());
      throw e;
    }
    return obj;
  }
 public void ejbCreate() {
   System.out.println("In SimpleMessageBean.ejbCreate()");
   try {
     jndiContext = new InitialContext();
     queueConnectionFactory =
         (QueueConnectionFactory) jndiContext.lookup("java:comp/env/jms/QCFactory");
     queue = (Queue) jndiContext.lookup("java:comp/env/jms/clientQueue");
   } catch (NamingException e) {
     System.out.println("JNDI lookup failed: " + e.toString());
   }
 }
示例#13
0
  public RewardList findRewardList(String fid) {
    RewardList rewardList = new RewardList();
    try {
      Context weblogicContext = ejbproxy.getInitialConnection();
      RewardListService serviceClient =
          (RewardListService) weblogicContext.lookup("RewardListBean/remote");
      rewardList = serviceClient.findRewardList(fid);

    } catch (NamingException ne) {
      // TODO: handle exception
      System.err.println("不能连接NamingException在:" + ne.toString());
      ne.printStackTrace();
    }

    return rewardList;
  }
示例#14
0
  public List<RewardList> ListRewardList(int offset, int length, HashMap<String, String> map) {
    List<RewardList> listRewardList = new ArrayList<RewardList>();
    try {
      Context weblogicContext = ejbproxy.getInitialConnection();
      RewardListService serviceClient =
          (RewardListService) weblogicContext.lookup("RewardListBean/remote");
      listRewardList = serviceClient.ListRewardList(offset, length, map);

    } catch (NamingException ne) {
      // TODO: handle exception
      System.err.println("不能连接NamingException在:" + ne.toString());
      ne.printStackTrace();
    }

    return listRewardList;
  }
示例#15
0
  public DAO(String dbName) {
    try {
      System.out.println(new InitialContext().getEnvironment());
      Context envCtx = (Context) new InitialContext().lookup("java:comp/env");

      DataSource datasource = (DataSource) envCtx.lookup("jdbc/" + dbName);

      this.conn = datasource.getConnection();

    } catch (NamingException a) {
      System.out.println(a.toString());

    } catch (SQLException a) {
      System.out.println(a.toString());
    }
  }
示例#16
0
  /**
   * Update an entry with the designated DN.
   *
   * @param oldSet the old entry containing teh old set of attributes.
   * @param newSet the new entry containing the replacement set of attributes.
   * @return the operation's success status.
   */
  public boolean updateEntry(DXEntry oldSet, DXEntry newSet) {

    try {
      if (DXAttributes.attributesEqual(oldSet, newSet)) return true; // nothing to do.

      DN nodeDN = newSet.getDN();
      RDN newRDN = nodeDN.getLowestRDN();

      DXAttributes adds =
          null; // use modify-add for new attribute values (inc entirely new attribute)
      DXAttributes reps = null; // use modify-replace for changed attribute values
      DXAttributes dels =
          null; // use modify-delete for deleted attribute values (inc deleting entire attribute)

      reps = DXAttributes.getReplacementSet(newRDN, oldSet, newSet);
      dels = DXAttributes.getDeletionSet(newRDN, oldSet, newSet);
      adds = DXAttributes.getAdditionSet(newRDN, oldSet, newSet);

      /*if (false)
      printDebug(oldSet, newSet, adds, reps, dels);*/

      CBUtility.log("updateNode: ", 4);

      ModificationItem[] mods;

      mods = new ModificationItem[dels.size() + reps.size() + adds.size()];

      int modIndex = 0;
      modIndex = loadMods(mods, dels.getAll(), DirContext.REMOVE_ATTRIBUTE, modIndex);
      modIndex = loadMods(mods, adds.getAll(), DirContext.ADD_ATTRIBUTE, modIndex);
      modIndex = loadMods(mods, reps.getAll(), DirContext.REPLACE_ATTRIBUTE, modIndex);

      return modifyAttributes(nodeDN, mods); // TE: This may fail, returning false.
    } catch (NamingException e) {
      error("Unable to update node " + oldSet.getDN() + "! " + e.toString(), e);
      e.printStackTrace();
      return false;
    } catch (Exception e) {
      error("Unexpected Error updating node " + oldSet.getDN() + "! " + e.toString(), e);
      e.printStackTrace();
      return false;
    }
  }
示例#17
0
  public void handlePageBody(PageContext pc) throws ServletException, IOException {
    ServletContext context = pc.getServletContext();
    Document doc = null;
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      doc = builder.newDocument();
    } catch (Exception e) {
      throw new ServletException(e);
    }

    Element rootElem = doc.createElement("xaf");
    doc.appendChild(rootElem);

    try {
      DatabaseContextFactory.createCatalog(pc, rootElem);
      transform(pc, doc, ACE_CONFIG_ITEM_PROPBROWSERXSL);
    } catch (NamingException e) {
      PrintWriter out = pc.getResponse().getWriter();
      out.write(e.toString());
      e.printStackTrace(out);
    }
  }
示例#18
0
  public void init(ServletConfig cfg) throws javax.servlet.ServletException {
    super.init(cfg);
    logger = Logger.getLogger(LoadingScheduler.class);
    try {
      InitialContext ic = new InitialContext();
      dataSource = (DataSource) ic.lookup("java:comp/env/jdbc/DB");
    } catch (NamingException nmEx) {
      logger.error(FILE_NAME + " naming exception " + nmEx.toString());
    }

    StdSchedulerFactory factory;

    File file = null;
    InputStream is = null;
    String shutdownPref = null;
    Properties quartz_props = null;
    Properties econ_props = null;
    String realPath = null;
    String schedId = null;
    // String	jobName			= "QuoteShop";
    String cronExp = null;
    String seconds = "00";
    String minuts = "00";
    String hours = "10";
    String dayOfMonth = "?";
    String month = "*";
    String dayOfWeek = "1-7";
    JobDetail job = null;
    String jobClass = "JobSchedulerProcess";
    CronTrigger cronTrigger = null;
    logger.info("Scheduler Started............");
    Statement stmt = null;
    Connection connection = null;
    ResultSet rs = null;
    String currencySchedularDtls =
        "SELECT * FROM QMS_QUARTZ_SCHEDULAR_CONFIG WHERE JOBID=1 AND JOBNAME='QuoteShop' AND SCHEDULAR_NAME='currency'";
    try {
      try {
        connection = this.getConnection();
        stmt = connection.createStatement();
        rs = stmt.executeQuery(currencySchedularDtls);
        if (rs.next()) {
          jobName = rs.getString("JOBNAME");
          seconds = rs.getString("TIME_SEC");
          minuts = rs.getString("TIME_MIN");
          ;
          hours = rs.getString("TIME_HRS");
          dayOfMonth = rs.getString("TIME_DAYOFMONTH");
          month = rs.getString("TIME_MONTH");
          dayOfWeek = rs.getString("TIME_DAYOFWEEK");

          logger.info(
              "jobName , sec, min, hrs, dayOfMon, month,dayOfwk :"
                  + jobName
                  + ","
                  + seconds
                  + ","
                  + minuts
                  + ","
                  + hours
                  + ","
                  + dayOfMonth
                  + ","
                  + month
                  + ","
                  + dayOfWeek);
        }
      } catch (Exception e) {
        logger.error(
            FILE_NAME
                + " Error while getting the configuration details for the currencySchedular:"
                + e.getMessage());
        e.printStackTrace();
        throw new ServletException(e);

      } finally {
        try {
          ConnectionUtil.closeConnection(connection, stmt, rs);
        } catch (Exception e) {
          logger.error(FILE_NAME + " Error while closing the connection & statement & ResultSet.");
        }
      }
      shutdownPref = cfg.getInitParameter("shutdown-on-unload");
      if (shutdownPref != null) performShutdown = Boolean.valueOf(shutdownPref).booleanValue();

      // IMPORTANT
      // For SunServer/Glassfish & OC4J [will not work in WebLogic]
      // realPath = cfg.getServletContext().getRealPath("/WEB-INF/quartz.properties");//by
      // subarhmanyam
      // For WebLogic & OC4J [Will not work in SunServer/Glassfish]
      // this configuration required if quartz.properties file is out side the quartz.jar
      /*		if(realPath == null)
      	realPath = cfg.getServletContext().getResource("/WEB-INF/classes/quartz.properties").getPath();
      	//realPath = cfg.getServletContext().getResource("/WEB-INF/quartz.properties").getPath();
      file = new File(realPath);
      is = new FileInputStream(file);
      quartz_props = new Properties();
      quartz_props.load (is);*/
      // factory = new StdSchedulerFactory(quartz_props);
      // ended for quartz.properties outside the quartz.jar file
      factory = new StdSchedulerFactory(); // if quartz.properties is inside the quartz.jar
      cfg.getServletContext().setAttribute(QUARTZ_FACTORY_KEY, factory);

      // Initially SCHEDULER -- will be in PAUSE state so we have to start the scheduler --
      sched = factory.getScheduler();

      logger.info("Scheduler Started     " + sched.toString());
      logger.info("Scheduler Name        " + sched.getSchedulerName());
      logger.info("Scheduler InstanceId  " + sched.getSchedulerInstanceId());

      file = null;
      quartz_props = null;
      econ_props = null;
      // is.close();

      // TriggerScheduler Classes
      factory =
          (StdSchedulerFactory)
              getServletConfig()
                  .getServletContext()
                  .getAttribute("org.quartz.impl.StdSchedulerFactory.KEY");
      sched = factory.getScheduler();
      schedId = sched.getSchedulerInstanceId();
      cronExp =
          seconds + " " + minuts + " " + hours + " " + dayOfMonth + " " + month + " " + dayOfWeek;
      job = new JobDetail(jobName, schedId, Class.forName(jobClass), false, true, false);

      job.setGroup("JG");
      job.setDurability(true);
      job.setJobDataMap(new JobDataMap());
      // sched.deleteJob(jobName,"JG");
      sched.addJob(job, true);

      // job=sched.getJobDetail(jobName,"JG");

      cronTrigger = new CronTrigger("001", "TG", jobName, "JG", cronExp); // Frequency
      cronTrigger.setVolatility(false);

      sched.scheduleJob(cronTrigger);
      logger.info("Before calling  execute().......");
      sched.start();
    } catch (Exception e) {
      logger.info("exception in loading scheduler " + e);
      e.printStackTrace();
      throw new ServletException(e);
    }
  }
示例#19
0
  @Override
  protected List<ConfigIssue> init() {
    List<ConfigIssue> issues = new ArrayList<>();
    try {
      Properties contextProperties = new Properties();
      contextProperties.setProperty(
          javax.naming.Context.INITIAL_CONTEXT_FACTORY, jmsConfig.initialContextFactory);
      contextProperties.setProperty(javax.naming.Context.PROVIDER_URL, jmsConfig.providerURL);
      if (jmsConfig.initialContextFactory.toLowerCase(Locale.ENGLISH).contains("oracle")) {
        contextProperties.setProperty("db_url", jmsConfig.providerURL); // workaround for SDC-2068
      }
      contextProperties.putAll(jmsConfig.contextProperties);

      initialContext = initialContextFactory.create(contextProperties);
    } catch (NamingException ex) {
      LOG.info(
          Utils.format(
              JmsErrors.JMS_00.getMessage(),
              jmsConfig.initialContextFactory,
              jmsConfig.providerURL,
              ex.toString()),
          ex);
      issues.add(
          getContext()
              .createConfigIssue(
                  JmsGroups.JMS.name(),
                  "jmsConfig.initialContextFactory",
                  JmsErrors.JMS_00,
                  jmsConfig.initialContextFactory,
                  jmsConfig.providerURL,
                  ex.toString()));
    }
    if (issues.isEmpty()) {
      try {
        connectionFactory = (ConnectionFactory) initialContext.lookup(jmsConfig.connectionFactory);
      } catch (NamingException ex) {
        LOG.info(
            Utils.format(
                JmsErrors.JMS_01.getMessage(), jmsConfig.initialContextFactory, ex.toString()),
            ex);
        issues.add(
            getContext()
                .createConfigIssue(
                    JmsGroups.JMS.name(),
                    "jmsConfig.initialContextFactory",
                    JmsErrors.JMS_01,
                    jmsConfig.connectionFactory,
                    ex.toString()));
      }
    }
    if (issues.isEmpty()) {
      jmsMessageConsumer =
          jmsMessageConsumerFactory.create(
              initialContext,
              connectionFactory,
              basicConfig,
              credentialsConfig,
              jmsConfig,
              jmsMessageConverter);
      issues.addAll(jmsMessageConsumer.init(getContext()));
    }
    // no dependencies on the above for initialization
    issues.addAll(jmsMessageConverter.init(getContext()));
    return issues;
  }
  /**
   * Returns {@link Item} with addition information in case of user exists and authicated correctly,
   * otherwise null
   *
   * @param username username
   * @param password password
   * @return a list of UserRole or null
   */
  public boolean checkAuthWithLdap(String uid, String password) {

    /*
     * Step 3. search the entry which has the username(in our case is the uid of the entry)
     */
    // List to store the user roles
    ArrayList<String> userRoles = new ArrayList<String>();

    searchCtls.setReturningAttributes(ldapConfig.getReturnattributs());

    // Specify the search scope
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Specifiy the LDAP search filter
    String searchFilter = "(&(uid=" + uid + ") )";

    NamingEnumeration<?> answer;
    try {
      answer = ctx.search(ldapConfig.getSearchbase(), searchFilter, searchCtls);
    } catch (NamingException e) {
      throw new Error("Search engine for LDAP server failed! Java exception: " + e.toString());
    }

    /*
     * Step 4. determin the dn of the found entry
     */

    try {
      if (answer.hasMore()) {

        SearchResult result = (SearchResult) answer.next();
        Attributes attrs = result.getAttributes();
        String dn = result.getNameInNamespace();

        // System.out.println(attrs.toString());

        System.out.println("dn of the entry: " + dn);

        Attribute member = attrs.get("memberOf");

        if (member == null) {
          userRoles.add("unknow_role");
        } else {
          userRoles.addAll(refineMemberInfo(member));
        }

        // System.out.println("UserRole "+i+": "+role);

        Properties env1 = new Properties();
        env1.put(Context.INITIAL_CONTEXT_FACTORY, ldapConfig.getINITIAL_CONTEXT_FACTORY());
        env1.put(Context.PROVIDER_URL, ldapConfig.getPROVIDER_URL());
        env1.put(Context.SECURITY_PRINCIPAL, dn);
        env1.put(Context.SECURITY_CREDENTIALS, password);
        /*
         * Step 5. Open one more connection to ldap with just found DN and password of user
         *
         */
        new InitialDirContext(env1); // in case of problem exception will be threw
        System.out.println("Authentication successful");
        // assign the current user roles
        this.setCurrentUserRoles(userRoles);
        return true;
      } else {
        System.out.println("Your password is wrong");
        return false;
      }
    } catch (NamingException e) {

      /*
       * Step 6. no exception - ok, otherwise user2 has entered wrong password.
       *
       */
      System.out.println("check password throws naming exeception :" + e.toString());
      System.out.println("Your Login or password is wrong");
      return false;
    }
  }
  /**
   * Constructor, set up database connection.
   *
   * @param pType - class instance of E
   * @param pLookUpDataBase look up of the data base
   * @param pSessionUser user session key
   * @param pDataBaseTableName database table name
   * @param pKeyFieldName key field of the database
   * @param pInsertHeadSQL sql statement to insert a new head entry
   * @param pInsertPosSQL sql statement to insert a new head entry (position)
   * @param pReadMinMaxSQL sql statement for min/max read
   * @param pReadNextSQL sql statement to read next key
   * @param pReadPrevSQL sql statement to read previous key
   * @param pReadHeadSQL sql statement to read head entry
   * @param pInvalidateHeadSQL sql statement to invalidate head entry
   * @param pReadPosSQL sql statement to read position entry
   * @param pInvalidatePosSQL sql statement to invalidate position entry
   */
  public AbstractDBHeadPosDateTemplateR(
      final Class<E> pType,
      final String pLookUpDataBase,
      final String pSessionUser,
      final String pDataBaseTableName,
      final String pKeyFieldName,
      final String pInsertHeadSQL,
      final String pInsertPosSQL,
      final String pReadMinMaxSQL,
      final String pReadNextSQL,
      final String pReadPrevSQL,
      final String pReadHeadSQL,
      final String pInvalidateHeadSQL,
      final String pReadPosSQL,
      final String pInvalidatePosSQL) {
    super(
        pType,
        pLookUpDataBase,
        pSessionUser,
        pDataBaseTableName,
        pKeyFieldName,
        pInsertHeadSQL,
        pReadMinMaxSQL,
        pReadNextSQL,
        pReadPrevSQL,
        pReadHeadSQL,
        pInvalidateHeadSQL);

    try {
      // connect to database
      final InitialContext ic = new InitialContext();
      final DataSource lDataSource = (DataSource) ic.lookup(pLookUpDataBase);
      try (final Connection thisDataBase = lDataSource.getConnection()) {

        final DataBaseDepending myDataBaseDepending =
            new DataBaseDepending(thisDataBase.getMetaData().getDatabaseProductName());

        if (pReadPosSQL == null) {
          this.readPosSQL = null;
        } else {
          this.readPosSQL =
              pReadPosSQL
                  .replace("OUTDATE()", myDataBaseDepending.getSQLTimeOutdate())
                  .replace("NOW()", myDataBaseDepending.getSQLTimeNow());
        }

        if (pInvalidatePosSQL == null) {
          this.invalidatePosSQL = null;
        } else {
          this.invalidatePosSQL =
              pInvalidatePosSQL
                  .replace("OUTDATE()", myDataBaseDepending.getSQLTimeOutdate())
                  .replace("NOW()", myDataBaseDepending.getSQLTimeNow());
        }

        if (pInsertPosSQL == null) {
          this.insertPosSQL = null;
        } else {
          this.insertPosSQL =
              pInsertPosSQL
                  .replace("OUTDATE()", myDataBaseDepending.getSQLTimeOutdate())
                  .replace("NOW()", myDataBaseDepending.getSQLTimeNow());
        }
      }
      ic.close();
    } catch (final SQLException e) {
      throw new UnexpectedException(e.toString(), e);
    } catch (final NamingException e) {
      throw new UnexpectedException(e.toString(), e);
    }
  }
示例#22
0
  /**
   * Recursively display the naming context information into the buffer.
   *
   * @param ctx
   * @param indent
   * @param buffer
   * @param verbose
   */
  public static void list(Context ctx, String indent, StringBuffer buffer, boolean verbose) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try {
      NamingEnumeration ne = ctx.list("");
      while (ne.hasMore()) {
        NameClassPair pair = (NameClassPair) ne.next();

        String name = pair.getName();
        String className = pair.getClassName();
        boolean recursive = false;
        boolean isLinkRef = false;
        boolean isProxy = false;
        Class c = null;
        try {
          c = loader.loadClass(className);

          if (Context.class.isAssignableFrom(c)) recursive = true;
          if (LinkRef.class.isAssignableFrom(c)) isLinkRef = true;

          isProxy = Proxy.isProxyClass(c);
        } catch (ClassNotFoundException cnfe) {
          // If this is a $Proxy* class its a proxy
          if (className.startsWith("$Proxy")) {
            isProxy = true;
            // We have to get the class from the binding
            try {
              Object p = ctx.lookup(name);
              c = p.getClass();
            } catch (NamingException e) {
              Throwable t = e.getRootCause();
              if (t instanceof ClassNotFoundException) {
                // Get the class name from the exception msg
                String msg = t.getMessage();
                if (msg != null) {
                  // Reset the class name to the CNFE class
                  className = msg;
                }
              }
            }
          }
        }

        buffer.append(indent + " +- " + name);

        // Display reference targets
        if (isLinkRef) {
          // Get the
          try {
            Object obj = ctx.lookupLink(name);

            LinkRef link = (LinkRef) obj;
            buffer.append("[link -> ");
            buffer.append(link.getLinkName());
            buffer.append(']');
          } catch (Throwable t) {
            buffer.append("invalid]");
          }
        }

        // Display proxy interfaces
        if (isProxy) {
          buffer.append(" (proxy: " + pair.getClassName());
          if (c != null) {
            Class[] ifaces = c.getInterfaces();
            buffer.append(" implements ");
            for (int i = 0; i < ifaces.length; i++) {
              buffer.append(ifaces[i]);
              buffer.append(',');
            }
            buffer.setCharAt(buffer.length() - 1, ')');
          } else {
            buffer.append(" implements " + className + ")");
          }
        } else if (verbose) {
          buffer.append(" (class: " + pair.getClassName() + ")");
        }

        buffer.append('\n');
        if (recursive) {
          try {
            Object value = ctx.lookup(name);
            if (value instanceof Context) {
              Context subctx = (Context) value;
              list(subctx, indent + " |  ", buffer, verbose);
            } else {
              buffer.append(indent + " |   NonContext: " + value);
              buffer.append('\n');
            }
          } catch (Throwable t) {
            buffer.append("Failed to lookup: " + name + ", errmsg=" + t.getMessage());
            buffer.append('\n');
          }
        }
      }
      ne.close();
    } catch (NamingException ne) {
      buffer.append("error while listing context " + ctx.toString() + ": " + ne.toString(true));
      formatException(buffer, ne);
    }
  }