Пример #1
1
  @Override
  public Set<EmpVO> getEmpsByDeptno(Integer deptno) {
    Set<EmpVO> set = new LinkedHashSet<EmpVO>();
    EmpVO empVO = null;

    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {

      Class.forName(driver);
      con = DriverManager.getConnection(url, userid, passwd);
      pstmt = con.prepareStatement(GET_Emps_ByDeptno_STMT);
      pstmt.setInt(1, deptno);
      rs = pstmt.executeQuery();

      while (rs.next()) {
        empVO = new EmpVO();
        empVO.setEmpno(rs.getInt("empno"));
        empVO.setEname(rs.getString("ename"));
        empVO.setJob(rs.getString("job"));
        empVO.setHiredate(rs.getDate("hiredate"));
        empVO.setSal(rs.getDouble("sal"));
        empVO.setComm(rs.getDouble("comm"));
        empVO.setDeptno(rs.getInt("deptno"));
        set.add(empVO); // Store the row in the vector
      }

      // Handle any driver errors
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Couldn't load database driver. " + e.getMessage());
      // Handle any SQL errors
    } catch (SQLException se) {
      throw new RuntimeException("A database error occured. " + se.getMessage());
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (pstmt != null) {
        try {
          pstmt.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (con != null) {
        try {
          con.close();
        } catch (Exception e) {
          e.printStackTrace(System.err);
        }
      }
    }
    return set;
  }
 public ArrayList<Empleado> listarEmpleado() {
   ArrayList<Empleado> emple = new ArrayList<Empleado>();
   try {
     cn = Conexion.realizarConexion();
     st = cn.createStatement();
     String sql = "select * from empleado";
     rs = st.executeQuery(sql);
     while (rs.next()) {
       emple.add(
           new Empleado(
               rs.getString(1),
               rs.getString(2),
               rs.getString(3),
               rs.getString(4),
               rs.getString(5),
               rs.getString(6),
               rs.getString(7),
               rs.getString(8)));
     }
   } catch (ClassNotFoundException ex) {
     showMessageDialog(null, ex.getMessage(), "Excepción", 0);
   } catch (SQLException ex) {
     showMessageDialog(null, ex.getMessage(), "Excepción", 0);
   } finally {
     try {
       rs.close();
       st.close();
       cn.close();
     } catch (Exception ex) {
       showMessageDialog(null, ex.getMessage(), "Excepción", 0);
     }
   }
   return emple;
 }
 public String buscarEmpleado(String codigo) {
   try {
     cn = Conexion.realizarConexion();
     st = cn.createStatement();
     String sql =
         "select chr_emplcodigo from empleado " + " where chr_emplcodigo = '" + codigo + "'";
     rs = st.executeQuery(sql);
     while (rs.next()) {
       return rs.getString("chr_emplcodigo");
     }
   } catch (ClassNotFoundException ex) {
     showMessageDialog(null, ex.getMessage(), "Excepción", 0);
   } catch (SQLException ex) {
     showMessageDialog(null, ex.getMessage(), "Excepción", 0);
   } finally {
     try {
       rs.close();
       st.close();
       cn.close();
     } catch (Exception ex) {
       showMessageDialog(null, ex.getMessage(), "Excepción", 0);
     }
   }
   return null;
 }
 public String insertarEmpleado(Empleado empleado) {
   String mensaje = null;
   try {
     cn = Conexion.realizarConexion();
     String sql = "insert into empleado values(?,?,?,?,?,?,?,?)";
     ps = cn.prepareStatement(sql);
     ps.setString(1, empleado.getCodigo());
     ps.setString(2, empleado.getPaterno());
     ps.setString(3, empleado.getMaterno());
     ps.setString(4, empleado.getNombre());
     ps.setString(5, empleado.getCiudad());
     ps.setString(6, empleado.getDireccion());
     ps.setString(7, empleado.getUsuario());
     ps.setString(8, empleado.getClave());
     ps.executeUpdate();
   } catch (ClassNotFoundException ex) {
     mensaje = ex.getMessage();
   } catch (SQLException ex) {
     mensaje = ex.getMessage();
   } finally {
     try {
       ps.close();
       cn.close();
     } catch (Exception ex) {
       mensaje = ex.getMessage();
     }
   }
   return mensaje;
 }
 public void testExceptionHandling() {
   final ComponentAdapter componentAdapter =
       new ThreadLocalizing.ThreadLocalized(
           new ConstructorInjection.ConstructorInjector(
               TargetInvocationExceptionTester.class, ThrowingComponent.class, null));
   final TargetInvocationExceptionTester tester =
       (TargetInvocationExceptionTester)
           componentAdapter.getComponentInstance(null, ComponentAdapter.NOTHING.class);
   try {
     tester.throwsCheckedException();
     fail("ClassNotFoundException expected");
   } catch (final ClassNotFoundException e) {
     assertEquals("junit", e.getMessage());
   }
   try {
     tester.throwsRuntimeException();
     fail("RuntimeException expected");
   } catch (final RuntimeException e) {
     assertEquals("junit", e.getMessage());
   }
   try {
     tester.throwsError();
     fail("Error expected");
   } catch (final Error e) {
     assertEquals("junit", e.getMessage());
   }
 }
  // 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();
  }
Пример #7
0
  static {
    groups = new HashMap<String, Integer>();

    JDBCDatabase database = null;

    try {
      database = new JDBCDatabase(url, user, password);
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    List<List<String>> lists = null;

    try {
      lists = database.selectFrom(table, "*");
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    for (List<String> list : lists) {
      groups.put(list.get(0), Integer.valueOf(list.get(1)));
    } /**/
  }
Пример #8
0
  protected void checkReturn(Stmt.Return ret) {
    JavaMethod method = (JavaMethod) getEnclosingScope(JavaMethod.class);

    if (method instanceof JavaConstructor) {
      return; // could do better than this.
    }

    Type retType = method.returnType().attribute(Type.class);

    if (ret.expr() != null) {
      checkExpression(ret.expr());

      Type ret_t = ret.expr().attribute(Type.class);
      try {
        if (ret_t.equals(new Type.Void())) {
          syntax_error("cannot return a value from method whose result type is void", ret);
        } else if (!types.subtype(retType, ret_t, loader)) {
          syntax_error("required return type " + retType + ",  found type " + ret_t, ret);
        }

      } catch (ClassNotFoundException ex) {
        syntax_error(ex.getMessage(), ret);
      }
    } else if (!(retType instanceof Type.Void)) {
      syntax_error("missing return value", ret);
    }
  }
Пример #9
0
 /**
  * @return an instanciation of the given content-type class name, or null if class wasn't found
  */
 public static ContentType getContentTypeFromClassName(String contentTypeClassName) {
   if (contentTypeClassName == null)
     contentTypeClassName = getAvailableContentTypes()[DEFAULT_CONTENT_TYPE_INDEX];
   ContentType ct = null;
   try {
     Class clazz = Class.forName(contentTypeClassName);
     ct = (ContentType) clazz.newInstance();
   } catch (ClassNotFoundException cnfex) {
     if (jpicedt.Log.DEBUG) cnfex.printStackTrace();
     JPicEdt.getMDIManager()
         .showMessageDialog(
             "The pluggable content-type you asked for (class "
                 + cnfex.getLocalizedMessage()
                 + ") isn't currently installed, using default instead...",
             Localizer.currentLocalizer().get("msg.LoadingContentTypeClass"),
             JOptionPane.ERROR_MESSAGE);
   } catch (Exception ex) {
     if (jpicedt.Log.DEBUG) ex.printStackTrace();
     JPicEdt.getMDIManager()
         .showMessageDialog(
             ex.getLocalizedMessage(),
             Localizer.currentLocalizer().get("msg.LoadingContentTypeClass"),
             JOptionPane.ERROR_MESSAGE);
   }
   return ct;
 }
Пример #10
0
  public static void main(String[] args) {
    // read class name from command line args or user input
    String name;
    if (args.length > 0) name = args[0];
    else {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter class name (e.g. java.util.Date): ");
      name = in.next();
    }

    try {
      // print class name and superclass name (if != Object)
      Class cl = Class.forName(name);
      Class supercl = cl.getSuperclass();
      String modifiers = Modifier.toString(cl.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.print("class " + name);
      if (supercl != null && supercl != Object.class)
        System.out.print(" extends " + supercl.getName());

      System.out.print("\n{\n");
      printConstructors(cl);
      System.out.println();
      printMethods(cl);
      System.out.println();
      printFields(cl);
      System.out.println("}");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    System.exit(0);
  }
Пример #11
0
 /** Running thread */
 public void run() {
   try {
     in = new ObjectInputStream(clientSocket.getInputStream());
     out = new ObjectOutputStream(clientSocket.getOutputStream());
     this.query = (String) in.readObject();
     // LOG.debug("Query: " + query);
     // We assume that query should either start with one of OntQueryQueue.QUERY_TYPES or
     // the query type will be missing - for the getBeanForId(id) queries
     OntQueryQueue oqq = new OntQueryQueue(query);
     if (oqq.getQueryType() == null || oqq.getQueryType().equals("")) {
       // it's a single  id query
       this.results = new TreeSet<OntBean>();
       String fbbtId = oqq.getQueries().get(0);
       OntBean ob = dlQueryServer.getBeanForId(fbbtId);
       this.results.add(ob);
     } else {
       // it's a list query
       this.results = dlQueryServer.askQuery(this.query);
     }
     sendObjectToClient(this.results);
   } catch (IOException ex) {
     ex.printStackTrace();
   } catch (ClassNotFoundException ex) {
     ex.printStackTrace();
   } catch (NullPointerException ex) {
     ex.printStackTrace();
   }
 }
Пример #12
0
  public void testSerial() {
    assertTrue(_nbhm.isEmpty());
    final String k1 = "k1";
    final String k2 = "k2";
    assertThat(_nbhm.put(k1, "v1"), nullValue());
    assertThat(_nbhm.put(k2, "v2"), nullValue());

    // Serialize it out
    try {
      FileOutputStream fos = new FileOutputStream("NBHM_test.txt");
      ObjectOutputStream out = new ObjectOutputStream(fos);
      out.writeObject(_nbhm);
      out.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    // Read it back
    try {
      File f = new File("NBHM_test.txt");
      FileInputStream fis = new FileInputStream(f);
      ObjectInputStream in = new ObjectInputStream(fis);
      NonBlockingIdentityHashMap nbhm = (NonBlockingIdentityHashMap) in.readObject();
      in.close();
      assertThat(
          "serialization works",
          nbhm.toString(),
          anyOf(is("{k1=v1, k2=v2}"), is("{k2=v2, k1=v1}")));
      if (!f.delete()) throw new IOException("delete failed");
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
  }
Пример #13
0
  @Override
  public void delete(Integer deptno) {
    int updateCount_EMPs = 0;

    Connection con = null;
    PreparedStatement pstmt = null;

    try {

      Class.forName(driver);
      con = DriverManager.getConnection(url, userid, passwd);

      // 1●設定於 pstm.executeUpdate()之前
      con.setAutoCommit(false);

      // 先刪除員工
      pstmt = con.prepareStatement(DELETE_EMPs);
      pstmt.setInt(1, deptno);
      updateCount_EMPs = pstmt.executeUpdate();
      // 再刪除部門
      pstmt = con.prepareStatement(DELETE_DEPT);
      pstmt.setInt(1, deptno);
      pstmt.executeUpdate();

      // 2●設定於 pstm.executeUpdate()之後
      con.commit();
      con.setAutoCommit(true);
      System.out.println("刪除部門編號" + deptno + "時,共有員工" + updateCount_EMPs + "人同時被刪除");

      // Handle any driver errors
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Couldn't load database driver. " + e.getMessage());
      // Handle any SQL errors
    } catch (SQLException se) {
      if (con != null) {
        try {
          // 3●設定於當有exception發生時之catch區塊內
          con.rollback();
        } catch (SQLException excep) {
          throw new RuntimeException("rollback error occured. " + excep.getMessage());
        }
      }
      throw new RuntimeException("A database error occured. " + se.getMessage());
    } finally {
      if (pstmt != null) {
        try {
          pstmt.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (con != null) {
        try {
          con.close();
        } catch (Exception e) {
          e.printStackTrace(System.err);
        }
      }
    }
  }
Пример #14
0
 @SuppressWarnings({"boxing", "unchecked"})
 public void loadCache() {
   this.cache.clear();
   try {
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(CACHE_FILE));
     this.remoteDiscoveryImpl.syso("load cache");
     try {
       final int cacheSize = (Integer) in.readObject();
       //					syso("size "+cacheSize);
       for (int i = 0; i < cacheSize; ++i) {
         HashMap<RemoteManagerEndpoint, Entry> rmee = new HashMap<RemoteManagerEndpoint, Entry>();
         Class<? extends Plugin> plugin = (Class<? extends Plugin>) in.readObject();
         this.remoteDiscoveryImpl.syso(plugin.getCanonicalName());
         //						syso("\t"+i+"'"+pluginName+"'");
         int numEntries = (Integer) in.readObject();
         //						syso("\t"+numEntries);
         for (int j = 0; j < numEntries; ++j) {
           Entry entry = (Entry) in.readObject();
           //							syso("\t\t"+entry);
           rmee.put(entry.manager, entry);
         }
         this.cache.put(plugin, rmee);
       }
     } catch (ClassNotFoundException e) {
       e.printStackTrace();
     } finally {
       in.close();
     }
   } catch (FileNotFoundException e) {
     this.remoteDiscoveryImpl.logger.warning("Loading cache file" + CACHE_FILE + " failed.");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Пример #15
0
 private static void findAndAddClassesInPackageByFile(
     String packName, String filePath, final boolean flag, Set<Class<?>> classes) {
   File dir = new File(filePath);
   if (!dir.exists() || !dir.isDirectory()) {
     System.out.println("此路径下没有文件");
     return;
   }
   File[] dirfiles =
       dir.listFiles(
           new FileFilter() {
             @Override
             public boolean accept(File pathname) {
               return flag && pathname.isDirectory() || pathname.getName().endsWith(".class");
             }
           });
   for (File file : dirfiles) {
     if (file.isDirectory()) { // 如果是目录,继续扫描
       findAndAddClassesInPackageByFile(
           packName + "." + file.getName(), file.getAbsolutePath(), flag, classes);
     } else { // 如果是文件
       String className = file.getName().substring(0, file.getName().length() - 6);
       // System.out.println("类名:" + className);
       try {
         classes.add(
             Thread.currentThread().getContextClassLoader().loadClass(packName + "." + className));
       } catch (ClassNotFoundException e) {
         e.printStackTrace();
       }
     }
   }
 }
Пример #16
0
  protected void checkVarDef(Stmt.VarDef def) {
    // Observe that we cannot use the declared type here, rather we have to
    // use the resolved type!
    Type t = def.type().attribute(Type.class);

    for (Triple<String, Integer, Expr> d : def.definitions()) {
      if (d.third() != null) {
        checkExpression(d.third());

        Type nt = t;
        for (int i = 0; i != d.second(); ++i) {
          nt = new Type.Array(nt);
        }

        Type i_t = d.third().attribute(Type.class);
        try {
          if (!types.subtype(nt, i_t, loader)) {
            ErrorHandler.handleTypeMismatch(
                new TypeMismatchException(d.third(), nt, loader, types),
                d.third().attribute(SourceLocation.class));
          }
        } catch (ClassNotFoundException ex) {
          syntax_error(ex.getMessage(), def);
        }
      }
    }
  }
Пример #17
0
  public void run() {
    boolean gotByePacket = false;

    try {
      /* stream to read from client */
      ObjectInputStream fromClient = new ObjectInputStream(socket.getInputStream());
      Packet packetFromClient;

      /* stream to write back to client */
      ObjectOutputStream toClient = new ObjectOutputStream(socket.getOutputStream());

      // writer to the disk
      // String file = "list";

      // while (( packetFromClient = (Packet) fromClient.readObject()) != null) {
      /* create a packet to send reply back to client */

      packetFromClient = (Packet) fromClient.readObject();
      Packet packetToClient = new Packet();
      packetToClient.type = Packet.LOOKUP_REPLY;
      packetToClient.data = new ArrayList<String>();

      if (packetFromClient.type == Packet.LOOKUP_REQUEST) {
        // called by client
        System.out.println("Request from Client:" + packetFromClient.type);

        packetToClient.type = Packet.LOOKUP_REPLY;
        long start = packetFromClient.start;
        long length = packetFromClient.length;

        if (start > dict.size()) {
          // set the error field, return
          packetToClient.error_code = Packet.ERROR_OUT_OF_RANGE;
        } else {
          for (int i = (int) start; i < start + length && i < dict.size(); i++) {
            packetToClient.data.add(dict.get(i));
          }
        }

        toClient.writeObject(packetToClient);
        // continue;
      }

      // }

      /* cleanup when client exits */
      fromClient.close();
      toClient.close();
      socket.close();

      // close the filehandle

    } catch (IOException e) {
      if (!gotByePacket) {
        e.printStackTrace();
      }
    } catch (ClassNotFoundException e) {
      if (!gotByePacket) e.printStackTrace();
    }
  }
Пример #18
0
  private Graph changeLatentNames(Graph full, Clusters measurements, List<String> latentVarList) {
    Graph g2 = null;

    try {
      g2 = (Graph) new MarshalledObject(full).get();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    for (int i = 0; i < measurements.getNumClusters(); i++) {
      List<String> d = measurements.getCluster(i);
      String latentName = latentVarList.get(i);

      for (Node node : full.getNodes()) {
        if (!(node.getNodeType() == NodeType.LATENT)) {
          continue;
        }

        List<Node> _children = full.getChildren(node);

        _children.removeAll(ReidentifyVariables.getLatents(full));

        List<String> childNames = getNames(_children);

        if (new HashSet<String>(childNames).equals(new HashSet<String>(d))) {
          g2.getNode(node.getName()).setName(latentName);
        }
      }
    }

    return g2;
  }
Пример #19
0
  /** DOCUMENT ME! */
  public void loadRaids() {
    File f = new File(REPO);

    if (!f.exists()) {
      return;
    }

    FileInputStream fIn = null;
    ObjectInputStream oIn = null;

    try {
      fIn = new FileInputStream(REPO);
      oIn = new ObjectInputStream(fIn);
      // de-serializing object
      raids = (HashMap<String, GregorianCalendar>) oIn.readObject();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        oIn.close();
        fIn.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
  private Map<String, SpringResource> generateResourceMap(Set<Class<?>> validClasses)
      throws GenerateException {
    Map<String, SpringResource> resourceMap = new HashMap<String, SpringResource>();
    for (Class<?> c : validClasses) {
      RequestMapping requestMapping = c.getAnnotation(RequestMapping.class);
      String description = "";
      // This try/catch block is to stop a bamboo build from failing due to NoClassDefFoundError
      // This occurs when a class or method loaded by reflections contains a type that has no
      // dependency
      try {
        resourceMap = analyzeController(c, resourceMap, description);
        List<Method> mList = new ArrayList<Method>(Arrays.asList(c.getMethods()));
        if (c.getSuperclass() != null) {
          mList.addAll(Arrays.asList(c.getSuperclass().getMethods()));
        }

      } catch (NoClassDefFoundError e) {
        LOG.error(e.getMessage());
        LOG.info(c.getName());
        // exception occurs when a method type or annotation is not recognized by the plugin
      } catch (ClassNotFoundException e) {
        LOG.error(e.getMessage());
        LOG.info(c.getName());
      }
    }

    return resourceMap;
  }
Пример #21
0
  /**
   * Creates the brain and launches if it is an agent. The brain class is given as a String. The
   * name argument is used to instantiate the name of the corresponding agent. If the gui flag is
   * true, a bean is created and associated to this agent.
   */
  public void makeBrain(String className, String name, boolean gui, String behaviorFileName) {
    try {
      Class c;
      // c = Class.forName(className);
      c = madkit.kernel.Utils.loadClass(className);
      myBrain = (Brain) c.newInstance();
      myBrain.setBody(this);
      if (myBrain instanceof AbstractAgent) {
        String n = name;
        if (n == null) {
          n = getLabel();
        }
        if (n == null) {
          n = getID();
        }
        if (behaviorFileName != null) setBehaviorFileName(behaviorFileName);
        getStructure().getAgent().doLaunchAgent((AbstractAgent) myBrain, n, gui);
      }

    } catch (ClassNotFoundException ev) {
      System.err.println("Class not found :" + className + " " + ev);
      ev.printStackTrace();
    } catch (InstantiationException e) {
      System.err.println("Can't instanciate ! " + className + " " + e);
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      System.err.println("illegal access! " + className + " " + e);
      e.printStackTrace();
    }
  }
Пример #22
0
 static {
   try {
     Class.forName("com.mysql.jdbc.Driver"); // 加载驱动类
     // System.out.println("sql success");
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   }
 }
Пример #23
0
  @Override
  public DeptVO findByPrimaryKey(Integer deptno) {

    DeptVO deptVO = null;
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {

      Class.forName(driver);
      con = DriverManager.getConnection(url, userid, passwd);
      pstmt = con.prepareStatement(GET_ONE_STMT);

      pstmt.setInt(1, deptno);

      rs = pstmt.executeQuery();

      while (rs.next()) {
        // deptVO 也稱為 Domain objects
        deptVO = new DeptVO();
        deptVO.setDeptno(rs.getInt("deptno"));
        deptVO.setDname(rs.getString("dname"));
        deptVO.setLoc(rs.getString("loc"));
      }

      // Handle any driver errors
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Couldn't load database driver. " + e.getMessage());
      // Handle any SQL errors
    } catch (SQLException se) {
      throw new RuntimeException("A database error occured. " + se.getMessage());
      // Clean up JDBC resources
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (pstmt != null) {
        try {
          pstmt.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (con != null) {
        try {
          con.close();
        } catch (Exception e) {
          e.printStackTrace(System.err);
        }
      }
    }
    return deptVO;
  }
  /**
   * 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;
  }
Пример #25
0
 private static Object decode(Class returnType, String valueStr, TypeResolver resolver) {
   if (returnType.isArray()) {
     int sIndex = valueStr.indexOf("{");
     int eIndex = valueStr.lastIndexOf("}");
     String content = valueStr.substring(sIndex + 1, eIndex).trim();
     StringTokenizer tok = new StringTokenizer(content, ",");
     Object ar =
         java.lang.reflect.Array.newInstance(returnType.getComponentType(), tok.countTokens());
     int j = 0;
     while (tok.hasMoreElements()) {
       java.lang.reflect.Array.set(
           ar, j++, decode(returnType.getComponentType(), tok.nextToken(), resolver));
     }
     return ar;
   } else if (returnType.isEnum()) {
     try {
       String value = valueStr.trim();
       if (value.indexOf('.') > 0) {
         value = valueStr.substring(valueStr.lastIndexOf(".") + 1);
       }
       return returnType.getMethod("valueOf", String.class).invoke(null, value);
     } catch (IllegalAccessException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     } catch (InvocationTargetException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     } catch (NoSuchMethodException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     }
   } else if (String.class.equals(returnType)) {
     return unquote(valueStr);
   } else if (boolean.class.equals(returnType)) {
     return Boolean.valueOf(valueStr);
   } else if (int.class.equals(returnType)) {
     return Integer.valueOf(valueStr);
   } else if (double.class.equals(returnType)) {
     return Double.valueOf(valueStr);
   } else if (long.class.equals(returnType)) {
     return Long.valueOf(valueStr);
   } else if (float.class.equals(returnType)) {
     return Float.valueOf(valueStr);
   } else if (short.class.equals(returnType)) {
     return Short.valueOf(valueStr);
   } else if (char.class.equals(returnType)) {
     return unquote(valueStr).charAt(0);
   } else if (Class.class.equals(returnType)) {
     try {
       String cName = valueStr.trim().replace(".class", "");
       return resolver.resolveType(cName);
     } catch (ClassNotFoundException cnfe) {
       cnfe.printStackTrace();
       return Object.class;
     }
   }
   return null;
 }
Пример #26
0
 public OriundoDAO() {
   try {
     Class.forName(new conexao().config.getString("driver"));
   } catch (ClassNotFoundException ex) {
     JOptionPane.showMessageDialog(
         null, "Driver Erro: " + ex.getMessage(), "Construtor da Classe", 0);
     ex.printStackTrace();
   }
 }
Пример #27
0
  @Override
  public List<DeptVO> getAll() {
    List<DeptVO> list = new ArrayList<DeptVO>();
    DeptVO deptVO = null;

    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {

      Class.forName(driver);
      con = DriverManager.getConnection(url, userid, passwd);
      pstmt = con.prepareStatement(GET_ALL_STMT);
      rs = pstmt.executeQuery();

      while (rs.next()) {
        deptVO = new DeptVO();
        deptVO.setDeptno(rs.getInt("deptno"));
        deptVO.setDname(rs.getString("dname"));
        deptVO.setLoc(rs.getString("loc"));
        list.add(deptVO); // Store the row in the list
      }

      // Handle any driver errors
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Couldn't load database driver. " + e.getMessage());
      // Handle any SQL errors
    } catch (SQLException se) {
      throw new RuntimeException("A database error occured. " + se.getMessage());
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (pstmt != null) {
        try {
          pstmt.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (con != null) {
        try {
          con.close();
        } catch (Exception e) {
          e.printStackTrace(System.err);
        }
      }
    }
    return list;
  }
Пример #28
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());
     }
   }
 }
  @Override
  public void execute(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    JSONObject jsonResult = new JSONObject();
    int listDisplayAmount = 5;
    int start = 0;
    String pageNo = request.getParameter("iDisplayStart");
    String pageSize = request.getParameter("iDisplayLength");
    String sortDirection = request.getParameter("sSortDir_0");

    if (pageNo != null) {
      start = Integer.parseInt(pageNo);
      if (start < 0) {
        start = 0;
      }
    }

    if (pageSize != null) {
      try {
        listDisplayAmount = Integer.parseInt(pageSize);
      } catch (Exception e) {
        listDisplayAmount = 5;
      }
      if (listDisplayAmount < 3 || listDisplayAmount > 50) {
        listDisplayAmount = 10;
      }
    }

    if (sortDirection != null) {
      if (!sortDirection.equals("asc")) sortDirection = "desc";
    } else {
      sortDirection = "asc";
    }

    int totalRecords = getTotalRecordCount();

    GLOBAL_SEARCH_TERM = request.getParameter("sSearch");

    try {
      jsonResult = getPersonDetails(start, listDisplayAmount, sortDirection, totalRecords, request);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Cache-Control", "no-store");
    PrintWriter out = response.getWriter();
    out.print(jsonResult);
  }
Пример #30
0
 private Variation createInstance(String className) {
   try {
     return (Variation) Class.forName(className).newInstance();
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   } catch (InstantiationException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   }
   return null;
 }