/**
   * Create MBean for Object. Attempts to create an MBean for the object by searching the package
   * and class name space. For example an object of the type
   *
   * <PRE>
   *   class com.acme.MyClass extends com.acme.util.BaseClass
   * </PRE>
   *
   * Then this method would look for the following classes:
   *
   * <UL>
   *   <LI>com.acme.MyClassMBean
   *   <LI>com.acme.jmx.MyClassMBean
   *   <LI>com.acme.util.BaseClassMBean
   *   <LI>com.acme.util.jmx.BaseClassMBean
   * </UL>
   *
   * @param o The object
   * @return A new instance of an MBean for the object or null.
   */
  public static ModelMBean mbeanFor(Object o) {
    try {
      Class oClass = o.getClass();
      ClassLoader loader = oClass.getClassLoader();

      ModelMBean mbean = null;
      boolean jmx = false;
      Class[] interfaces = null;
      int i = 0;

      while (mbean == null && oClass != null) {
        Class focus = interfaces == null ? oClass : interfaces[i];
        String pName = focus.getPackage().getName();
        String cName = focus.getName().substring(pName.length() + 1);
        String mName = pName + (jmx ? ".jmx." : ".") + cName + "MBean";

        try {
          Class mClass = loader.loadClass(mName);
          if (log.isTraceEnabled()) log.trace("mbeanFor " + o + " mClass=" + mClass);
          mbean = (ModelMBean) mClass.newInstance();
          mbean.setManagedResource(o, "objectReference");
          if (log.isDebugEnabled()) log.debug("mbeanFor " + o + " is " + mbean);
          return mbean;
        } catch (ClassNotFoundException e) {
          if (e.toString().endsWith("MBean")) {
            if (log.isTraceEnabled()) log.trace(e.toString());
          } else log.warn(LogSupport.EXCEPTION, e);
        } catch (Error e) {
          log.warn(LogSupport.EXCEPTION, e);
          mbean = null;
        } catch (Exception e) {
          log.warn(LogSupport.EXCEPTION, e);
          mbean = null;
        }

        if (jmx) {
          if (interfaces != null) {
            i++;
            if (i >= interfaces.length) {
              interfaces = null;
              oClass = oClass.getSuperclass();
            }
          } else {
            interfaces = oClass.getInterfaces();
            i = 0;
            if (interfaces == null || interfaces.length == 0) {
              interfaces = null;
              oClass = oClass.getSuperclass();
            }
          }
        }
        jmx = !jmx;
      }
    } catch (Exception e) {
      LogSupport.ignore(log, e);
    }
    return null;
  }
  // get drivername, user, pw & server, and return connection id
  public void serve(InputStream i, OutputStream o) throws IOException {
    // TODOServiceList.getSingleInstance();
    initialize();
    NameListMessage nameListMessage = null;

    try {
      // read input to know which target panel is required
      ObjectInputStream input = new ObjectInputStream(i);
      nameListMessage = (NameListMessage) input.readObject();

      // parse the required panel
      parseSqlFile(nameListMessage);

    } catch (ClassNotFoundException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
      nameListMessage.errorMessage = ex.toString();
    }

    // send object to the caller
    ObjectOutputStream output = new ObjectOutputStream(o);
    output.writeObject(nameListMessage);

    // end socket connection
    o.close();
    i.close();
  }
Esempio n. 3
0
 public void readFields(DataInput in) throws IOException {
   String className = UTF8.readString(in);
   declaredClass = PRIMITIVE_NAMES.get(className);
   if (declaredClass == null) {
     try {
       declaredClass = getConf().getClassByName(className);
     } catch (ClassNotFoundException e) {
       throw new RuntimeException(e.toString());
     }
   }
 }
Esempio n. 4
0
 private static Object readRealObject(byte type, InputStream is, ClassLoader loader)
     throws IOException {
   try {
     if (type == 0) {
       return PDataStream.readUTF(is);
     } else if (type == 1) {
       return new Integer(PDataStream.readInt(is));
     } else if (type == 2) {
       return new Long(PDataStream.readLong(is));
     } else if (type == 3) {
       return new Byte((byte) is.read());
     } else if (type == 4) {
       return PDataStream.readBoolean(is) ? Boolean.TRUE : Boolean.FALSE;
     } else if (type == 5) {
       return new Character(PDataStream.readChar(is));
     } else if (type == 6) {
       return new Short(PDataStream.readShort(is));
     } else if (type == 7) {
       return new Float(PDataStream.readFloat(is));
     } else if (type == 8) {
       return new Double(PDataStream.readDouble(is));
     } else if (type == 11) {
       String name = PDataStream.readUTF(is);
       Class c = loader == null ? Class.forName(name) : loader.loadClass(name);
       if (Externalizable.class.isAssignableFrom(c)) {
         Externalizable obj = (Externalizable) c.newInstance();
         obj.readObject(is);
         return obj;
       }
       throw new IOException("Could not read object " + name);
     } else if (type == 12) {
       ObjectInputStream in =
           loader == null
               ? new ObjectInputStream(is)
               : (ObjectInputStream) new XObjectInputStream(loader, is);
       return in.readObject();
     }
   } catch (ClassNotFoundException cnfe) {
     throw new IOException("Could not find class " + cnfe.toString());
   } catch (Exception exc) {
     throw exc instanceof IOException
         ? (IOException) exc
         : new IOException("Could not read object " + exc.toString());
   }
   throw new IllegalArgumentException("Unsupported Typed Object: " + type);
 }
  /*
   * This test creates an object and registers it with a unit of work.  It then serializes that
   * object and deserializes it.  Adds an object onto the origional then performs serialization
   * sequence again.  Then deepMergeClone is attempted and the results are compared to verify that
   * the merge worked.
   */
  public void test() {
    try {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      ObjectOutputStream stream = new ObjectOutputStream(byteStream);

      // create the phoneNumber object
      Session session = getSession();
      UnitOfWork uow = session.acquireUnitOfWork();
      this.deptObject =
          (Dept)
              session.readObject(
                  Dept.class,
                  new org.eclipse.persistence.expressions.ExpressionBuilder()
                      .get("deptno")
                      .equal(5.0));
      Dept deptClone = (Dept) uow.registerObject(this.deptObject);

      // force instantiations of value holders before serialization
      deptClone.getEmpCollection().size();
      Emp empClone = null;
      if ((deptClone.getEmpCollection() != null) && (deptClone.getEmpCollection().size() > 1)) {
        empClone = (Emp) deptClone.getEmpCollection().iterator().next();
        deptClone.getEmpCollection().remove(empClone);
        empClone.setDeptno(null);
      }

      // serialize object by writing to a stream
      stream.writeObject(deptClone);
      stream.writeObject(empClone);
      stream.flush();
      byte[] arr = byteStream.toByteArray();
      ByteArrayInputStream inByteStream = new ByteArrayInputStream(arr);
      ObjectInputStream inObjStream = new ObjectInputStream(inByteStream);
      Dept deserialDept;
      Emp deserialEmp = null;

      // deserialize the object
      try {
        deserialDept = (Dept) inObjStream.readObject();
        deserialEmp = (Emp) inObjStream.readObject();

      } catch (ClassNotFoundException e) {
        throw new TestErrorException("Could not deserialize object " + e.toString());
      }

      // add a new manager, test 1-m's
      /*            if (deserialDept.getEmpCollection() != null && deserialDept.getEmpCollection().size() > 1) {
                    deserialEmp =  (Emp)deserialDept.getEmpCollection().iterator().next();
                    deserialDept.getEmpCollection().remove(deserialEmp);
                    deserialEmp.setDeptno(null);
                }
      */
      deserialDept.getEmpCollection().add(deserialEmp);
      deserialEmp.setDeptno(deserialDept);
      int collectionSize = deserialDept.getEmpCollection().size();

      byteStream = new ByteArrayOutputStream();
      stream = new ObjectOutputStream(byteStream);
      // send the ammended object back through the serialization process
      stream.writeObject(deserialDept);
      stream.flush();
      arr = byteStream.toByteArray();
      inByteStream = new ByteArrayInputStream(arr);
      inObjStream = new ObjectInputStream(inByteStream);
      try {
        deserialDept = (Dept) inObjStream.readObject();
      } catch (ClassNotFoundException e) {
        throw new TestErrorException("Could not deserialize object " + e.toString());
      }

      // merge the ammended clone with the unit of work
      deptClone = (Dept) uow.deepMergeClone(deserialDept);
      if (deptClone.getEmpCollection().size() != collectionSize) {
        throw new TestErrorException("Failed to merge the collection correctly not enough Emps");
      }
      for (Iterator iterator = deptClone.getEmpCollection().iterator(); iterator.hasNext(); ) {
        Emp emp = (Emp) iterator.next();
        if (emp.getDeptno() != deptClone) {
          throw new TestErrorException("Failed to merge the back pointer");
        }
      }
      uow.commit();
    } catch (IOException e) {
      throw new TestErrorException("Error running Test " + e.toString());
    }
  }
  public Properties parseURL(String url, Properties defaults) throws java.sql.SQLException {
    Properties urlProps = (defaults != null) ? new Properties(defaults) : new Properties();

    if (url == null) {
      return null;
    }

    if (!StringUtils.startsWithIgnoreCase(url, URL_PREFIX)
        && !StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)
        && !StringUtils.startsWithIgnoreCase(url, LOADBALANCE_URL_PREFIX)
        && !StringUtils.startsWithIgnoreCase(url, REPLICATION_URL_PREFIX)) { // $NON-NLS-1$

      return null;
    }

    int beginningOfSlashes = url.indexOf("//");

    if (StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)) {
      urlProps.setProperty(
          "socketFactory", "com.mysql.management.driverlaunched.ServerLauncherSocketFactory");
    }

    /*
     * Parse parameters after the ? in the URL and remove them from the
     * original URL.
     */
    int index = url.indexOf("?"); // $NON-NLS-1$

    if (index != -1) {
      String paramString = url.substring(index + 1, url.length());
      url = url.substring(0, index);

      StringTokenizer queryParams = new StringTokenizer(paramString, "&"); // $NON-NLS-1$

      while (queryParams.hasMoreTokens()) {
        String parameterValuePair = queryParams.nextToken();

        int indexOfEquals = StringUtils.indexOfIgnoreCase(0, parameterValuePair, "=");

        String parameter = null;
        String value = null;

        if (indexOfEquals != -1) {
          parameter = parameterValuePair.substring(0, indexOfEquals);

          if (indexOfEquals + 1 < parameterValuePair.length()) {
            value = parameterValuePair.substring(indexOfEquals + 1);
          }
        }

        if ((value != null && value.length() > 0)
            && (parameter != null && parameter.length() > 0)) {
          try {
            urlProps.put(parameter, URLDecoder.decode(value, "UTF-8"));
          } catch (UnsupportedEncodingException badEncoding) {
            // punt
            urlProps.put(parameter, URLDecoder.decode(value));
          } catch (NoSuchMethodError nsme) {
            // punt again
            urlProps.put(parameter, URLDecoder.decode(value));
          }
        }
      }
    }

    url = url.substring(beginningOfSlashes + 2);

    String hostStuff = null;

    int slashIndex = url.indexOf("/"); // $NON-NLS-1$

    if (slashIndex != -1) {
      hostStuff = url.substring(0, slashIndex);

      if ((slashIndex + 1) < url.length()) {
        urlProps.put(
            DBNAME_PROPERTY_KEY, //$NON-NLS-1$
            url.substring((slashIndex + 1), url.length()));
      }
    } else {
      hostStuff = url;
    }

    if ((hostStuff != null) && (hostStuff.length() > 0)) {
      urlProps.put(HOST_PROPERTY_KEY, hostStuff); // $NON-NLS-1$
    }

    String propertiesTransformClassName = urlProps.getProperty(PROPERTIES_TRANSFORM_KEY);

    if (propertiesTransformClassName != null) {
      try {
        ConnectionPropertiesTransform propTransformer =
            (ConnectionPropertiesTransform)
                Class.forName(propertiesTransformClassName).newInstance();

        urlProps = propTransformer.transformProperties(urlProps);
      } catch (InstantiationException e) {
        throw SQLError.createSQLException(
            "Unable to create properties transform instance '"
                + propertiesTransformClassName
                + "' due to underlying exception: "
                + e.toString(),
            SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
      } catch (IllegalAccessException e) {
        throw SQLError.createSQLException(
            "Unable to create properties transform instance '"
                + propertiesTransformClassName
                + "' due to underlying exception: "
                + e.toString(),
            SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
      } catch (ClassNotFoundException e) {
        throw SQLError.createSQLException(
            "Unable to create properties transform instance '"
                + propertiesTransformClassName
                + "' due to underlying exception: "
                + e.toString(),
            SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
      }
    }

    if (Util.isColdFusion()
        && urlProps.getProperty("autoConfigureForColdFusion", "true").equalsIgnoreCase("true")) {
      String configs = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY);

      StringBuffer newConfigs = new StringBuffer();

      if (configs != null) {
        newConfigs.append(configs);
        newConfigs.append(",");
      }

      newConfigs.append("coldFusion");

      urlProps.setProperty(USE_CONFIG_PROPERTY_KEY, newConfigs.toString());
    }

    // If we use a config, it actually should get overridden by anything in
    // the URL or passed-in properties

    String configNames = null;

    if (defaults != null) {
      configNames = defaults.getProperty(USE_CONFIG_PROPERTY_KEY);
    }

    if (configNames == null) {
      configNames = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY);
    }

    if (configNames != null) {
      List splitNames = StringUtils.split(configNames, ",", true);

      Properties configProps = new Properties();

      Iterator namesIter = splitNames.iterator();

      while (namesIter.hasNext()) {
        String configName = (String) namesIter.next();

        try {
          InputStream configAsStream =
              getClass().getResourceAsStream("configs/" + configName + ".properties");

          if (configAsStream == null) {
            throw SQLError.createSQLException(
                "Can't find configuration template named '" + configName + "'",
                SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
          }
          configProps.load(configAsStream);
        } catch (IOException ioEx) {
          throw SQLError.createSQLException(
              "Unable to load configuration template '"
                  + configName
                  + "' due to underlying IOException: "
                  + ioEx,
              SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
        }
      }

      Iterator propsIter = urlProps.keySet().iterator();

      while (propsIter.hasNext()) {
        String key = propsIter.next().toString();
        String property = urlProps.getProperty(key);
        configProps.setProperty(key, property);
      }

      urlProps = configProps;
    }

    // Properties passed in should override ones in URL

    if (defaults != null) {
      Iterator propsIter = defaults.keySet().iterator();

      while (propsIter.hasNext()) {
        String key = propsIter.next().toString();
        String property = defaults.getProperty(key);
        urlProps.setProperty(key, property);
      }
    }

    return urlProps;
  }