/** Looks up the local database, creating if necessary. */ private DataSource findDatabaseImpl(String url, String driverName) throws SQLException { try { synchronized (_databaseMap) { DBPool db = _databaseMap.get(url); if (db == null) { db = new DBPool(); db.setVar(url + "-" + _gId++); DriverConfig driver = db.createDriver(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class driverClass = Class.forName(driverName, false, loader); driver.setType(driverClass); driver.setURL(url); db.init(); _databaseMap.put(url, db); } return db; } } catch (RuntimeException e) { throw e; } catch (SQLException e) { throw e; } catch (Exception e) { throw ConfigException.create(e); } }
/** * Should parse a string to select, initialize, and return the user interface selected * * @param optionValue the string to parse * @return the user interface to use */ private void selectUI(String optionValue) { try { Class<?> cls = Class.forName("com.kpro.ui." + optionValue); userInterface = (UserIO) cls.newInstance(); } catch (Exception e) { System.err.println("Selected UserIO not found"); } }
private void guessClassReference(TypedValues list, String name) { try { Class<?> type = Class.forName(fixPotentialArrayName(name)); list.add(new TypedValue(type.getClass(), type)); } catch (ClassNotFoundException y) { _logger.fine(name + " looked like a class reference but is not"); } }
protected static Object newInstance(String name) { try { Class clazz = Class.forName(name); return clazz.newInstance(); } catch (Exception e) { Logger().severe("Cannot extatiate class " + name + ": " + e.getMessage()); return null; } }
/** * Starts the NetworkR specificied by the configuration settings. * * @throws ClassNotFoundException * @throws InvocationTargetException * @throws IllegalAccessException * @throws InstantiationException * @throws SecurityException * @throws IllegalArgumentException */ private void startNetwork() throws ClassNotFoundException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException { // System.err.println("startnetwork called"); Class<?> cls = Class.forName("com.kpro.datastorage." + genProps.getProperty("NetworkRType")); if (cls == null) { System.err.println("NetworkRType incorrect- null in Gio.startNetwork()"); } nr = (NetworkR) cls.getDeclaredConstructors()[0].newInstance(genProps.getProperty("NetworkROptions")); // System.err.println("nr in startNetwork="+nr); }
/** * ************************************************************************ Start Java Process * Class. instanciate the class implementing the interface ProcessCall. The class can be a * Server/Client class (when in Package org compiere.process or org.compiere.model) or a client * only class (e.g. in org.compiere.report) * * @return true if success */ private boolean startProcess() { log.fine(m_pi.toString()); boolean started = false; if (DB.isRemoteProcess()) { Server server = CConnection.get().getServer(); try { if (server != null) { // See ServerBean m_pi = server.process(m_wscctx, m_pi); log.finest("server => " + m_pi); started = true; } } catch (UndeclaredThrowableException ex) { Throwable cause = ex.getCause(); if (cause != null) { if (cause instanceof InvalidClassException) log.log( Level.SEVERE, "Version Server <> Client: " + cause.toString() + " - " + m_pi, ex); else log.log(Level.SEVERE, "AppsServer error(1b): " + cause.toString() + " - " + m_pi, ex); } else log.log(Level.SEVERE, " AppsServer error(1) - " + m_pi, ex); started = false; } catch (Exception ex) { Throwable cause = ex.getCause(); if (cause == null) cause = ex; log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause); started = false; } } // Run locally if (!started && !m_IsServerProcess) { ProcessCall myObject = null; try { Class myClass = Class.forName(m_pi.getClassName()); myObject = (ProcessCall) myClass.newInstance(); if (myObject == null) m_pi.setSummary("No Instance for " + m_pi.getClassName(), true); else myObject.startProcess(m_wscctx, m_pi, m_trx); if (m_trx != null) { m_trx.commit(); m_trx.close(); } } catch (Exception e) { if (m_trx != null) { m_trx.rollback(); m_trx.close(); } m_pi.setSummary("Error starting Class " + m_pi.getClassName(), true); log.log(Level.SEVERE, m_pi.getClassName(), e); } } return !m_pi.isError(); } // startProcess
static { if (enableInstructionDecodeViewer && ((instructionListenerClassName == null) || instructionListenerClassName.equals(""))) { instructionListenerClassName = InstructionViewer.class.getName(); } if ((instructionListenerClassName != null) && !instructionListenerClassName.equals("")) { try { final Class<?> instructionListenerClass = Class.forName(instructionListenerClassName); instructionListener = (InstructionListener) instructionListenerClass.newInstance(); } catch (final ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (dumpFlags) { System.out.println(propPkgName + ".executionMode{GPU|ACC|CPU|JTP|SEQ}=" + executionMode); System.out.println( propPkgName + ".logLevel{OFF|FINEST|FINER|FINE|WARNING|SEVERE|ALL}=" + logger.getLevel()); System.out.println(propPkgName + ".enableProfiling{true|false}=" + enableProfiling); System.out.println(propPkgName + ".enableProfilingCSV{true|false}=" + enableProfilingCSV); System.out.println(propPkgName + ".enableVerboseJNI{true|false}=" + enableVerboseJNI); System.out.println( propPkgName + ".enableVerboseJNIOpenCLResourceTracking{true|false}=" + enableVerboseJNIOpenCLResourceTracking); System.out.println( propPkgName + ".enableShowGeneratedOpenCL{true|false}=" + enableShowGeneratedOpenCL); System.out.println( propPkgName + ".enableExecutionModeReporting{true|false}=" + enableExecutionModeReporting); System.out.println( propPkgName + ".enableInstructionDecodeViewer{true|false}=" + enableInstructionDecodeViewer); System.out.println( propPkgName + ".instructionListenerClassName{<class name which extends com.amd.aparapi.Config.InstructionListener>}=" + instructionListenerClassName); } }
private static Class<?> getClassFromJar(String pathToJar, String pkg, String classToGet) throws IOException, ClassNotFoundException, SecurityException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { JarFile jarFile = new JarFile(pathToJar); Enumeration e = jarFile.entries(); URL[] urls = {new URL("jar:file:" + pathToJar + "!/")}; ClassLoader cl = URLClassLoader.newInstance(urls); Class<?> c = Class.forName(pkg + "." + classToGet, true, cl); return c; }
private void initDriverList() { try { Thread thread = Thread.currentThread(); ClassLoader loader = thread.getContextClassLoader(); Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver"); while (iter.hasMoreElements()) { URL url = (URL) iter.nextElement(); ReadStream is = null; try { is = Vfs.lookup(url.toString()).openRead(); String filename; while ((filename = is.readLine()) != null) { int p = filename.indexOf('#'); if (p >= 0) filename = filename.substring(0, p); filename = filename.trim(); if (filename.length() == 0) continue; try { Class cl = Class.forName(filename, false, loader); Driver driver = null; if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance(); if (driver != null) { log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName())); _driverList.add(driver); } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } finally { if (is != null) is.close(); } } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } }
/** * Should parse a string to select, initialize, and return one of the policy databases coded * * @param optionValue the string to parse * @return the policy database being used */ private void selectPDB(String optionValue) { try { Class<?> cls = Class.forName("com.kpro.datastorage." + optionValue); @SuppressWarnings("rawtypes") Class[] params = new Class[2]; params[0] = String.class; params[1] = String.class; Method m = cls.getDeclaredMethod("getInstance", params); Object[] argslist = new Object[2]; argslist[0] = genProps.getProperty("inDBLoc"); argslist[1] = genProps.getProperty("outDBLoc", genProps.getProperty("inDBLoc")); pdb = (PolicyDatabase) m.invoke(null, argslist); } catch (Exception e) { System.err.println("Selected PolicyDatabase not found"); } if (pdb == null) { System.err.println("pdb null in selectPDB"); } }
public static void preventEventualClassLoadingConflicts() { // Pre-load certain JMockit classes to avoid NoClassDefFoundError's or re-entrancy loops during // class loading // when certain JRE classes are mocked, such as ArrayList or Thread. try { Class.forName("mockit.Capturing"); Class.forName("mockit.Delegate"); Class.forName("mockit.Invocation"); Class.forName("mockit.internal.RedefinitionEngine"); Class.forName("mockit.internal.util.GeneratedClasses"); Class.forName("mockit.internal.util.MethodReflection"); Class.forName("mockit.internal.util.ObjectMethods"); Class.forName("mockit.internal.util.TypeDescriptor"); Class.forName("mockit.internal.expectations.RecordAndReplayExecution"); Class.forName("mockit.internal.expectations.invocation.InvocationResults"); Class.forName("mockit.internal.expectations.invocation.MockedTypeCascade"); Class.forName("mockit.internal.expectations.mocking.BaseTypeRedefinition$MockedClass"); Class.forName("mockit.internal.expectations.mocking.SharedFieldTypeRedefinitions"); Class.forName("mockit.internal.expectations.mocking.TestedClasses"); Class.forName("mockit.internal.expectations.argumentMatching.EqualityMatcher"); } catch (ClassNotFoundException ignore) { } wasCalledDuringClassLoading(); DefaultValues.computeForReturnType("()J"); }
public Codable newInstance(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException { return (Codable) Class.forName(className).newInstance(); }
/** * Main method used to startup muCommander. * * @param args command line arguments. * @throws IOException if an unrecoverable error occurred during startup */ public static void main(String args[]) throws IOException { try { int i; // Index in the command line arguments. // Initialises fields. // Whether or not to ignore warnings when booting. boolean fatalWarnings = false; verbose = true; // - Command line parsing ------------------------------------- // ------------------------------------------------------------ for (i = 0; i < args.length; i++) { // Print version. if (args[i].equals("-v") || args[i].equals("--version")) printVersion(); // Print help. else if (args[i].equals("-h") || args[i].equals("--help")) printUsage(); // Associations handling. else if (args[i].equals("-a") || args[i].equals("--assoc")) { if (i >= args.length - 1) printError("Missing FILE parameter to " + args[i], null, true); try { com.mucommander.command.CommandManager.setAssociationFile(args[++i]); } catch (Exception e) { printError("Could not set association files", e, fatalWarnings); } } // Custom commands handling. else if (args[i].equals("-f") || args[i].equals("--commands")) { if (i >= args.length - 1) printError("Missing FILE parameter to " + args[i], null, true); try { com.mucommander.command.CommandManager.setCommandFile(args[++i]); } catch (Exception e) { printError("Could not set commands file", e, fatalWarnings); } } // Bookmarks handling. else if (args[i].equals("-b") || args[i].equals("--bookmarks")) { if (i >= args.length - 1) printError("Missing FILE parameter to " + args[i], null, true); try { com.mucommander.bookmark.BookmarkManager.setBookmarksFile(args[++i]); } catch (Exception e) { printError("Could not set bookmarks file", e, fatalWarnings); } } // Configuration handling. else if (args[i].equals("-c") || args[i].equals("--configuration")) { if (i >= args.length - 1) printError("Missing FILE parameter to " + args[i], null, true); try { MuConfiguration.setConfigurationFile(args[++i]); } catch (Exception e) { printError("Could not set configuration file", e, fatalWarnings); } } // Shell history. else if (args[i].equals("-s") || args[i].equals("--shell-history")) { if (i >= args.length - 1) printError("Missing FILE parameter to " + args[i], null, true); try { ShellHistoryManager.setHistoryFile(args[++i]); } catch (Exception e) { printError("Could not set shell history file", e, fatalWarnings); } } // Keymap file. else if (args[i].equals("-k") || args[i].equals("--keymap")) { if (i >= args.length - 1) printError("Missing FILE parameter to " + args[i], null, true); try { com.mucommander.ui.action.ActionKeymapIO.setActionsFile(args[++i]); } catch (Exception e) { printError("Could not set keymap file", e, fatalWarnings); } } // Toolbar file. else if (args[i].equals("-t") || args[i].equals("--toolbar")) { if (i >= args.length - 1) printError("Missing FILE parameter to " + args[i], null, true); try { ToolBarIO.setDescriptionFile(args[++i]); } catch (Exception e) { printError("Could not set keymap file", e, fatalWarnings); } } // Commandbar file. else if (args[i].equals("-C") || args[i].equals("--commandbar")) { if (i >= args.length - 1) printError("Missing FILE parameter to " + args[i], null, true); try { CommandBarIO.setDescriptionFile(args[++i]); } catch (Exception e) { printError("Could not set commandbar description file", e, fatalWarnings); } } // Credentials file. else if (args[i].equals("-U") || args[i].equals("--credentials")) { if (i >= args.length - 1) printError("Missing FILE parameter to " + args[i], null, true); try { com.mucommander.auth.CredentialsManager.setCredentialsFile(args[++i]); } catch (Exception e) { printError("Could not set credentials file", e, fatalWarnings); } } // Preference folder. else if ((args[i].equals("-p") || args[i].equals("--preferences"))) { if (i >= args.length - 1) printError("Missing FOLDER parameter to " + args[i], null, true); try { PlatformManager.setPreferencesFolder(args[++i]); } catch (Exception e) { printError("Could not set preferences folder", e, fatalWarnings); } } // Extensions folder. else if ((args[i].equals("-e") || args[i].equals("--extensions"))) { if (i >= args.length - 1) printError("Missing FOLDER parameter to " + args[i], null, true); try { ExtensionManager.setExtensionsFolder(args[++i]); } catch (Exception e) { printError("Could not set extensions folder", e, fatalWarnings); } } // Ignore warnings. else if (args[i].equals("-i") || args[i].equals("--ignore-warnings")) fatalWarnings = false; // Fail on warnings. else if (args[i].equals("-w") || args[i].equals("--fail-on-warnings")) fatalWarnings = true; // Silent mode. else if (args[i].equals("-S") || args[i].equals("--silent")) verbose = false; // Verbose mode. else if (args[i].equals("-V") || args[i].equals("--verbose")) verbose = true; // Illegal argument. else break; } // - Configuration init --------------------------------------- // ------------------------------------------------------------ // Ensure that a graphics environment is available, exit otherwise. checkHeadless(); // Attempts to guess whether this is the first time muCommander is booted or not. boolean isFirstBoot; try { isFirstBoot = !MuConfiguration.getConfigurationFile().exists(); } catch (IOException e) { isFirstBoot = true; } // Configuration needs to be loaded before any sort of GUI creation is performed : under Mac // OS X, if we're // to use the metal look, we need to know about it right about now. try { MuConfiguration.read(); } catch (Exception e) { printFileError("Could not load configuration", e, fatalWarnings); } // - Logging configuration ------------------------------------ // ------------------------------------------------------------ configureLogging(); // - MAC OS X specific init ----------------------------------- // ------------------------------------------------------------ // If muCommander is running under Mac OS X (how lucky!), add some glue for the main menu bar // and other OS X // specifics. if (OsFamilies.MAC_OS_X.isCurrent()) { // Use reflection to create an OSXIntegration instance so that ClassLoader // doesn't throw an NoClassDefFoundException under platforms other than Mac OS X try { Class<?> osxIntegrationClass = Class.forName("com.mucommander.ui.macosx.OSXIntegration"); Constructor<?> constructor = osxIntegrationClass.getConstructor(new Class[] {}); constructor.newInstance(); } catch (Exception e) { AppLogger.fine("Exception thrown while initializing Mac OS X integration", e); } } // - muCommander boot ----------------------------------------- // ------------------------------------------------------------ // Adds all extensions to the classpath. try { ExtensionManager.addExtensionsToClasspath(); } catch (Exception e) { AppLogger.fine("Failed to add extensions to the classpath", e); } // This the property is supposed to have the java.net package use the proxy defined in the // system settings // to establish HTTP connections. This property is supported only under Java 1.5 and up. // Note that Mac OS X already uses the system HTTP proxy, with or without this property being // set. System.setProperty("java.net.useSystemProxies", "true"); // Shows the splash screen, if enabled in the preferences useSplash = MuConfiguration.getVariable( MuConfiguration.SHOW_SPLASH_SCREEN, MuConfiguration.DEFAULT_SHOW_SPLASH_SCREEN); if (useSplash) { splashScreen = new SplashScreen(RuntimeConstants.VERSION, "Loading preferences..."); } boolean showSetup; showSetup = MuConfiguration.getVariable(MuConfiguration.THEME_TYPE) == null; // Traps VM shutdown Runtime.getRuntime().addShutdownHook(new ShutdownHook()); // Configure filesystems configureFilesystems(); // Initializes the desktop. try { com.mucommander.desktop.DesktopManager.init(isFirstBoot); } catch (Exception e) { printError("Could not initialize desktop", e, true); } // Loads dictionary printStartupMessage("Loading dictionary..."); try { com.mucommander.text.Translator.loadDictionaryFile(); } catch (Exception e) { printError("Could not load dictionary", e, true); } // Loads custom commands printStartupMessage("Loading file associations..."); try { com.mucommander.command.CommandManager.loadCommands(); } catch (Exception e) { printFileError("Could not load custom commands", e, fatalWarnings); } // Migrates the custom editor and custom viewer if necessary. migrateCommand("viewer.use_custom", "viewer.custom_command", CommandManager.VIEWER_ALIAS); migrateCommand("editor.use_custom", "editor.custom_command", CommandManager.EDITOR_ALIAS); try { CommandManager.writeCommands(); } catch (Exception e) { System.out.println("###############################"); AppLogger.fine("Caught exception", e); // There's really nothing we can do about this... } try { com.mucommander.command.CommandManager.loadAssociations(); } catch (Exception e) { printFileError("Could not load custom associations", e, fatalWarnings); } // Loads bookmarks printStartupMessage("Loading bookmarks..."); try { com.mucommander.bookmark.BookmarkManager.loadBookmarks(); } catch (Exception e) { printFileError("Could not load bookmarks", e, fatalWarnings); } // Loads credentials printStartupMessage("Loading credentials..."); try { com.mucommander.auth.CredentialsManager.loadCredentials(); } catch (Exception e) { printFileError("Could not load credentials", e, fatalWarnings); } // Loads shell history printStartupMessage("Loading shell history..."); try { ShellHistoryManager.loadHistory(); } catch (Exception e) { printFileError("Could not load shell history", e, fatalWarnings); } // Inits CustomDateFormat to make sure that its ConfigurationListener is added // before FileTable, so CustomDateFormat gets notified of date format changes first com.mucommander.text.CustomDateFormat.init(); // Initialize file icons printStartupMessage("Loading icons..."); // Initialize the SwingFileIconProvider from the main thread, see method Javadoc for an // explanation on why we do this now SwingFileIconProvider.forceInit(); // The math.max(1.0f, ...) part is to workaround a bug which cause(d) this value to be set to // 0.0 in the configuration file. com.mucommander.ui.icon.FileIcons.setScaleFactor( Math.max( 1.0f, MuConfiguration.getVariable( MuConfiguration.TABLE_ICON_SCALE, MuConfiguration.DEFAULT_TABLE_ICON_SCALE))); com.mucommander.ui.icon.FileIcons.setSystemIconsPolicy( MuConfiguration.getVariable( MuConfiguration.USE_SYSTEM_FILE_ICONS, MuConfiguration.DEFAULT_USE_SYSTEM_FILE_ICONS)); // Register actions printStartupMessage("Registering actions..."); ActionManager.registerActions(); // Loads the ActionKeymap file printStartupMessage("Loading actions shortcuts..."); try { com.mucommander.ui.action.ActionKeymapIO.loadActionKeymap(); } catch (Exception e) { printFileError("Could not load actions shortcuts", e, fatalWarnings); } // Loads the ToolBar's description file printStartupMessage("Loading toolbar description..."); try { ToolBarIO.loadDescriptionFile(); } catch (Exception e) { printFileError("Could not load toolbar description", e, fatalWarnings); } // Loads the CommandBar's description file printStartupMessage("Loading command bar description..."); try { CommandBarIO.loadCommandBar(); } catch (Exception e) { printFileError("Could not load commandbar description", e, fatalWarnings); } // Loads the themes. printStartupMessage("Loading theme..."); com.mucommander.ui.theme.ThemeManager.loadCurrentTheme(); // Starts Bonjour services discovery (only if enabled in prefs) printStartupMessage("Starting Bonjour services discovery..."); com.mucommander.bonjour.BonjourDirectory.setActive( MuConfiguration.getVariable( MuConfiguration.ENABLE_BONJOUR_DISCOVERY, MuConfiguration.DEFAULT_ENABLE_BONJOUR_DISCOVERY)); // Creates the initial main frame using any initial path specified by the command line. printStartupMessage("Initializing window..."); for (; i < args.length; i += 2) { if (i < args.length - 1) WindowManager.createNewMainFrame(args[i], args[i + 1]); else WindowManager.createNewMainFrame(args[i], null); } // If no initial path was specified, start a default main window. if (WindowManager.getCurrentMainFrame() == null) WindowManager.createNewMainFrame(); // Done launching, wake up threads waiting for the application being launched. // Important: this must be done before disposing the splash screen, as this would otherwise // create a deadlock // if the AWT event thread were waiting in #waitUntilLaunched . synchronized (LAUNCH_LOCK) { isLaunching = false; LAUNCH_LOCK.notifyAll(); } // Enable system notifications, only after MainFrame is created as SystemTrayNotifier needs to // retrieve // a MainFrame instance if (MuConfiguration.getVariable( MuConfiguration.ENABLE_SYSTEM_NOTIFICATIONS, MuConfiguration.DEFAULT_ENABLE_SYSTEM_NOTIFICATIONS)) { printStartupMessage("Enabling system notifications..."); if (com.mucommander.ui.notifier.AbstractNotifier.isAvailable()) com.mucommander.ui.notifier.AbstractNotifier.getNotifier().setEnabled(true); } // Dispose splash screen. if (splashScreen != null) splashScreen.dispose(); // Check for newer version unless it was disabled if (MuConfiguration.getVariable( MuConfiguration.CHECK_FOR_UPDATE, MuConfiguration.DEFAULT_CHECK_FOR_UPDATE)) new CheckVersionDialog(WindowManager.getCurrentMainFrame(), false); // If no theme is configured in the preferences, ask for an initial theme. if (showSetup) new InitialSetupDialog(WindowManager.getCurrentMainFrame()).showDialog(); } catch (Throwable t) { // Startup failed, dispose the splash screen if (splashScreen != null) splashScreen.dispose(); AppLogger.severe("Startup failed", t); // Display an error dialog with a proper message and error details InformationDialog.showErrorDialog(null, null, Translator.get("startup_error"), null, t); // Quit the application WindowManager.quit(); } }
public Class<?> loadClass(String name) throws ClassNotFoundException { return Class.forName(name); }
private TypedValues guessUntypedValue(String name, String value) { TypedValues list = new TypedValues(name); if (value.startsWith("java:")) { // possible java static reference int dot; if (value.equals("java:null")) { list.add(new TypedValue(Object.class, null)); } else if (value.charAt(5) == '$') { // reference to a local object (assemble @id) ElementInfo element = _local.get(value.substring(6)); if (element != null) { list.add(new TypedValue(element.type, element.data)); } } else if ((dot = value.lastIndexOf('.')) > 5) { try { // public static refernce? (don't override access control) _logger.fine("public static refernce? " + value); Object object = Class.forName(value.substring(5, dot)).getField(value.substring(dot + 1)).get(null); Class<?> type = object.getClass(); list.add(new TypedValue(type, object)); // automatic upscaling to larger types if (type == Byte.class) { object = new Short(((Byte) object).byteValue()); list.add(new TypedValue(Short.class, object)); type = Short.class; } if (type == Short.class) { object = new Integer(((Short) object).shortValue()); list.add(new TypedValue(Integer.class, object)); type = Integer.class; } if (type == Integer.class) { object = new Long(((Integer) object).intValue()); list.add(new TypedValue(Long.class, object)); type = Long.class; } if (type == Long.class) { object = new Float(((Long) object).longValue()); list.add(new TypedValue(Float.class, object)); type = Float.class; } if (type == Float.class) { object = new Double(((Float) object).floatValue()); list.add(new TypedValue(Double.class, object)); } } catch (Exception x) { _logger.fine(value + " looked like a static reference but is not: " + x.getMessage()); // class reference? guessClassReference(list, value.substring(5)); } } else { // no '.' at all // class reference? guessClassReference(list, value.substring(5)); } } else if (value.equals("true")) { list.add(new TypedValue(Boolean.class, Boolean.TRUE)); } else if (value.equals("false")) { list.add(new TypedValue(Boolean.class, Boolean.FALSE)); } else { // numbers? multiple possibilities try { list.add(new TypedValue(Integer.class, Integer.valueOf(value))); } catch (Exception x) { } try { list.add(new TypedValue(Long.class, Long.valueOf(value))); } catch (Exception x) { } try { list.add(new TypedValue(Float.class, Float.valueOf(value))); } catch (Exception x) { } try { list.add(new TypedValue(Double.class, Double.valueOf(value))); } catch (Exception x) { } } // always try String as the last resort list.add(new TypedValue(String.class, value)); return list; }
/** Receive notification of the start of an element. */ @Override public void startElement(String uri, String l, String q, Attributes a) { /* * 1. Load a class that matches the element name. * 2. If no class found, assume the element maps to a String. * 3. Otherwise, construct a new object of the class with element attributes. */ _logger.fine( S.fine(_logger) ? "Consider element " + l + "\n uri " + uri + "\n q " + q : null); ElementInfo info = new ElementInfo(); // Record java packages defined on this element as xmlns for (int i = 0; i < a.getLength(); ++i) { _logger.fine( S.fine(_logger) ? " attr " + a.getQName(i) + "=" + a.getValue(i) + "\n " + a.getQName(i) + ":" + a.getURI(i) : null); if (a.getQName(i).startsWith("xmlns:") && a.getValue(i).startsWith("java://")) { info.pkgs.put(a.getQName(i).substring(6), a.getValue(i).substring(7)); } } // Resolve the package name of this element, which could be empty (default package) int colon = q.indexOf(':'); if (colon > 0) { String xmlns = q.substring(0, colon); // is it defined right here? info.jpkg = info.pkgs.get(xmlns); // find a matching namespace from ancesters if (info.jpkg == null && !_stack.isEmpty()) { for (int i = _stack.size() - 1; i >= 0; --i) { info.jpkg = _stack.get(i).pkgs.get(xmlns); if (info.jpkg != null) { break; } } } } else if (isPrimitiveType(q)) { info.jpkg = "java.lang"; } else if (!_stack.isEmpty()) { info.jpkg = _stack.get(_stack.size() - 1).jpkg; } else { info.jpkg = _jpkg; } _logger.fine("to create element with package = " + info.jpkg); try { info.name = (info.jpkg != null) ? info.jpkg + '.' + Strings.toCamelCase(l) : Strings.toCamelCase(l); try { if (info.name.endsWith("...")) { // Array construction info.type = Class.forName(info.name.substring(0, info.name.length() - 3)); info.data = new ArrayList<Object>(); } else { // Non-array construction int size = a.getLength(); TypedValueGroup arguments = new TypedValueGroup(); for (int i = 0; i < size; ++i) { if (!a.getQName(i).startsWith("xmlns:") && !a.getQName(i).equals("xmlns")) { arguments.add(guessUntypedValue(a.getQName(i), a.getValue(i))); } } arguments.complete(); _logger.fine(S.fine(_logger) ? "arguments=" + arguments : null); if (arguments.size() > 0) { if (arguments.size() == 1 && "java.lang".equals(info.jpkg)) { info.inst.put( "@as", Strings.toCamelCase( arguments.get(0).name, '-', false)); // respect original spelling info.data = arguments.get(0).get(0).data; info.type = arguments.get(0).get(0).type; } else { Exception last = null; Object[] args = new Object[arguments.size()]; while (arguments.load(args, 0)) { try { _logger.fine( S.fine(_logger) ? "to create " + info.name + " with args: " + args.length + args(args) : null); info.data = _factory.create(info.name, args); info.type = info.data.getClass(); break; } catch (InvocationTargetException x) { throw x; } catch (Exception x) { last = x; _logger.fine( "failure in creating " + info.name + ": probing for other constructors"); } } if (info.data == null) { throw last; } } } else { _logger.fine("Create " + info.name + " with the default constructor"); info.data = _factory.create(info.name); info.type = info.data.getClass(); } } } catch (ClassNotFoundException x) { // no class by the element name is found, assumed String if (!_lenient) { throw new BeanAssemblyException("No class associated with element " + q); } else { _logger.log(Level.WARNING, "can't find class " + info.name, x); } } _stack.add(info); // _logger.fine(">>ElementInfo: " + info.type.getName() + " in " + info); // all other exceptions indicate mismatches between the beans and the XML schema } catch (Exception x) { if (!_lenient) { throw new BeanAssemblyException("Failed to assemble bean from element " + q, x); } else { _logger.log(Level.SEVERE, "can't create object for this element", x); } } }
public static void main(String arg[]) { Hashtable ignoreList = new Hashtable(); Class cl = null; Model model = null; System.out.println("Synchronizing forms with database..."); Db.init(); try { DatabaseMetaData meta = Db.getCon().getMetaData(); String[] types = {"TABLE"}; ResultSet rs = meta.getTables(null, null, "%", types); // read ignore.list ignoreList = AutogenerateUtil.readIgnoreList(); // prepare directory File fDir = new File("../../web/WEB-INF/views/crud_form"); if (!fDir.exists()) fDir.mkdir(); while (rs.next()) { // proper file name generationm String className = ""; String tableName = rs.getString("TABLE_NAME"); className = StringUtil.toProperClassName(tableName); // space allowed... // tableName = tableName.toUpperCase(); //If Oracle that need uppercase tablename. In MySQL // in Mac OS X (and probably Linux), it mustbe case sensitive // open table String sql = "select * from " + tableName; PreparedStatement pstmt = Db.getCon() .prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet resultSet = pstmt.executeQuery(); ResultSetMetaData metaColumn = resultSet.getMetaData(); int nColoumn = metaColumn.getColumnCount(); // get foreign keys,and stored it in hashtable ResultSet rsFk = meta.getImportedKeys(Db.getCon().getCatalog(), null, tableName); Hashtable hashFk = new Hashtable(); System.out.println("FK Infos for table " + tableName); while (rsFk.next()) { String pkTableName = rsFk.getString("PKTABLE_NAME"); String pkColumnName = rsFk.getString("PKCOLUMN_NAME"); String fkColumnName = rsFk.getString("FKCOLUMN_NAME"); int fkSequence = rsFk.getInt("KEY_SEQ"); System.out.println( tableName + "." + fkColumnName + " => " + pkTableName + "." + pkColumnName); hashFk.put(fkColumnName, pkColumnName); hashFk.put(fkColumnName + "_table", pkTableName); } rsFk.close(); // create form page System.out.println( "Creating form page for " + tableName + " from table + " + application.config.Database.DB + "." + tableName); fDir = new File("../../web/WEB-INF/views/" + tableName); if (!fDir.exists()) fDir.mkdir(); File f = new File("../../web/WEB-INF/views/" + tableName + "/form_" + tableName + ".jsp"); if (ignoreList.get("form_" + tableName + ".jsp") != null) { Logger.getLogger(GenerateForm.class.getName()) .log(Level.INFO, "Ignoring creation of form_" + tableName + ".jsp"); } else { Writer out = new FileWriter(f); out.write( "<%@ page contentType=\"text/html; charset=UTF-8\" language=\"java\" import=\"java.sql.*,recite18th.library.Db,application.config.Config,recite18th.library.Pagination\" %>"); out.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n"); out.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\n"); // create model for this class, use in detecting its PK Field cl = Class.forName("application.models." + className + "Model"); model = (Model) cl.newInstance(); // iterate all columns resultSet.beforeFirst(); resultSet.next(); out.write( "<table border=\"1\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" bordercolor=\"#E8EDFF\">\n"); out.write("<tr>\n"); out.write("<td>\n"); out.write( "<form action=\"<%=Config.base_url%>index/" + className + "/save\" method=\"post\" enctype=\"multipart/form-data\">\n"); // I hope it's // okay to // default it to // multipart data out.write("<table id=\"hor-zebra\" summary=\"Form " + className + "\">\n"); out.write("<thead>\n"); out.write("<tr>\n"); out.write("<th colspan=\"2\" class=\"odd\" scope=\"col\">Form " + className + " </th>\n"); out.write("</tr>\n"); out.write("</thead>\n"); out.write("<tbody>\n"); for (int i = 1; i <= nColoumn; i++) { String columnName = metaColumn.getColumnName(i); String dataType = metaColumn.getColumnClassName(i); out.write("<tr>\n"); // if(!columnName.equals(model.getPkFieldName())) // implementing the case of PK not // AutoIncrement // if(!metaColumn.isAutoIncrement(i)) // { // varying field input for type // foreign field, as chooser page view if (hashFk.get(columnName) != null) // TODO: what if PK is chooser also?? :) CUrrently I add it manually the // hidden_*Pk_nama* field { String fkTableName = hashFk.get(columnName + "_table") + ""; String fkColumnName = hashFk.get(columnName) + ""; String fkController = StringUtil.toProperClassName(fkTableName); out.write("<td>" + columnName + "</td>\n"); out.write("<td>\n"); out.write( "<input name=\"" + columnName + "\" type=\"hidden\" id=\"" + columnName + "\" value=\"${model." + columnName + "}\"/>\n"); out.write( "<input name=\"label_" + columnName + "\" readonly=\"true\" type=\"text\" id=\"label_" + columnName + "\" value=\"${model." + columnName + "}\"/>\n"); // TODO : translate I out.write( "<a href=\"<%=Config.base_url%>index/" + fkController + "/chooseView?height=220&width=700\" class=\"thickbox\">Pilih</a>"); out.write("</td>\n"); } else { // regular field input, not foreign key case if (!columnName.equals(model.getPkFieldName())) { out.write("<td>" + columnName + "</td>\n"); out.write("<td>\n"); // ENUM Column, displayed as HTML SELECT. May will only work for mysql only... Logger.getLogger(GenerateForm.class.getName()) .log(Level.INFO, columnName + " type is " + metaColumn.getColumnType(i)); if (metaColumn.getColumnType(i) == 1) { String enum_content[][] = Db.getDataSet( "SELECT SUBSTRING(COLUMN_TYPE,6,length(SUBSTRING(COLUMN_TYPE,6))-1) as enum_content " + " FROM information_schema.COLUMNS " + " WHERE TABLE_NAME='" + tableName + "' " + " AND COLUMN_NAME='" + columnName + "'"); if (enum_content.length > 0) { // Logger.getLogger(Model.class.getName()).log(Level.INFO, "Enum Content = " + // enum_content[0][0]); String enum_list[] = enum_content[0][0].split(","); out.write("<select name=\"" + columnName + "\" id=\"" + columnName + "\">\n"); for (int ienum_list = 0; ienum_list < enum_list.length; ienum_list++) out.write( "\t<option <c:if test=\"${model." + columnName + "=='" + enum_list[ienum_list].substring( 1, enum_list[ienum_list].length() - 1) + "'}\"> selected=\"selected\" </c:if> value=\"" + enum_list[ienum_list].substring( 1, enum_list[ienum_list].length() - 1) + "\">" + enum_list[ienum_list].substring( 1, enum_list[ienum_list].length() - 1) + "</option>\n"); out.write("</select>\n\n"); } else { // no enum content detected.. :) out.write( "<input name=\"" + columnName + "\" type=\"text\" id=\"" + columnName + "\" value=\"${model." + columnName + "}\"/>\n"); } } else if (metaColumn.getColumnType(i) == 91) { out.write( "<input name=\"" + columnName + "\" type=\"text\" id=\"" + columnName + "\" value=\"${model." + columnName + "}\"/>\n"); out.write("<script>\n"); out.write( " if(!isValidDate($('#" + columnName + "').val())) $('#" + columnName + "').val('1980-1-1');\n"); // TODO: default value out.write(" (function($){\n"); out.write(" $('#" + columnName + "').click(function() {\n"); out.write(" $('#" + columnName + "').DatePickerShow();\n"); out.write(" });\n"); out.write(" $('#" + columnName + "').DatePicker({\n"); out.write(" format:'Y-m-d',\n"); out.write(" date: $('#" + columnName + "').val(),\n"); out.write(" current: $('#" + columnName + "').val(),\n"); out.write(" starts: 1,\n"); out.write(" position: 'r',\n"); out.write(" onBeforeShow: function(){\n"); out.write( " $('#" + columnName + "').DatePickerSetDate($('#" + columnName + "').val(), true);\n"); out.write(" },\n"); out.write(" onChange: function(formated, dates){\n"); out.write(" $('#" + columnName + "').DatePickerHide();\n"); out.write(" $('#" + columnName + "').val(formated);\n"); out.write(" }\n"); out.write(" });\n"); out.write(" })(jQuery)\n"); out.write(" </script>\n"); } else { out.write( "<input name=\"" + columnName + "\" type=\"text\" id=\"" + columnName + "\" value=\"${model." + columnName + "}\"/>\n"); out.write("${" + columnName + "_error}\n"); // regular input field } } else { // PK case if (metaColumn.isAutoIncrement(i)) { out.write( "<input name=\"hidden_" + columnName + "\" type=\"hidden\" id=\"hidden_" + columnName + "\" value=\"${model." + columnName + "}\"/>\n"); } else { out.write("<td>" + columnName + "</td>\n"); out.write("<td>\n"); out.write( "<input name=\"" + columnName + "\" type=\"text\" id=\"" + columnName + "\" value=\"${model." + columnName + "}\"/>\n"); out.write("${" + columnName + "_error}\n"); out.write( "<input name=\"hidden_" + columnName + "\" type=\"hidden\" id=\"hidden_" + columnName + "\" value=\"${model." + columnName + "}\"/>\n"); } } out.write("</td>\n"); } out.write("</tr>\n"); } out.write("<tr class=\"odd\">\n"); out.write("<td> </td>\n"); out.write("<td><input type=\"submit\" name=\"Submit\" value=\"Simpan\">"); out.write( "<input name=\"Button\" type=\"button\" id=\"Submit\" value=\"Batal\" onClick=\"javascript:history.back(-1);\"></td>\n"); out.write("</tr>\n"); out.write("</tbody>\n"); out.write("</table>\n"); out.write("</form></td>\n"); out.write("</tr>\n"); out.write("</table>\n"); out.flush(); out.close(); } // create viewPage if (ignoreList.get("view_" + tableName + ".jsp") != null) { Logger.getLogger(GenerateForm.class.getName()) .log(Level.INFO, "Ignoring creation of view_" + tableName + ".jsp"); } else { System.out.println("Creating view page " + tableName); fDir = new File("../../web/WEB-INF/views/" + tableName); if (!fDir.exists()) fDir.mkdir(); File fView = new File("../../web/WEB-INF/views/" + tableName + "/view_" + tableName + ".jsp"); Writer outView = new FileWriter(fView); outView.write( "<%@ page contentType=\"text/html; charset=UTF-8\" language=\"java\" import=\"java.sql.*,recite18th.library.Db,application.config.Config,recite18th.library.Pagination\" %>"); outView.write("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n"); outView.write( "<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\n"); outView.write("<% int pagenum = 0; %>\n"); // outView.write("<%@ include file=\"/WEB-INF/views/header.jsp\" %>"); outView.write( "<a href=\"<%=Config.base_url%>index/" + className + "/input/-1\">Tambah Data</a>\n"); outView.write( "|| <a href=\"<%=Config.base_url%>index/" + className + "/print\">Cetak</a>\n"); outView.write("<table width=\"100%\" id=\"rounded-corner\">\n"); outView.write("<thead>\n"); // iterate all columns : table header outView.write(" <tr>\n"); outView.write(" <th scope=\"col\" class=\"rounded-company\">No.</th>\n"); resultSet.beforeFirst(); resultSet.next(); // get Primary Key Field Name : often use String pkFieldName = ""; try { Class params[] = null; Method objMethod = cl.getMethod("getPkFieldName", params); pkFieldName = "" + objMethod.invoke(model); } catch (Exception ex) { Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex); } // ALL Lower Case pkFieldName = pkFieldName.toLowerCase(); // customize column view page for (int i = 1; i <= nColoumn; i++) { String columnName = metaColumn.getColumnName(i).toLowerCase(); // Caution : ALL LowerCase String dataType = metaColumn.getColumnClassName(i); String thClass = "rounded-q1"; String thTitle = StringUtil.toProperFieldTitle(columnName); if (TableCustomization.getTable(tableName) != null) // there is customization for this table { if (TableCustomization.getTable(tableName).get(columnName) != null) { thTitle = TableCustomization.getTable(tableName).get(columnName) + ""; outView.write( " <th scope=\"col\" class=\"" + thClass + "\">" + thTitle + "</th>\n"); } } else { // standard view for this table : hide PK, because mostly is auto increment if (!metaColumn.isAutoIncrement(i)) outView.write( " <th scope=\"col\" class=\"" + thClass + "\">" + thTitle + "</th>\n"); } } outView.write(" <th scope=\"col\" class=\"rounded-q4\">Aksi</th>\n"); outView.write(" </tr>\n"); outView.write("</thead>\n"); outView.write("<tfoot>\n"); outView.write(" <tr>\n"); outView.write( " <td colspan=\"" + (nColoumn + 1) + "\" class=\"rounded-foot-left\"><%=Pagination.createLinks(pagenum)%></td>\n"); outView.write(" <td class=\"rounded-foot-right\"> </td>\n"); outView.write(" </tr>\n"); outView.write("</tfoot>\n"); outView.write("<tbody>\n"); outView.write(" <c:forEach items=\"${row}\" var=\"item\" varStatus=\"status\" >\n"); outView.write(" <tr>\n"); outView.write(" <td>${status.count}</td>\n"); // iterate all columns : table data resultSet.beforeFirst(); resultSet.next(); for (int i = 1; i <= nColoumn; i++) { String columnName = metaColumn.getColumnName(i); // if(!columnName.equals(pkFieldName)) //TOFIX : currently, PK Field is not shown if (TableCustomization.getTable(tableName) != null) { if (TableCustomization.getTable(tableName).get(columnName) != null) { outView.write(" <td>${item." + columnName + "}</td>\n"); } } else { if (!metaColumn.isAutoIncrement(i)) outView.write(" <td>${item." + columnName + "}</td>\n"); } } outView.write(" <td>\n"); outView.write( " <a href=\"<%=Config.base_url%>index/" + className + "/input/${item." + pkFieldName + "}\">Ubah</a>\n"); outView.write( " <a href=\"<%=Config.base_url%>index/" + className + "/delete/${item." + pkFieldName + "}\" onClick=\"return confirm('Apakah Anda yakin?');\">Hapus</a>\n"); outView.write(" </td>\n"); outView.write(" </tr>\n"); outView.write(" </c:forEach>\n"); outView.write("</tbody>\n"); outView.write("</table>\n"); // outView.write("<%@ include file=\"/WEB-INF/views/footer.jsp\" %>"); outView.flush(); outView.close(); } } } catch (Exception e) { e.printStackTrace(); } }