List of usage examples for java.lang InstantiationException InstantiationException
public InstantiationException(String s)
From source file:jp.furplag.util.commons.ObjectUtils.java
/** * substitute for {@link java.lang.Class#newInstance()}. * * @param typeRef {@link com.fasterxml.jackson.core.type.TypeReference}. * @return empty instance of specified {@link java.lang.Class}. * @throws InstantiationException/* ww w . j a v a2s. com*/ * @throws IllegalAccessException * @throws NegativeArraySizeException * @throws ClassNotFoundException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws IllegalArgumentException * @throws SecurityException */ @SuppressWarnings("unchecked") public static <T> T newInstance(TypeReference<T> typeRef) throws InstantiationException { if (typeRef == null) return null; Type type = typeRef.getType(); if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type).getGenericComponentType(); return (T) Array.newInstance((Class<?>) componentType, 0); } if (type instanceof ParameterizedType) { Type rawType = ((ParameterizedType) type).getRawType(); Class<?> clazz = (Class<?>) rawType; if (clazz.isInterface()) { if (List.class.isAssignableFrom(clazz)) return (T) Lists.newArrayList(); if (Map.class.isAssignableFrom(clazz)) return (T) Maps.newHashMap(); if (Set.class.isAssignableFrom(clazz)) return (T) Sets.newHashSet(); } try { return ((Class<T>) rawType).newInstance(); } catch (IllegalAccessException e) { } throw new InstantiationException("could not create instance, the default constructor of \"" + ((Class<T>) rawType).getName() + "()\" is not accessible ( or undefined )."); } if (type instanceof Class) return newInstance((Class<T>) type); return null; }
From source file:org.lnicholls.galleon.gui.Galleon.java
private static void createAndShowGUI() { try {/*from w w w . ja v a 2s. c o m*/ System.setProperty("os.user.home", System.getProperty("user.home")); ArrayList errors = new ArrayList(); Server.setup(errors); log = Server.setupLog("org.lnicholls.galleon.gui.Galleon", "GuiTrace", "GuiFile", Constants.GUI_LOG_FILE); // log = Logger.getLogger(Galleon.class.getName()); printSystemProperties(); UIManager.put("ClassLoader", (com.jgoodies.plaf.LookUtils.class).getClassLoader()); UIManager.put("Application.useSystemFontSettings", Boolean.TRUE); Options.setGlobalFontSizeHints(FontSizeHints.MIXED2); Options.setDefaultIconSize(new Dimension(18, 18)); try { UIManager.setLookAndFeel( LookUtils.IS_OS_WINDOWS_XP ? "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel" : Options.getSystemLookAndFeelClassName()); } catch (Exception e) { Tools.logException(Galleon.class, e); } /* * mServerConfiguration = new ServerConfiguration(); if * (mConfigureDir != null) { log.info("Configuration Dir=" + * mConfigureDir.getAbsolutePath()); new * Configurator(mServerConfiguration).load(mAppManager, * mConfigureDir); } else new * Configurator(mServerConfiguration).load(mAppManager); mAddress = * mServerConfiguration.getIPAddress(); if (mAddress == null || * mAddress.length() == 0) mAddress = "127.0.0.1"; */ log.info("Server address: " + mServerAddress); for (int i = 0; i < 100; i++) { try { mRegistry = LocateRegistry.getRegistry(mServerAddress, 1099 + i); String[] names = mRegistry.list(); ServerControl serverControl = (ServerControl) mRegistry.lookup("serverControl"); log.info("Found server at: " + mServerAddress + " on " + (1099 + i)); break; } catch (Throwable ex) { if (log.isDebugEnabled()) Tools.logException(Galleon.class, ex); } } File directory = new File(System.getProperty("apps")); if (!directory.exists() || !directory.isDirectory()) { String message = "App Class Loader directory not found: " + System.getProperty("apps"); InstantiationException exception = new InstantiationException(message); log.error(message, exception); throw exception; } File[] files = directory.listFiles(new FileFilter() { public final boolean accept(File file) { return !file.isDirectory() && !file.isHidden() && file.getName().toLowerCase().endsWith(".jar"); } }); ArrayList urls = new ArrayList(); for (int i = 0; i < files.length; ++i) { try { URL url = files[i].toURI().toURL(); urls.add(url); log.debug(url); } catch (Exception ex) { // should never happen } } directory = new File(System.getProperty("hme")); if (directory.exists()) { files = directory.listFiles(new FileFilter() { public final boolean accept(File file) { return !file.isDirectory() && !file.isHidden() && file.getName().toLowerCase().endsWith(".jar"); } }); for (int i = 0; i < files.length; ++i) { try { URL url = files[i].toURI().toURL(); urls.add(url); log.debug(url); } catch (Exception ex) { // should never happen } } } File currentDirectory = new File("."); directory = new File(currentDirectory.getAbsolutePath() + "/../lib"); // TODO Handle reloading; what if list changes? files = directory.listFiles(new FileFilter() { public final boolean accept(File file) { return !file.isDirectory() && !file.isHidden() && file.getName().toLowerCase().endsWith(".jar"); } }); for (int i = 0; i < files.length; ++i) { try { URL url = files[i].toURI().toURL(); urls.add(url); log.debug(url); } catch (Exception ex) { // should never happen } } URLClassLoader classLoader = new URLClassLoader((URL[]) urls.toArray(new URL[0])); Thread.currentThread().setContextClassLoader(classLoader); mMainFrame = new MainFrame(Tools.getVersion()); splashWindow.setVisible(false); mMainFrame.setVisible(true); /* * javax.swing.SwingUtilities.invokeLater(new Runnable() { public * void run() { mToGo.getRecordings(); } }); */ if (!isCurrentVersion()) { if (JOptionPane.showConfirmDialog(mMainFrame, "A new version of Galleon is available. Do you want to download the latest version?", "New Version", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { try { BrowserLauncher.openURL("http://galleon.tv"); } catch (Exception ex) { Tools.logException(Galleon.class, ex); } } } } catch (Exception ex) { Tools.logException(Galleon.class, ex); System.exit(0); } }
From source file:ORG.oclc.os.SRW.ParallelSearching.SRWRemoteDatabase.java
public QueryResult getQueryResult(String query, SearchRetrieveRequestType request) throws InstantiationException { long startTime = System.currentTimeMillis(); String urlStr = url + "&operation=searchRetrieve&query=" + Utilities.urlParameterEncode(query); NonNegativeInteger maxRecords = request.getMaximumRecords(); if (maxRecords != null) urlStr = urlStr + "&maximumRecords=" + maxRecords; NonNegativeInteger startRecord = request.getStartRecord(); if (startRecord != null) urlStr = urlStr + "&startRecord=" + startRecord; String schema = request.getRecordSchema(); if (schema != null) urlStr = urlStr + "&recordSchema=" + schema; NonNegativeInteger resultSetTTL = request.getResultSetTTL(); if (resultSetTTL != null) urlStr = urlStr + "&resultSetTTL=" + resultSetTTL; String sortKeys = request.getSortKeys(); if (sortKeys != null) urlStr = urlStr + "&sortKeys=" + Utilities.urlParameterEncode(sortKeys); Hashtable extraRequestDataElements = parseElements(request.getExtraRequestData()); String s = (String) extraRequestDataElements.get("restrictorSummary"); if (s != null && !s.equals("false")) { // restrictorSummary=true; urlStr = urlStr + "&x-info-5-restrictorSummary"; log.info("turned restrictorSummary on"); }// ww w . j av a 2 s. c o m s = (String) extraRequestDataElements.get("returnSortKeys"); if (s != null && !s.equals("false")) { // returnSortKeys=true; urlStr = urlStr + "&x-info-5-returnSortKeys"; log.info("turned returnSortKeys on"); } log.info("urlStr=" + urlStr + "; " + System.currentTimeMillis()); try { RemoteQueryResult rqr = new RemoteQueryResult(url, getRemoteResponse(urlStr)); log.info("search " + query + ": " + (System.currentTimeMillis() - startTime) + "ms"); return rqr; } catch (CharConversionException e) { log.error(e, e); throw new InstantiationException(e.getMessage()); } catch (EOFException e) { log.error(e, e); throw new InstantiationException(e.getMessage()); } catch (IOException e) { log.error(e, e); throw new InstantiationException(e.getMessage()); } // if(recordPacking==null) { // MessageContext msgContext=MessageContext.getCurrentContext(); // if(msgContext!=null && msgContext.getProperty("sru")!=null) // recordPacking="xml"; // default for sru // else // recordPacking="string"; // default for srw // } // log.info("calling getNextSearchRetrieveResponse"+"; "+System.currentTimeMillis()); // SearchRetrieveResponseType response=searchHandler.getNextSearchRetrieveResponse(recordPacking); // log.info("exit doRequest"+"; "+System.currentTimeMillis()); // return response; }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
Provider setUpExplicitProvider(String securityProviderClassName) throws InstantiationException, ClassNotFoundException, IllegalAccessException { if (null == securityProviderClassName) { throw new InstantiationException(format("Security provider class name property (%s) set to null ", Config.SECURITY_PROVIDER_CLASS_NAME)); }/*from w ww. j av a2 s. co m*/ if (CryptoSuiteFactory.DEFAULT_JDK_PROVIDER.equals(securityProviderClassName)) { return null; } Class<?> aClass = Class.forName(securityProviderClassName); if (null == aClass) { throw new InstantiationException( format("Getting class for security provider %s returned null ", securityProviderClassName)); } if (!Provider.class.isAssignableFrom(aClass)) { throw new InstantiationException( format("Class for security provider %s is not a Java security provider", aClass.getName())); } Provider securityProvider = (Provider) aClass.newInstance(); if (securityProvider == null) { throw new InstantiationException( format("Creating instance of security %s returned null ", aClass.getName())); } return securityProvider; }
From source file:org.pentaho.osgi.legacy.LegacyPluginExtenderFactory.java
/** * Creates the object using a child-first classloader that uses local bundle bytecode first (so that it will be the * classloader for bundle classes created using this method which is necessary for correct loading of imports), the * bundleContext's classloader second, and the Kettle plugin's classloader third. * <p/>//w w w. j av a2 s. com * This allows bundles to implement interfaces known only to OSGi using classes only known to Ketle plugins (or vice * versa). * * @param className the classname to instantiate * @param arguments the arguments to use to instantiate the class * @return the instantiated class * @throws ClassNotFoundException * @throws InvocationTargetException * @throws InstantiationException * @throws KettlePluginException * @throws IllegalAccessException * @throws InterruptedException */ public Object create(String className, List<Object> arguments) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { Class<?> clazz = Class.forName(className, true, legacyBridgingClassloader); if (arguments == null || arguments.size() == 0) { return clazz.newInstance(); } for (Constructor<?> constructor : clazz.getConstructors()) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == arguments.size()) { boolean match = true; for (int i = 0; i < parameterTypes.length; i++) { Object o = arguments.get(i); if (o != null && !parameterTypes[i].isInstance(o)) { match = false; break; } } if (match) { return constructor.newInstance(arguments.toArray()); } } } throw new InstantiationException( "Unable to find constructor for class " + className + " with arguments " + arguments); }
From source file:de.dhbw_mannheim.cloudraid.dropbox.impl.net.connector.DropboxConnector.java
/** * This function initializes the {@link DropboxConnector} with the customer * and application tokens. During the {@link #connect()} process various * tokens are used. If {@link #connect()} returns <code>false</code>, this * class has to be re-instantiated and initialized with proper credentials. * </br>//ww w . ja va 2s. c om * * The {@link ICloudRAIDConfig} must contain following keys: * <ul> * <li><code>connector.ID.appKey</code></li> * <li><code>connector.ID.appSecret</code></li> * <li><i><code>connector.ID.accessTokenValue</code></i> (optional)</li> * <li><i><code>connector.ID.accessTokenSecret</code></i> (optional)</li> * </ul> * * @param connectorid * The internal id of this connector. * @param config * The reference to a running {@link ICloudRAIDConfig} service. * * @throws InstantiationException * Thrown if not all required parameters are passed. */ @Override public IStorageConnector create(int connectorid, ICloudRAIDConfig config) throws InstantiationException { this.id = connectorid; this.config = config; String kAccessTokenSecret = String.format("connector.%d.accessTokenSecret", this.id); String kAccessTokenValue = String.format("connector.%d.accessTokenValue", this.id); String kAppKey = String.format("connector.%d.appKey", this.id); String kAppSecret = String.format("connector.%d.appSecret", this.id); try { this.splitOutputDir = this.config.getString("split.output.dir"); if (this.config.keyExists(kAccessTokenSecret) && this.config.keyExists(kAccessTokenValue) && this.config.keyExists(kAppKey) && this.config.keyExists(kAppSecret)) { this.accessTokenSecret = this.config.getString(kAccessTokenSecret); this.accessTokenValue = this.config.getString(kAccessTokenValue); this.appKey = this.config.getString(kAppKey); this.appSecret = this.config.getString(kAppSecret); } else if (this.config.keyExists(kAppKey) && this.config.keyExists(kAppSecret)) { this.appKey = this.config.getString(kAppKey); this.appSecret = this.config.getString(kAppSecret); } else { throw new InstantiationException( "At least " + kAppKey + " and " + kAppSecret + " have to be set in the config. " + kAccessTokenValue + " and " + kAccessTokenSecret + " are optional!"); } } catch (MissingConfigValueException e) { e.printStackTrace(); throw new InstantiationException(e.getMessage()); } return this; }
From source file:fitnesse.responders.ResponderFactory.java
private Responder lookupResponder(String responderKey) throws InstantiationException { Class<?> responderClass = getResponderClass(responderKey); if (responderClass != null) { try {//from w w w .j a v a 2 s . c o m return newResponderInstance(responderClass); } catch (Exception e) { LOG.log(Level.WARNING, "Unable to instantiate responder " + responderKey, e); throw new InstantiationException("Unable to instantiate responder " + responderKey); } } throw new InstantiationException("No responder for " + responderKey); }
From source file:org.dhatim.smooks.scripting.groovy.GroovyContentHandlerFactory.java
public ContentHandler create(SmooksResourceConfiguration configuration) throws SmooksConfigurationException, InstantiationException { try {/*from w w w. j a v a2 s . c o m*/ byte[] groovyScriptBytes = configuration.getBytes(); String groovyScript = new String(groovyScriptBytes, "UTF-8"); if (groovyScriptBytes == null) { throw new InstantiationException( "No resource specified in either the resource path or resource 'resdata'."); } Object groovyObject; GroovyClassLoader groovyClassLoader = new GroovyClassLoader(getClass().getClassLoader()); try { Class groovyClass = groovyClassLoader.parseClass(groovyScript); groovyObject = groovyClass.newInstance(); } catch (CompilationFailedException e) { logger.debug( "Failed to create Visitor class instance directly from script:\n==========================\n" + groovyScript + "\n==========================\n Will try applying Visitor template to script.", e); groovyObject = null; } if (!(groovyObject instanceof Visitor)) { groovyObject = createFromTemplate(groovyScript, configuration); } ContentHandler groovyResource = (ContentHandler) groovyObject; Configurator.configure(groovyResource, configuration); return groovyResource; } catch (Exception e) { throw new SmooksConfigurationException( "Error constructing class from Groovy script " + configuration.getResource(), e); } }
From source file:org.pentaho.reporting.engine.classic.core.metadata.DefaultElementMetaData.java
public ElementType create() throws InstantiationException { try {//from w ww. j a v a2s . c o m return elementType.newInstance(); } catch (IllegalAccessException e) { throw new InstantiationException( "Unable to instantiate " + elementType + ": IllegalAccessException caught"); } }
From source file:gda.data.scan.datawriter.NexusDataWriter.java
protected void setupProperties() throws InstantiationException { if (setupPropertiesDone) return;/*from w ww.j a v a 2s .c om*/ metadata = GDAMetadataProvider.getInstance(); try { beamline = metadata.getMetadataValue("instrument", "gda.instrument", null); } catch (DeviceException e1) { } // If the beamline name isn't set then default to 'base'. if (beamline == null) { // If the beamline name is not set then use 'base' beamline = "base"; } // Check to see if we want to use a different NeXus backend format. defaultNeXusBackend = LocalProperties.get(GDA_DATA_NEXUS_BACKEND); if (defaultNeXusBackend == null) { defaultNeXusBackend = NexusGlobals.GDA_NX_DEFAULT; } // Check to see if the data directory has been defined. dataDir = PathConstructor.createFromDefaultProperty(); if (dataDir == null) { // this java property is compulsory - stop the scan throw new InstantiationException("cannot work out data directory - cannot create a new data file."); } if (beforeScanMetaData == null) { String metaDataProviderName = LocalProperties.get(GDA_NEXUS_METADATAPROVIDER_NAME); if (StringUtils.hasLength(metaDataProviderName)) { NexusTreeAppender metaDataProvider = Finder.getInstance().find(metaDataProviderName); InterfaceProvider.getTerminalPrinter().print("Getting meta data before scan"); beforeScanMetaData = new NexusTreeNode("before_scan", NexusExtractor.NXCollectionClassName, null); metaDataProvider.appendToTopNode(beforeScanMetaData); } } setupPropertiesDone = true; }