/**
   * 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;
  }
Beispiel #2
0
 public String generateInterfaceScriptAngular(String csp, String scriptName) {
   RemoteRequestProxy module;
   try {
     module = RemoteRequestProxy.getModule(scriptName, null, null);
   } catch (ClassNotFoundException ignore) {
     logger.log(Level.SEVERE, ignore.toString());
     return "";
   }
   StringBuilder buffer = new StringBuilder();
   // defines the java classes in the global context
   for (Method method : module.getMethodList()) {
     String methodName = method.getName();
     // Is it on the list of banned names
     if (Json.isReserved(methodName)) continue;
     Class<?>[] paramTypes = method.getParameterTypes();
     // Create the function definition
     buffer.append("     " + methodName + ": function(  ");
     for (int j = 0; j < paramTypes.length; j++) buffer.append("p").append(j).append(", ");
     buffer.setLength(buffer.length() - 2);
     buffer.append(") {\n  return this._execute('");
     buffer.append(scriptName);
     buffer.append("', '");
     buffer.append(methodName);
     buffer.append("\', arguments); },\n");
   }
   return buffer.toString();
 }
  protected Object reifyCall(
      String className,
      String methodName,
      Class<?>[] parameterTypes,
      Object[] effectiveParameters,
      short priority) {
    try {
      return this.proxy.reify(
          MethodCall.getComponentMethodCall(
              Class.forName(className).getDeclaredMethod(methodName, parameterTypes),
              effectiveParameters,
              null,
              (String) null,
              null,
              priority));

      // functional interface name is null
    } catch (NoSuchMethodException e) {
      throw new ProActiveRuntimeException(e.toString());
    } catch (ClassNotFoundException e) {
      throw new ProActiveRuntimeException(e.toString());
    } catch (Throwable e) {
      throw new ProActiveRuntimeException(e.toString());
    }
  }
  /**
   * Use strict mode to determine app bottlenecks.
   *
   * <p>Does nothing if api version is less than 11.
   */
  @TargetApi(11)
  private static void initStrictMode() {

    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
      return;
    }

    StrictMode.setThreadPolicy(
        new StrictMode.ThreadPolicy.Builder()
            .detectCustomSlowCalls()
            .detectDiskReads()
            .detectDiskWrites()
            .detectNetwork()
            .penaltyLog()
            .penaltyFlashScreen()
            .build());

    try {
      StrictMode.setVmPolicy(
          new StrictMode.VmPolicy.Builder()
              .detectLeakedSqlLiteObjects()
              .detectLeakedClosableObjects()
              .setClassInstanceLimit(Class.forName(PlaybackService.class.getName()), 1)
              .penaltyLog()
              .build());
    } catch (ClassNotFoundException e) {
      Log.e(TAG, e.toString());
    }
  }
  /** Creates the SSL ServerSocket. */
  public static QServerSocket createJNI(InetAddress host, int port) throws IOException {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Class cl = Class.forName("com.caucho.vfs.JniServerSocketImpl", false, loader);

      Method method = cl.getMethod("create", new Class[] {String.class, int.class});

      String hostAddress;

      if (host != null) hostAddress = host.getHostAddress();
      else {
        hostAddress = null;
      }

      try {
        return (QServerSocket) method.invoke(null, hostAddress, port);
      } catch (InvocationTargetException e) {
        throw e.getTargetException();
      }
    } catch (IOException e) {
      throw e;
    } catch (ClassNotFoundException e) {
      log.fine(e.toString());

      throw new IOException(L.l("JNI Socket support requires Resin Professional."));
    } catch (Throwable e) {
      log.log(Level.FINE, e.toString(), e);

      throw new IOException(L.l("JNI Socket support requires Resin Professional."));
    }
  }
  @Override
  public String prepareResponse(String className, Object o) throws ParseException {
    try {
      Class clazz = Class.forName(className);

      JAXBContext jaxbContext = JAXBContext.newInstance(clazz.getPackage().getName());
      Marshaller marshaller = jaxbContext.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      marshaller.marshal(clazz.cast(o), byteArrayOutputStream);

      return byteArrayOutputStream.toString();

    } catch (JAXBException e) {
      throw new ParseException(
          "Error occured during the parsing of request's XML body. The details of the exception "
              + e.toString(),
          0);
    } catch (ClassNotFoundException e) {
      throw new ParseException(
          "Error occured during the parsing of request's XML body. The details of the exception "
              + e.toString(),
          0);
    }
  }
  // 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();
  }
  /* Constructeur : ouvre la connexion */
  private ConnexionMySQL() {
    try {
      Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException classe) {
      System.out.println(classe.toString());
    }
    connected = false;

    url = "jdbc:mysql://localhost/tfe_memoir"; // en local
    // String url = "jdbc:mysql://sql.info.iepscf-uccle.be/sonneville"; //à l'école
    try {
      /* setup the properties: si les accents ne sont pas Unicode ds la BDD
      java.util.Properties prop = new java.util.Properties();
      prop.put("charSet", "ISO-8859-15");
      prop.put("user", username);
      prop.put("password", password);*/

      // Connect to the database
      conn = DriverManager.getConnection(url, "root", ""); // en local
      // conn=DriverManager.getConnection(url, "sonneville",""); // à l'école

      stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
      // on peut parcourir le résultat dans les 2 sens, insensible aux chgmts d'autrui
      // on peut modifier ce résultat pour ensuite reporter ces modifs ds la table (updateRow)
      conn.setAutoCommit(false);
      connected = true;
    } catch (SQLException e) {
      System.out.println(e.toString());
    }
  }
 /**
  * This function loads a class from file into the JVM given its fully-qualified name.
  *
  * @param classInfo the fully-qualified class name
  * @return a Class object representing the class name if such a class is defined, otherwise null
  */
 private static Class<?> getClass(String classInfo) {
   try {
     return ClassLoader.getSystemClassLoader().loadClass(classInfo);
   } catch (ClassNotFoundException e) {
     throw new RuntimeException(e.toString());
   }
 }
Beispiel #10
0
  public void invoke(Request request, Response response) throws IOException, ServletException {

    String servletName = ((HttpServletRequest) request).getRequestURI();
    servletName = servletName.substring(servletName.lastIndexOf("/") + 1);
    URLClassLoader loader = null;
    try {
      URL[] urls = new URL[1];
      URLStreamHandler streamHandler = null;
      File classPath = new File(WEB_ROOT);
      String repository =
          (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
      urls[0] = new URL(null, repository, streamHandler);
      loader = new URLClassLoader(urls);
    } catch (IOException e) {
      System.out.println(e.toString());
    }
    Class myClass = null;
    try {
      myClass = loader.loadClass(servletName);
    } catch (ClassNotFoundException e) {
      System.out.println(e.toString());
    }

    Servlet servlet = null;

    try {
      servlet = (Servlet) myClass.newInstance();
      servlet.service((HttpServletRequest) request, (HttpServletResponse) response);
    } catch (Exception e) {
      System.out.println(e.toString());
    } catch (Throwable e) {
      System.out.println(e.toString());
    }
  }
  @Override
  public boolean deleteAll(List<Role> entities) throws SQLException {
    boolean retval = false;

    try {

      con = new DBConnection();

      if (con.connect()) {

        Iterator<Role> iterator = entities.iterator();

        while (iterator.hasNext()) {

          Role entity = iterator.next();

          cstmt = (CallableStatement) con.getConnection().prepareCall("{call sp_del_role(?)}");
          cstmt.setString(1, entity.getRolename());

          con.customQuery(cstmt);
        }
      }

      retval = true;

    } catch (ClassNotFoundException ex) {
      logger.log(Priority.ERROR, ex.toString());
    } catch (SQLException ex) {
      throw ex;
    } finally {
      con.disconnect();
    }
    return retval;
  }
  /**
   * Authenticates to the Database Server using the provided bind request.
   *
   * @param request The bind request.
   * @return The result of the operation.
   * @throws ErrorResultException If the result code indicates that the request failed for some
   *     reason.
   * @throws ClassNotFoundException If no definition for the class with the specified driver name
   *     could be found.
   * @throws SQLException If the driver could not establish a connection with the Database Server.
   */
  @Override
  public BindResult bind(final BindRequest request) throws ErrorResultException {
    BindResult r;

    // Extract user name and password from the bind request.
    final String userName = request.getName();
    final String userPass;
    byte[] password = null;

    if (request instanceof SimpleBindRequest) {
      password = ((SimpleBindRequest) request).getPassword();
    } else {
      r = Responses.newBindResult(ResultCode.PROTOCOL_ERROR);
      return r;
    }
    userPass = new String(password);

    // Establish SQL connection to the Database Server.
    try {
      Class.forName(driverName);
      this.connection = DriverManager.getConnection(this.connectionUrl, userName, userPass);
    } catch (ClassNotFoundException e) {
      System.out.println(e.toString());
      r = Responses.newBindResult(ResultCode.OTHER);
      return r;
    } catch (SQLException e) {
      System.out.println(e.toString());
      r = Responses.newBindResult(ResultCode.CLIENT_SIDE_CONNECT_ERROR);
      return r;
    }
    r = Responses.newBindResult(ResultCode.SUCCESS);
    return r;
  }
  static Vector loadPrefs(
      String f, DataAccessPoint sourceDb, DataAccessPoint targetDb, Traceable tracer) {

    TransferTable t;
    Vector tTable = null;

    try {
      FileInputStream fis = new FileInputStream(f);
      ObjectInputStream ois = new ObjectInputStream(fis);

      tTable = (Vector) ois.readObject();

      for (int i = 0; i < tTable.size(); i++) {
        t = (TransferTable) tTable.elementAt(i);
        t.tracer = tracer;
        t.sourceDb = (TransferDb) sourceDb;
        t.destDb = targetDb;
      }
    } catch (ClassNotFoundException e) {
      System.out.println("class not found pb in LoadPrefs : " + e.toString());

      tTable = new Vector();
    } catch (IOException e) {
      System.out.println("IO pb in LoadPrefs : actionPerformed" + e.toString());

      tTable = new Vector();
    }

    return (tTable);
  }
  @Override
  public boolean delete(String key) throws SQLException {
    boolean retval = false;
    ResultSet rs = null;

    try {

      con = new DBConnection();

      if (con.connect()) {

        cstmt = (CallableStatement) con.getConnection().prepareCall("{call sp_del_role(?)}");

        cstmt.setString(1, key);

        rs = con.customQuery(cstmt);
      }

      retval = true;

    } catch (ClassNotFoundException ex) {
      logger.log(Priority.ERROR, ex.toString());
    } catch (SQLException ex) {
      throw ex;
    } finally {
      con.disconnect();
    }

    return retval;
  }
 private int test02SendSmsReflect2(long subId) {
   try {
     String packageName = ActivityThread.currentPackageName();
     Log.i(TAG, "test02SendSmsReflect2 " + packageName + ", " + smsNumber());
     Method method =
         Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
     method.setAccessible(true);
     IBinder binder = (IBinder) method.invoke(null, new Object[] {"isms"});
     ISms simISms = (ISms) ISms.Stub.asInterface(binder);
     byte[] bytes = "SMS message (Reflect 2)".getBytes("GBK");
     simISms.sendDataForSubscriber(subId, packageName, smsNumber(), null, 0, bytes, null, null);
     return MSG_TEST_FINISH;
   } catch (ClassNotFoundException e) {
     Log.e(TAG, e.toString());
   } catch (NoSuchMethodException e) {
     Log.e(TAG, e.toString());
   } catch (InvocationTargetException e) {
     Log.e(TAG, e.toString());
   } catch (IllegalAccessException e) {
     Log.e(TAG, e.toString());
   } catch (UnsupportedEncodingException e) {
     Log.e(TAG, e.toString());
   } catch (RemoteException e) {
     Log.e(TAG, e.toString());
   }
   return MSG_TEST_FAILED;
 }
 private int test02SendSmsReflect3(long subId) {
   try {
     String packageName = ActivityThread.currentPackageName();
     Log.i(TAG, "test02SendSmsReflect3 " + packageName + ", " + smsNumber());
     Method method =
         Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
     method.setAccessible(true);
     IBinder binder = (IBinder) method.invoke(null, new Object[] {"isms"});
     ISms simISms = (ISms) ISms.Stub.asInterface(binder);
     List<String> parts = new ArrayList<String>();
     parts.add("SMS message (Reflect 3)");
     List<PendingIntent> intents = new ArrayList<PendingIntent>();
     intents.add(null);
     simISms.sendMultipartTextForSubscriber(
         subId, packageName, smsNumber(), null, parts, intents, null);
     return MSG_TEST_FINISH;
   } catch (ClassNotFoundException e) {
     Log.e(TAG, e.toString());
   } catch (NoSuchMethodException e) {
     Log.e(TAG, e.toString());
   } catch (InvocationTargetException e) {
     Log.e(TAG, e.toString());
   } catch (IllegalAccessException e) {
     Log.e(TAG, e.toString());
   } catch (RemoteException e) {
     Log.e(TAG, e.toString());
   }
   return MSG_TEST_FAILED;
 }
Beispiel #17
0
  /** Parses the services file, looking for PHP services. */
  private void parseServicesModule(ReadStream in)
      throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    String line;

    while ((line = in.readLine()) != null) {
      int p = line.indexOf('#');

      if (p >= 0) {
        line = line.substring(0, p);
      }

      line = line.trim();

      if (line.length() > 0) {
        String className = line;

        try {
          Class cl;
          try {
            cl = Class.forName(className, false, loader);
          } catch (ClassNotFoundException e) {
            throw new ClassNotFoundException(L.l("'{0}' not valid {1}", className, e.toString()));
          }

          introspectPhpModuleClass(cl);
        } catch (Throwable e) {
          log.log(Level.FINE, "Failed loading {0}\n{1}", new Object[] {className, e.toString()});
          log.log(Level.FINE, e.toString(), e);
        }
      }
    }
  }
Beispiel #18
0
 public String generateInterfaceScript(String csp, String scriptName) {
   RemoteRequestProxy module;
   try {
     module = RemoteRequestProxy.getModule(scriptName, null, null);
   } catch (ClassNotFoundException ignore) {
     logger.log(Level.SEVERE, ignore.toString());
     return "";
   }
   StringBuilder buffer = new StringBuilder();
   // defines the java classes in the global context
   buffer.append(
       "\n(function() {  var _ = window; if (_." + scriptName + " == undefined) {\n    var p;");
   buffer.append("p = {}; p._path = '" + csp + "';\n");
   for (Method method : module.getMethodList()) {
     String methodName = method.getName();
     // Is it on the list of banned names
     if (Json.isReserved(methodName)) continue;
     Class<?>[] paramTypes = method.getParameterTypes();
     // Create the function definition
     buffer.append("p." + methodName + " = function(  ");
     for (int j = 0; j < paramTypes.length; j++) buffer.append("p").append(j).append(", ");
     buffer.setLength(buffer.length() - 2);
     buffer.append(") {\n  return brijj._execute(p._path, '");
     buffer.append(scriptName);
     buffer.append("', '");
     buffer.append(methodName);
     buffer.append("\', arguments); };\n");
   }
   buffer.append("    _." + scriptName + "=p; } })();\n");
   return buffer.toString();
 }
Beispiel #19
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Statement stmt;
    ResultSet rs;
    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
      String connectionUrl = "jdbc:mysql://localhost/myflickr?" + "user=root&password=123456";
      con = DriverManager.getConnection(connectionUrl);

      if (con != null) {
        System.out.println("connected to mysql");
      }
    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e.toString());
    } catch (ClassNotFoundException cE) {
      System.out.println("Class Not Found Exception: " + cE.toString());
    }

    try {
      stmt = con.createStatement();

      System.out.println("SELECT * FROM flickrusers WHERE name='" + username + "'");
      rs = stmt.executeQuery("SELECT * FROM flickrusers WHERE name='" + username + "'");

      while (rs.next()) {

        if (rs.getObject(1).toString().equals(username)) {

          out.println("<h1>To username pou epileksate uparxei hdh</h1>");
          out.println("<a href=\"project3.html\">parakalw dokimaste kapoio allo.</a>");

          stmt.close();
          rs.close();
          return;
        }
      }
      stmt.close();
      rs.close();

      stmt = con.createStatement();

      if (!stmt.execute("INSERT INTO flickrusers VALUES('" + username + "', '" + password + "')")) {
        out.println("<h1>Your registration is completed  " + username + "</h1>");
        out.println("<a href=\"index.jsp\">go to the login menu</a>");
        registerListener.Register(username);
      } else {
        out.println("<h1>To username pou epileksate uparxei hdh</h1>");
        out.println("<a href=\"project3.html\">Register</a>");
      }
    } catch (SQLException e) {
      throw new ServletException("Servlet Could not display records.", e);
    }
  }
  public void process(Request request, Response response) {

    String uri = request.getUri();
    String servletName = uri.substring(uri.lastIndexOf("/") + 1);
    URLClassLoader loader = null;

    try {
      // create a URLClassLoader
      URL[] urls = new URL[1];
      URLStreamHandler streamHandler = null;
      File classPath = new File(Constants.WEB_ROOT);
      // the forming of repository is taken from the createClassLoader method in
      // org.apache.catalina.startup.ClassLoaderFactory
      String repository =
          (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
      // the code for forming the URL is taken from the addRepository method in
      // org.apache.catalina.loader.StandardClassLoader class.
      urls[0] = new URL(null, repository, streamHandler);
      loader = new URLClassLoader(urls);
    } catch (IOException e) {
      System.out.println(e.toString());
    }
    Class myClass = null;
    try {
      myClass = loader.loadClass(servletName);
    } catch (ClassNotFoundException e) {
      System.out.println(e.toString());
    }

    Servlet servlet = null;

    try {
      servlet = (Servlet) myClass.newInstance();
      servlet.service((ServletRequest) request, (ServletResponse) response);
    } catch (Exception e) {
      System.out.println(e.toString());
    } catch (Throwable e) {
      System.out.println(e.toString());
    }
    // this is  to run application1 by another way
    /*
    	 *  URL myUrl[]={new URL("file:///D:/github/Toy-Tomcat/Tomcat/TOMCAT/src/")};
    	  URLClassLoader x = new URLClassLoader(myUrl);
    	    Class myClass = x.loadClass("test.PrimitiveServlet");
        Servlet servlet = null;

        try {
          servlet = (Servlet) myClass.newInstance();
          servlet.service((ServletRequest) request, (ServletResponse) response);
        }
        catch (Exception e) {
          System.out.println(e.toString());
        }
        catch (Throwable e) {
          System.out.println(e.toString());
        }
    */
  }
Beispiel #21
0
 public final Class getDefaultImplementation(Class javaContentInterface) {
   try {
     // by caching the obtained Class objects.
     return Class.forName(
         (String) defaultImplementationMap.get(javaContentInterface), true, classLoader);
   } catch (ClassNotFoundException e) {
     throw new NoClassDefFoundError(e.toString());
   }
 }
Beispiel #22
0
 private static boolean isValidTest(String name) {
   try {
     return name.endsWith(SUFFIX)
         && ((Class.forName(name).getModifiers() & Modifier.ABSTRACT) == 0);
   } catch (ClassNotFoundException e) {
     System.err.println(e.toString());
     return false;
   }
 }
 protected void myInitPool() throws SQLException {
   try {
     Class.forName(getDriverName());
   } catch (ClassNotFoundException ex) {
     throw new SQLException("Driver Class Not Found", ex.toString());
   }
   pHelper = new PoolHelper(getJdbcURL(), getUserId(), getUserPwd(), maxLimit);
   pHelper.initPoolConnection();
 }
  @Test
  public void testFile() {

    List<String> stringData = new ArrayList<>();

    for (int i = 0; i < 100; i++) {
      stringData.add(UUID.randomUUID().toString());
    }

    List<Integer> integerData = new ArrayList<>();

    for (String uuid : stringData) {
      integerData.add(uuid.hashCode());
    }

    File tempFile = null;

    try {
      tempFile = Files.createTempFile("test", "").toFile();
      tempFile.deleteOnExit();
    } catch (IOException e) {
      fail(e.toString());
    }

    try (FileOutputStream fos = new FileOutputStream(tempFile)) {
      BinaryStreamDriver bsd = new BinaryStreamDriver();
      XStream xstream = new XStream(bsd);

      try (ObjectOutputStream out = xstream.createObjectOutputStream(fos)) {
        out.writeObject(stringData);
        out.writeObject(integerData);
      }
    } catch (IOException e) {
      fail(e.toString());
    }

    assertTrue(FileMagic.isBinaryXStreamFile(tempFile));
    assertFalse(FileMagic.isOfxV2(tempFile));

    try (FileInputStream fis = new FileInputStream(tempFile)) {
      BinaryStreamDriver bsd = new BinaryStreamDriver();
      XStream xstream = new XStream(bsd);

      try (ObjectInputStream in = xstream.createObjectInputStream(fis)) {
        List<?> strings = (List<?>) in.readObject();
        List<?> integers = (List<?>) in.readObject();

        assertArrayEquals(strings.toArray(), stringData.toArray());
        assertArrayEquals(integers.toArray(), integerData.toArray());
      } catch (ClassNotFoundException e) {
        fail(e.toString());
      }
    } catch (IOException e) {
      fail(e.toString());
    }
  }
Beispiel #25
0
 protected Class<?> getClass(final Type t) {
   try {
     if (t.getSort() == Type.ARRAY) {
       return Class.forName(t.getDescriptor().replace('/', '.'), false, loader);
     }
     return Class.forName(t.getClassName(), false, loader);
   } catch (ClassNotFoundException e) {
     throw new RuntimeException(e.toString());
   }
 }
Beispiel #26
0
 protected Class loadClass(String name) {
   String c = name.replace("/", ".");
   try {
     return ClassUtils.loadClass(c, classLoader);
   } catch (ClassNotFoundException e) {
     if (logger.isWarnEnabled()) {
       logger.warn(String.format("%s : %s", c, e.toString()));
     }
     return null;
   }
 }
Beispiel #27
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());
     }
   }
 }
Beispiel #28
0
 /**
  * A workaround the plugin framework does not work in junit but we do not use the plugin framework
  * in junit tests.
  */
 private static void ignoreJunitEnvironment(ClassNotFoundException e, String suffix, String key) {
   boolean junitRunning = false;
   assert (junitRunning = true);
   if (!junitRunning) {
     log.warn(
         "registerPlugin failure. File suffix is \"{}\", key is \"{}\", exception is {}.",
         suffix,
         key,
         e.toString());
   }
 }
Beispiel #29
0
  /** Adds a java class */
  public void addJavaClass(String phpName, String className) {
    Class type;

    try {
      type = Class.forName(className, false, _loader);
    } catch (ClassNotFoundException e) {
      throw new QuercusRuntimeException(L.l("`{0}' not valid: {1}", className, e.toString()), e);
    }

    addJavaClass(phpName, type);
  }
 private void getConstractor(String className) {
   Objects.requireNonNull(className);
   Constructor<?>[] constructors = null;
   try {
     // コンストラクタの取得
     constructors = ConstructorService.getConstractor(className);
     // 取得したコンストラクタを表示する
     ConstructorList.getInstance().setList(constructors);
   } catch (ClassNotFoundException e) {
     new ExceptionDialog(e.toString());
   }
 }