Ejemplo n.º 1
0
  /**
   * Deletes students who are older than a certain number of years and not registered to any course.
   *
   * @param year students older than year are candidates to be deleted
   * @throws InvalidDBRequestException
   */
  public void deleteOldStudent(int year) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();

      // query all student who have been in the database longer than a number of years and not
      // registered to any course
      ResultSet rs =
          stmt.executeQuery(
              "select login, count(course_id) "
                  + "from student s left join courseRoster r on login = user_login "
                  + "where date_entered < SUBDATE(now(), INTERVAL "
                  + new String().valueOf(year).trim()
                  + " YEAR) "
                  + "group by login, date_entered");
      // delete them
      while (rs.next()) if (rs.getInt(2) == 0) purgeStudent(rs.getString(1).trim());

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Ejemplo n.º 2
0
  public java.sql.Connection getDbConnection(java.lang.String userName, java.lang.String passWord)
      throws java.sql.SQLException {

    java.sql.Connection connection = null;

    try {

      java.lang.Class.forName("org.postgresql.Driver");

    } catch (java.lang.ClassNotFoundException cnf) {

      javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), cnf.getMessage());
    }

    try {

      connection =
          java.sql.DriverManager.getConnection(
              "jdbc:postgresql://" + this.dbServerIp + ":" + dbPort + "/" + activeDatabase,
              userName,
              passWord);

    } catch (java.sql.SQLException sqlExec) {

      javax.swing.JOptionPane.showMessageDialog(
          new javax.swing.JFrame(), "ERROR : Logon denied due to incorrect password!");
    }

    return connection;
  }
Ejemplo n.º 3
0
  /**
   * Delete a student from the database. Also deletes the student's folders. Throws
   * InvalidDBRequestException if any error in database connection.
   *
   * @param username student's user name
   * @throws InvalidDBRequestException
   */
  private void purgeStudent(String username) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete from scores
      count = stmt.executeUpdate("delete from scores where user_login = '******'");

      // delete from student
      count = stmt.executeUpdate("delete from student where login = '******'");

      // delete student's folder
      File studentDir = new File("./StudentQuizzes/" + username);
      if (!(studentDir.delete())) {
        System.err.println("Error in deleting folder for student: " + username);
      }

      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Ejemplo n.º 4
0
  static {
    java.util.Properties prop = System.getProperties();
    java.lang.String vendor = prop.getProperty("java.vendor");
    java.lang.String platform_class_name;
    java.lang.Class platform_class;

    if (vendor.equals("Oracle Corporation")) {
      platform_class_name = "python.platform.JavaPlatform";
    } else if (vendor.equals("The Android Project")) {
      platform_class_name = "python.platform.AndroidPlatform";
    } else {
      throw new org.python.exceptions.RuntimeError("Unknown platform vendor '" + vendor + "'");
    }

    try {
      platform_class = java.lang.Class.forName(platform_class_name);
      impl = (python.Platform) platform_class.getConstructor().newInstance();
    } catch (ClassNotFoundException e) {
      throw new org.python.exceptions.RuntimeError(
          "Unable to find platform '" + platform_class_name + "'");
    } catch (NoSuchMethodException e) {
      throw new org.python.exceptions.RuntimeError(
          "Unable to call constructor for plaform '" + platform_class_name + "'");
    } catch (InstantiationException e) {
      throw new org.python.exceptions.RuntimeError(
          "Unable to instantiate platform '" + platform_class_name + "'");
    } catch (IllegalAccessException e) {
      throw new org.python.exceptions.RuntimeError(
          "Unable to access constructor for platform '" + platform_class_name + "'");
    } catch (java.lang.reflect.InvocationTargetException e) {
      throw new org.python.exceptions.RuntimeError(
          "Unable to invoke constructor for platform '" + platform_class_name + "'");
    }
  }
Ejemplo n.º 5
0
 private static boolean classExtendsClass(java.lang.Class<?> klass, String className) {
   if (klass == null) return false;
   if (klass.getName().equals(className)) return true;
   if ((className.equals("ceylon.language.Basic"))
       && klass != java.lang.Object.class
       && !isSubclassOfString(klass)
       // && klass!=java.lang.String.class
       && !klass.isAnnotationPresent(Class.class)
       && (!klass.isInterface() || !klass.isAnnotationPresent(Ceylon.class))) {
     // TODO: this is broken for a Java class that
     //      extends a Ceylon class
     return true;
   }
   Class classAnnotation = klass.getAnnotation(Class.class);
   if (classAnnotation != null) {
     String superclassName = declClassName(classAnnotation.extendsType());
     int i = superclassName.indexOf('<');
     if (i > 0) {
       superclassName = superclassName.substring(0, i);
     }
     if (superclassName.isEmpty()) {
       return false;
     }
     try {
       return classExtendsClass(
           java.lang.Class.forName(superclassName, true, klass.getClassLoader()), className);
     } catch (ClassNotFoundException e) {
       throw new RuntimeException(e);
     }
   }
   return classExtendsClass(klass.getSuperclass(), className);
 }
  private void compile() {
    Class[] staticLib = new Class[1];

    Class[] dynamicLib = new Class[1];
    context = new Object[1];
    Class[] dotLib = {Object.class, String.class, Class.class, java.util.Date.class};
    try {
      staticLib[0] = java.lang.Class.forName("java.lang.Math");

      pro = new ValueProvider();
      dynamicLib[0] = pro.getClass();
      context[0] = pro;

      res = new Resolver();

    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Can not find class for JEL!", e);
    }

    try {
      lib = new Library(staticLib, dynamicLib, dotLib, res, null);
      lib.markStateDependent("random", null);
    } catch (gnu.jel.CompilationException ec1) {
      throw new RuntimeException("Can not compile JEL Library!", ec1);
    }

    try {
      compExpression = Evaluator.compile(parsedExpression, lib, Boolean.TYPE);
    } catch (gnu.jel.CompilationException ec2) {
      throw new RuntimeException("Can not compile JEL Expression: " + expression, ec2);
    }
  }
Ejemplo n.º 7
0
  /**
   * Deletes an instructor from the database. Deletes the instructor's courses by invoking the
   * deleteCourse method. Throws InvalidDBRequestException if instructor not in the database or
   * other database connection problems.
   *
   * @see deleteCourse
   * @param instructor instructor's user name
   * @throws InvalidDBRequestException
   */
  public void deleteInstructor(String instructor) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete the instructor's courses
      ResultSet rs =
          stmt.executeQuery(
              "select course_num from course where instructor = '" + instructor + "'");
      while (rs.next()) deleteCourse(rs.getString(1).trim(), instructor);

      // delete the instructor's record
      count = stmt.executeUpdate("delete from instructor where login ='******'");

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Ejemplo n.º 8
0
 static Object createObject(String className)
     throws InstantiationException, IllegalAccessException, ClassNotFoundException {
   Object object1 = null;
   Class classDefinition = Class.forName(className);
   object1 = classDefinition.newInstance();
   return object1;
 }
Ejemplo n.º 9
0
 /**
  * Defines the specified array of structs as inner structs. The array is populated if necessary
  * using the struct component default constructor (which must be public).
  *
  * @param structs the struct array.
  * @return the specified struct array.
  * @throws IllegalArgumentException if the specified array contains inner structs.
  */
 protected /* <S extends Struct> S*/ Struct[] array(/*S*/ Struct[] structs) {
   Class structClass = null;
   boolean resetIndexSaved = _resetIndex;
   if (_resetIndex) {
     _bitIndex = 0;
     _resetIndex = false; // Ensures the array elements are sequential.
   }
   for (int i = 0; i < structs.length; ) {
     /*S*/ Struct struct = structs[i];
     if (struct == null) {
       try {
         if (structClass == null) {
           String arrayName = structs.getClass().getName();
           String structName = arrayName.substring(2, arrayName.length() - 1);
           structClass = java.lang.Class.forName(structName);
           /*                        if (structClass == null) throw new
           JavolutionError("Struct class: " + structName + " not found");*/
         }
         struct = (/*S*/ Struct) structClass.newInstance();
       } catch (Exception e) {
         System.out.println("Error with struct:" + e);
         return null;
       }
     }
     structs[i++] = inner(struct);
   }
   _resetIndex = resetIndexSaved;
   return (/*S*/ Struct[]) structs;
 }
Ejemplo n.º 10
0
  /**
   * Check the user's name and password and verify that the user is an instructor. Throws
   * InvalidDBRequestException if user is not an instructor, wrong password, or if any error occured
   * to the database connection.
   *
   * @param name user's user name
   * @param pass user's password
   * @throws InvalidDBRequestException
   */
  public void instructorLogin(String name, String pass) throws InvalidDBRequestException {
    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      // check if instructor
      rs = stmt.executeQuery("select password from instructor where login = '******'");
      if (!rs.next()) {
        if (debug) System.out.println("User not found in the instructor table");
        throw new InvalidDBRequestException("Instructor not registered");
      }

      // check password
      if (!rs.getString(1).equals(pass)) {
        if (debug) System.out.println("Invalid password for user: "******"Invalid password for user: "******"Invalid SQL in instructor login: "******"???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Server Error");
    }
  }
Ejemplo n.º 11
0
 private static boolean lookForInterface(
     java.lang.Class<?> klass, String className, Set<java.lang.Class<?>> alreadyVisited) {
   if (klass.getName().equals(className)) return true;
   // did we already visit this type?
   if (!alreadyVisited.add(klass)) return false;
   // first see if it satisfies it directly
   SatisfiedTypes satisfiesAnnotation = klass.getAnnotation(SatisfiedTypes.class);
   if (satisfiesAnnotation != null) {
     for (String satisfiedType : satisfiesAnnotation.value()) {
       satisfiedType = declClassName(satisfiedType);
       int i = satisfiedType.indexOf('<');
       if (i > 0) {
         satisfiedType = satisfiedType.substring(0, i);
       }
       try {
         if (lookForInterface(
             java.lang.Class.forName(satisfiedType, true, klass.getClassLoader()),
             className,
             alreadyVisited)) {
           return true;
         }
       } catch (ClassNotFoundException e) {
         throw new RuntimeException(e);
       }
     }
   }
   // now look at this class's interfaces
   for (java.lang.Class<?> intrface : klass.getInterfaces()) {
     if (lookForInterface(intrface, className, alreadyVisited)) return true;
   }
   // no luck
   return false;
 }
Ejemplo n.º 12
0
  /**
   * Remove a student from a particular course. Also Deletes all the quiz vizualisation files in the
   * student's directory which relates to the course. Caution: vizualisation file will be deleted
   * eventhough it also relates to another course if the student is also registered to that course.
   * (FIX ME!) Throws InvalidDBRequestException if the student is not registered in the course,
   * error occured during deletion, or other exception occured.
   *
   * @param username student's user name
   * @param courseID course id (course number + instructor name)
   * @throws InvalidDBRequestException
   */
  public void deleteStudent(String username, String courseID) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      int count = 0;

      // check if student registered to the course
      rs =
          stmt.executeQuery(
              "select * from courseRoster where course_id = '"
                  + courseID
                  + "' and user_login = '******'");
      if (!rs.next())
        throw new InvalidDBRequestException("Student is not registered to the course");

      // remove student from the course
      count =
          stmt.executeUpdate(
              "delete from courseRoster where course_id = '"
                  + courseID
                  + "' and user_login = '******'");
      if (count != 1) throw new InvalidDBRequestException("Error occured during deletion!");

      // delete the quiz visualization files
      rs =
          stmt.executeQuery(
              "select distinct unique_id, s.test_name from scores s, courseTest t "
                  + "where s.test_name = t.test_name "
                  + "and course_id = '"
                  + courseID
                  + "' "
                  + "and user_login = '******'");
      while (rs.next()) {
        deleteVisualization(rs.getString(1), username, rs.getString(2));
        count =
            stmt.executeUpdate("delete from scores where unique_id = " + rs.getString(1).trim());
      }

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addstudent: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Ejemplo n.º 13
0
  /**
   * Uses 'loader' to load class 'clzz', and calls the static method 'method'. If the return value
   * does not equal 'value' (or if an exception is thrown), then a test failure is indicated.
   *
   * <p>If 'value' is null, then no equality check is performed -- the assertion fails only if an
   * exception is thrown.
   */
  protected void assertStaticCallEquals(
      ClassLoader loader, Class clzz, String method, Object value) {
    java.lang.Class<?> cls = null;
    try {
      cls = java.lang.Class.forName(clzz.getName(), true, loader);
    } catch (ClassNotFoundException e) {
    }
    assertNotNull(cls);

    java.lang.reflect.Method m = null;
    try {
      m = cls.getMethod(method);
    } catch (NoSuchMethodException e) {
    }
    assertNotNull(m);

    try {
      Object res = m.invoke(null);
      assertNotNull(res);
      if (value != null) {
        assertEquals(res, value);
      }
    } catch (InvocationTargetException | IllegalAccessException e) {
      fail("Unexpected exception thrown: " + e.getCause(), e.getCause());
    }
  }
Ejemplo n.º 14
0
  /**
   * Gets a list of courses that belongs to an instructor. Throws InvalidDBRequestException if any
   * error occured to the database connection.
   *
   * @param name the instructor's user name
   * @return a vector containing the list of courses
   * @throws InvalidDBRequestException
   */
  public Vector getCourseList(String name) throws InvalidDBRequestException {
    Vector courseList = new Vector();

    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      // get the course list
      rs =
          stmt.executeQuery(
              "select course_num, course_name from course where instructor = '"
                  + name
                  + "' order by course_num");
      while (rs.next()) courseList.add(rs.getString(1) + " - " + rs.getString(2));

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in getCourseList: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Server Error");
    }

    return courseList;
  }
Ejemplo n.º 15
0
 private XmlUIElement getXmlUIElementFor(String typeArg) {
   if (typeToClassMappingProp == null) {
     setUpMappingsHM();
   }
   String clsName = (String) typeToClassMappingProp.get(typeArg);
   if ((clsName != null) && !(clsName.equals("*NOTFOUND*")) && !(clsName.equals("*EXCEPTION*"))) {
     try {
       Class cls = Class.forName(clsName);
       return (XmlUIElement) cls.newInstance();
     } catch (Throwable th) {
       typeToClassMappingProp.put(typeArg, "*EXCEPTION*");
       showErrorMessage(
           MessageFormat.format(
               ProvClientUtils.getString(
                   "{0} occurred when trying to get the XmlUIElement for type : {1}"),
               new Object[] {th.getClass().getName(), typeArg}));
       th.printStackTrace();
       return null;
     }
   } else if (clsName == null) {
     typeToClassMappingProp.put(typeArg, "*NOTFOUND*");
     showErrorMessage(
         MessageFormat.format(
             ProvClientUtils.getString(
                 "The type {0} does not have the corresponding XMLUIElement specified in the TypeToUIElementMapping.txt file"),
             new Object[] {typeArg}));
   }
   return null;
 }
Ejemplo n.º 16
0
  /**
   * Query a quiz list from the database. If there is no student user name specified, the list will
   * contain all quizzes that are used in the instructor's courses. Otherwise, the list will contain
   * all quizzes that the student has taken and from the instructor's courses which the student is
   * registered. Throws InvalidDBRequestException if any error occured to the database connection.
   *
   * @param instructor instructor's user name
   * @param student student's user name. Can be empty to get a list of all quizzes in the
   *     instructor's courses.
   * @return a vector containing the list of quizzes
   * @throws InvalidDBRequestException
   */
  public Vector getQuizList(String instructor, String student) throws InvalidDBRequestException {
    Vector list = new Vector();

    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      if (!student.equals("")) {
        // get the list that contains all quizzes that the student has taken and from the
        // instructor's courses which the student is registered
        rs =
            stmt.executeQuery(
                "select courseTest.test_name, scores.start_time from scores, courseTest, course "
                    + "where courseTest.test_name = scores.test_name "
                    + "and courseTest.course_id = course.course_id "
                    + "and instructor = '"
                    + instructor
                    + "' and user_login = '******' "
                    + "order by scores.start_time");

        while (rs.next()) {
          list.add(rs.getString(1) + " <" + rs.getString(2) + ">");
        }
      } else {
        // get the list that contains all quizzes that are used in the instructor's courses
        rs =
            stmt.executeQuery(
                "select test_name from courseTest, course "
                    + "where courseTest.course_id = course.course_id "
                    + "and instructor = '"
                    + instructor
                    + "' ");

        while (rs.next()) {
          list.add(rs.getString(1));
        }
      }

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in getQuizList: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }

    return list;
  }
Ejemplo n.º 17
0
  /**
   * Obtains information on a quiz that a student has taken, which includes the student's answer to
   * the quiz, a unique id of the instance, number of questions in the quiz, number of questions
   * answered correctly, and vizualisation type of the quiz. Throws InvalidDBRequestException if
   * cannot find the record of the stuent taking the quiz, quiz is not registered in the database,
   * or if any error occured to the database connection.
   *
   * @param student student's user name
   * @param quiz quiz name
   * @param startTime the time the student started the quiz
   * @return a string tokenizer containing: answer,uniqueID, numQuestions, numCorrect, and
   *     visualType. It uses "@" as the delimiter.
   * @throws InvalidDBRequestException
   */
  public StringTokenizer getAnswerAndVisualType(String student, String quiz, String startTime)
      throws InvalidDBRequestException {
    String answer;
    String uniqueID;
    String numQuestions;
    String numCorrect;
    String visualType;
    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      // get student's answer, unique id, number of questions, and number of questions answered
      // correctly
      rs =
          stmt.executeQuery(
              "select transcript, unique_id, num_questions, num_correct from scores "
                  + "where test_name = '"
                  + quiz
                  + "' and user_login = '******' and start_time = '"
                  + startTime
                  + "'");
      if (!rs.next()) throw new InvalidDBRequestException("Student has not taken the quiz");
      else {
        answer = rs.getString(1).trim();
        uniqueID = rs.getString(2).trim();
        numQuestions = rs.getString(3).trim();
        numCorrect = rs.getString(4).trim();
      }

      // get quiz vizualisation type
      rs = stmt.executeQuery("select visual_type from test where name = '" + quiz + "' ");
      if (!rs.next())
        throw new InvalidDBRequestException(
            "Quiz was not found! Can't retrieve visualization type.");
      else {
        visualType = rs.getString(1);
      }

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in getAnswerAndVisualType: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
    return new StringTokenizer(
        answer + "@" + uniqueID + "@" + numQuestions + "@" + numCorrect + "@" + visualType, "@");
  }
Ejemplo n.º 18
0
  public static Object loadFrame(
      JopSession session, String className, String instance, boolean scrollbar)
      throws ClassNotFoundException {

    if (className.indexOf(".pwg") != -1) {
      GrowFrame frame =
          new GrowFrame(
              className, session.getGdh(), instance, new GrowFrameCb(session), session.getRoot());
      frame.validate();
      frame.setVisible(true);
    } else {
      Object frame;
      if (instance == null) instance = "";

      JopLog.log(
          "JopSpider.loadFrame: Loading frame \"" + className + "\" instance \"" + instance + "\"");
      try {
        Class clazz = Class.forName(className);
        try {
          Class argTypeList[] =
              new Class[] {session.getClass(), instance.getClass(), boolean.class};
          Object argList[] = new Object[] {session, instance, new Boolean(scrollbar)};
          System.out.println("JopSpider.loadFrame getConstructor");
          Constructor constructor = clazz.getConstructor(argTypeList);

          try {
            frame = constructor.newInstance(argList);
          } catch (Exception e) {
            System.out.println(
                "Class instanciation error: "
                    + className
                    + " "
                    + e.getMessage()
                    + " "
                    + constructor);
            return null;
          }
          // frame = clazz.newInstance();
          JopLog.log("JopSpider.loadFrame openFrame");
          openFrame(frame);
          return frame;
        } catch (NoSuchMethodException e) {
          System.out.println("NoSuchMethodException: Unable to get frame constructor " + className);
        } catch (Exception e) {
          System.out.println(
              "Exception: Unable to get frame class " + className + " " + e.getMessage());
        }
      } catch (ClassNotFoundException e) {
        System.out.println("Class not found: " + className);
        throw new ClassNotFoundException();
      }
      return null;
    }
    return null;
  }
Ejemplo n.º 19
0
 private Class<?> getPackageInfo() {
   if (packageInfo == null) {
     try {
       packageInfo = Class.forName(pkgName + ".package-info", false, loader);
     } catch (ClassNotFoundException ex) {
       // store a proxy for the package info that has no annotations
       class PackageInfoProxy {}
       packageInfo = PackageInfoProxy.class;
     }
   }
   return packageInfo;
 }
Ejemplo n.º 20
0
  /**
   * Loads the SWIG-generated libSBML Java module when this class is loaded, or reports a sensible
   * diagnostic message about why it failed.
   */
  static {
    String varname;
    String shlibname;

    if (System.getProperty("os.name").startsWith("Mac OS")) {
      varname = "DYLD_LIBRARY_PATH"; // We're on a Mac.
      shlibname = "'libsbmlj.jnilib'";
    } else {
      varname = "LD_LIBRARY_PATH"; // We're not on a Mac.
      shlibname = "'libsbmlj.so' and/or 'libsbml.so'";
    }

    try {
      System.loadLibrary("sbmlj");
      // For extra safety, check that the jar file is in the classpath.
      Class.forName("org.sbml.libsbml.libsbml");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Error encountered while attempting to load libSBML:");
      e.printStackTrace();
      System.err.println(
          "Please check the value of your "
              + varname
              + " environment variable and/or"
              + " your 'java.library.path' system property"
              + " (depending on which one you are using) to"
              + " make sure it list the directories needed to"
              + " find the "
              + shlibname
              + " library file and the"
              + " libraries it depends upon (e.g., the XML parser).");
      System.exit(1);
    } catch (ClassNotFoundException e) {
      System.err.println(
          "Error: unable to load the file 'libsbmlj.jar'."
              + " It is likely that your -classpath command line "
              + " setting or your CLASSPATH environment variable "
              + " do not include the file 'libsbmlj.jar'.");
      System.exit(1);
    } catch (SecurityException e) {
      System.err.println("Error encountered while attempting to load libSBML:");
      e.printStackTrace();
      System.err.println(
          "Could not load the libSBML library files due to a" + " security exception.\n");
      System.exit(1);
    }
  }
Ejemplo n.º 21
0
 /**
  * Given a class path of the form package.className and the name of the method, this will return
  * the method
  *
  * @param classPath
  * @param methodName
  * @param targetObject
  * @param parameters
  * @return The private method to be tested.
  */
 public static java.lang.reflect.Method extractPrivateMethod(
     String classPath, String methodName, java.lang.Class<?>[] parameters) {
   try {
     java.lang.Class<?> c = java.lang.Class.forName(classPath);
     java.lang.reflect.Method parsePackage = c.getDeclaredMethod(methodName, parameters);
     parsePackage.setAccessible(true);
     return parsePackage;
   } catch (ClassNotFoundException cnfe) {
     cnfe.printStackTrace();
     System.out.println("The class " + classPath + " cound not be found. Check your spelling!");
   } catch (NoSuchMethodException nsme) {
     nsme.printStackTrace();
     System.out.println(
         "The method " + methodName + "() cound not be found. Check your spelling!");
   }
   return null;
 } // extractPrivateMethod()
Ejemplo n.º 22
0
  static ClassLoader getSystemClassLoader() {
    // This method is called as the initialization of systemClassLoader,
    // so if there is a null value, this is the first call and we must check
    // for java.system.class.loader.
    String loader = System.getProperty("java.system.class.loader");
    ClassLoader default_sys = getSystemClassLoaderInternal();
    if (loader != null) {
      try {
        Class load_class = Class.forName(loader, true, default_sys);
        Constructor c = load_class.getConstructor(new Class[] {ClassLoader.class});
        default_sys = (ClassLoader) c.newInstance(new Object[] {default_sys});
      } catch (Exception ex) {
        throw new Error("Failed to load requested system classloader " + loader, ex);
      }
    }

    return default_sys;
  }
Ejemplo n.º 23
0
  // New implementation
  public JopSession(JopEngine engine, Object rootObject) {
    // Create a JopSessionRep object which class is not known by the compiler
    try {
      Class clazz = Class.forName("jpwr.jop.JopSessionRep");
      try {
        sessionRep = clazz.newInstance();
      } catch (InstantiationException e) {
        System.out.println("InstatiationException");
      } catch (IllegalAccessException e) {
        System.out.println("IllegalAccessException");
      }
    } catch (ClassNotFoundException e) {
      System.out.println("Class not found");
    }

    ((JopSessionIfc) sessionRep).setSession(this);
    ((JopSessionIfc) sessionRep).setRoot(rootObject);
    ((JopSessionIfc) sessionRep).setEngine(engine);
  }
Ejemplo n.º 24
0
  /**
   * Add a course into the database if not already so. Throws InvalidDBRequestException if course
   * already in the DB, error occured during insertion, or other exception occured.
   *
   * @param courseNum course number
   * @param courseName name of the course
   * @param instructor name of the instructor who owns the course
   * @throws InvalidDBRequestException
   */
  public void addCourse(String courseNum, String courseName, String instructor)
      throws InvalidDBRequestException {
    String courseId = courseNum + instructor;

    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      int count = 0;

      // check if course already in the database
      rs = stmt.executeQuery("select course_id from course where course_id = '" + courseId + "'");
      if (rs.next()) throw new InvalidDBRequestException("Course is already in the database");

      // insert course into database
      count =
          stmt.executeUpdate(
              "insert into course values ('"
                  + courseId
                  + "', '"
                  + courseName
                  + "', '"
                  + courseNum
                  + "', '"
                  + instructor
                  + "')");
      if (count != 1) throw new InvalidDBRequestException("Something happen during insertion!");

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Ejemplo n.º 25
0
  public org.python.Object __getattribute__(java.lang.String name) {
    // System.out.println("GETATTRIBUTE NATIVE MODULE " + this + " " + name);
    org.python.types.Type cls = org.python.types.Type.pythonType(this.klass);
    // System.out.println("instance attrs = " + this.attrs);
    // System.out.println("class attrs = " + cls.attrs);
    org.python.Object value;

    value = cls.attrs.get(name);
    if (value == null) {
      try {
        java.lang.Class java_class = java.lang.Class.forName(java_namespace + "." + name);
        value = new org.python.java.Type(java_class);
        cls.attrs.put(name, value);
      } catch (java.lang.ClassNotFoundException e) {
        throw new org.python.exceptions.NameError(name);
      }
    }
    return value;
  }
Ejemplo n.º 26
0
  private static boolean classSatisfiesInterface(
      java.lang.Class<?> klass, String className, Set<java.lang.Class<?>> alreadyVisited) {
    if (klass == null || klass == ceylon.language.Anything.class) return false;
    if ((className.equals("ceylon.language.Identifiable"))
        && klass != java.lang.Object.class
        // && klass!=java.lang.String.class
        && !klass.isAnnotationPresent(Ceylon.class)) {
      // TODO: this is broken for a Java class that
      //      extends a Ceylon class
      return true;
    }
    if (className.equals("ceylon.language.Identifiable") && isSubclassOfString(klass)) {
      return false;
    }
    // try the interfaces
    if (lookForInterface(klass, className, alreadyVisited)) return true;
    // try its superclass
    Class classAnnotation = klass.getAnnotation(Class.class);
    String superclassName;
    if (classAnnotation != null) {
      superclassName = declClassName(classAnnotation.extendsType());
      int i = superclassName.indexOf('<');
      if (i > 0) {
        superclassName = superclassName.substring(0, i);
      }

    } else {
      // Maybe the class didn't have an extends, so implictly Basic
      superclassName = "ceylon.language.Basic";
    }
    if (!superclassName.isEmpty()) {
      try {
        return classSatisfiesInterface(
            java.lang.Class.forName(superclassName, true, klass.getClassLoader()),
            className,
            alreadyVisited);
      } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
      }
    }
    return classSatisfiesInterface(klass.getSuperclass(), className, alreadyVisited);
  }
Ejemplo n.º 27
0
  public static void main(String[] args) {
    // Ensure to have all necessary drivers installed !
    try {
      Driver d = (Driver) (Class.forName("oracle.jdbc.driver.OracleDriver").newInstance());
      DriverManager.registerDriver(d);
    } catch (Exception e) {
    }

    // Set the priority which messages have to be logged
    cat.setPriority(Priority.INFO);

    // Configuration with configuration-file
    PropertyConfigurator.configure("log4jtestprops.txt");

    // These messages with Priority >= setted priority will be logged to the database.
    cat.debug("debug"); // this not, because Priority DEBUG is less than INFO
    cat.info("info");
    cat.error("error");
    cat.fatal("fatal");
  }
Ejemplo n.º 28
0
  /**
   * Initialize the Oracle database from the connection parameters set in the XML Configuration file
   *
   * @param strConfigFile XML Configuration file
   * @return Connection Statement object
   */
  public static java.sql.Statement OracleInit(final java.lang.String strConfigFile) {
    org.w3c.dom.Document doc = GetNormalizedXMLDoc(strConfigFile);

    if (null == doc) return null;

    org.w3c.dom.NodeList nlDBConn = doc.getElementsByTagName("dbconn");

    if (null == nlDBConn
        || null == nlDBConn.item(0)
        || org.w3c.dom.Node.ELEMENT_NODE != nlDBConn.item(0).getNodeType()) return null;

    org.w3c.dom.Element elemDBConn = (org.w3c.dom.Element) nlDBConn.item(0);

    try {
      java.lang.Class.forName("oracle.jdbc.driver.OracleDriver");

      java.lang.String strURL =
          "jdbc:oracle:thin:@//"
              + GetStringTagValue(elemDBConn, "host")
              + ":"
              + GetStringTagValue(elemDBConn, "port")
              + "/"
              + GetStringTagValue(elemDBConn, "dbname");

      // java.lang.String strURL = "jdbc:oracle:thin:@//localhost:1521/XE";

      System.out.println("URL: " + strURL);

      java.sql.Connection conn = java.sql.DriverManager.getConnection(strURL, "hr", "hr");

      System.out.println("Conn: " + conn);

      conn.setAutoCommit(false);

      return conn.createStatement();
    } catch (java.lang.Exception e) {
      e.printStackTrace();
    }

    return null;
  }
Ejemplo n.º 29
0
  /**
   * Private method to delete a visualization script file of a quiz taken by a student.
   *
   * @param uniqueId a unique number of that indicates the instance of the quiz taking in the
   *     database
   * @param studentName student's user name
   * @param testName quiz name
   */
  private void deleteVisualization(String uniqueId, String studentName, String testName) {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();

      // get quiz visulization type
      ResultSet rs =
          stmt.executeQuery("select visual_type from test where name = '" + testName + "'");
      // construct the quiz vizualisation file name
      String visFileName =
          new String("./StudentQuizzes/" + studentName + "/" + testName + uniqueId);
      if (rs.next())
        if (rs.getString(1).trim().equalsIgnoreCase("gaigs")) visFileName = visFileName + ".sho";
        else if (rs.getString(1).trim().equalsIgnoreCase("samba"))
          visFileName = visFileName + ".sam";
        else if (rs.getString(1).trim().equalsIgnoreCase("animal"))
          visFileName = visFileName + ".ani";
        else {
          System.err.println("visualization type unknown for quiz: " + rs.getString(3) + "\n");
        }
      else {
        System.err.println("Visulization type not found for quiz: " + rs.getString(3) + "\n");
      }

      // delete the file
      File visFile = new File(visFileName);
      if (debug) System.out.println("deleting " + visFileName);
      if (visFile.exists())
        if (!visFile.delete()) System.err.println("can't delete the visualization file");

      rs.close();
      stmt.close();
      db.close();
    } catch (Exception e) {
      System.err.println("Execption thrown from deleteVisualisation: " + e.getMessage());
    }
  }
  private static final X509Certificate getInst(Object value) throws CertificateException {
    /*
     * This turns out not to work for now. To run under JDK1.2 we would
     * need to call beginPrivileged() but we can't do that and run
     * under JDK1.1.
     */
    String className = X509Provider;
    if (className == null || className.length() == 0) {
      // shouldn't happen, but assume corrupted properties file
      // provide access to sun implementation
      className = "com.sun.security.cert.internal.x509.X509V1CertImpl";
    }
    try {
      Class<?>[] params = null;
      if (value instanceof InputStream) {
        params = new Class<?>[] {InputStream.class};
      } else if (value instanceof byte[]) {
        params = new Class<?>[] {value.getClass()};
      } else throw new CertificateException("Unsupported argument type");
      Class<?> certClass = Class.forName(className);

      // get the appropriate constructor and instantiate it
      Constructor<?> cons = certClass.getConstructor(params);

      // get a new instance
      Object obj = cons.newInstance(new Object[] {value});
      return (X509Certificate) obj;

    } catch (ClassNotFoundException e) {
      throw new CertificateException("Could not find class: " + e);
    } catch (IllegalAccessException e) {
      throw new CertificateException("Could not access class: " + e);
    } catch (InstantiationException e) {
      throw new CertificateException("Problems instantiating: " + e);
    } catch (InvocationTargetException e) {
      throw new CertificateException("InvocationTargetException: " + e.getTargetException());
    } catch (NoSuchMethodException e) {
      throw new CertificateException("Could not find class method: " + e.getMessage());
    }
  }