protected static DeviceImpl importFromBEncodedMapStatic(DeviceManagerImpl manager, Map map) throws IOException { String impl = ImportExportUtils.importString(map, "_impl"); if (impl.startsWith(".")) { impl = MY_PACKAGE + impl; } try { Class<DeviceImpl> cla = (Class<DeviceImpl>) Class.forName(impl); Constructor<DeviceImpl> cons = cla.getDeclaredConstructor(DeviceManagerImpl.class, Map.class); cons.setAccessible(true); return (cons.newInstance(manager, map)); } catch (Throwable e) { Debug.out("Can't construct device for " + impl, e); throw (new IOException("Construction failed: " + Debug.getNestedExceptionMessage(e))); } }
private static Map<String, GenotypeLikelihoodsCalculationModel> getGenotypeLikelihoodsCalculationObject(Logger logger, UnifiedArgumentCollection UAC) { final Map<String, GenotypeLikelihoodsCalculationModel> glcm = new HashMap<String, GenotypeLikelihoodsCalculationModel>(); final List<Class<? extends GenotypeLikelihoodsCalculationModel>> glmClasses = new PluginManager<GenotypeLikelihoodsCalculationModel>( GenotypeLikelihoodsCalculationModel.class) .getPlugins(); for (int i = 0; i < glmClasses.size(); i++) { final Class<? extends GenotypeLikelihoodsCalculationModel> glmClass = glmClasses.get(i); final String key = glmClass .getSimpleName() .replaceAll("GenotypeLikelihoodsCalculationModel", "") .toUpperCase(); try { final Object args[] = new Object[] {UAC, logger}; final Constructor c = glmClass.getDeclaredConstructor(UnifiedArgumentCollection.class, Logger.class); glcm.put(key, (GenotypeLikelihoodsCalculationModel) c.newInstance(args)); } catch (Exception e) { throw new UserException( "The likelihoods model provided for the -glm argument (" + UAC.GLmodel + ") is not a valid option: " + e.getMessage()); } } return glcm; }
public static <T> Constructor<T> findConstructor(Class<T> cls, boolean canFixAccess) throws IllegalArgumentException { try { Constructor<T> ctor = cls.getDeclaredConstructor(); if (canFixAccess) { checkAndFixAccess(ctor); } else { // Has to be public... if (!Modifier.isPublic(ctor.getModifiers())) { throw new IllegalArgumentException( "Default constructor for " + cls.getName() + " is not accessible (non-public?): not allowed to try modify access via Reflection: can not instantiate type"); } } return ctor; } catch (NoSuchMethodException e) {; } catch (Exception e) { ClassUtil.unwrapAndThrowAsIAE( e, "Failed to find default constructor of class " + cls.getName() + ", problem: " + e.getMessage()); } return null; }
public boolean isConstructorAccessibleForDecoding(Class clazz) { try { Constructor constr = clazz.getDeclaredConstructor(null); return isWithin(constr.getModifiers(), decodingAccessScope.get(CONSTRUCTOR_SCOPE)); } catch (Exception e) { return false; } }
/** * @param cacheName Cache name. * @param key Key. * @return Data key. * @throws Exception In case of error. */ private Object key(String cacheName, int key) throws Exception { Class<?> cls = Class.forName(GridSpringDynamicCacheManager.class.getName() + "$DataKey"); Constructor<?> cons = cls.getDeclaredConstructor(String.class, Object.class); cons.setAccessible(true); return cons.newInstance(cacheName, key); }
/** * Find a constructor in the class for the argument types. This method converts any checked * exception in unchecked exception. * * @param cls the class whos constructor will be found. * @param types the types of the parameters of the constructor. * @return the constructor of the given class which has the given parameter types. */ public static Constructor safeGetConstructor(Class cls, Class[] types) { try { return cls.getDeclaredConstructor(types); } catch (Exception ex) { logger.error( "Error while trying to find constructor for class " + cls.getCanonicalName(), ex); throw new RuntimeException( "Error while trying to find constructor for class " + cls.getCanonicalName(), ex); } }
/** * create a plugin with the given type * * @param pluginType type of the plugin to create. * @return The plugin object if created; null otherwise. */ public PluginType createByType(Class<? extends PluginType> pluginType) { try { Constructor<? extends PluginType> noArgsConstructor = pluginType.getDeclaredConstructor((Class[]) null); noArgsConstructor.setAccessible(true); return noArgsConstructor.newInstance(); } catch (Exception e) { throw new DynamicClassResolutionException(pluginType, e); } }
public void process(File cFile) { try { String cName = ClassNameFinder.thisClass(BinaryFile.read(cFile)); if (!cName.contains("")) return; // Ignore unpackaged classes testClass = Class.forName(cName); } catch (Exception e) { throw new RuntimeException(e); } TestMethods testMethods = new TestMethods(); Method creator = null; Method cleanup = null; for (Method m : testClass.getDeclaredMethods()) { testMethods.addIfTestMethod(m); if (creator == null) creator = checkForCreatorMethod(m); if (cleanup == null) cleanup = checkForCleanupMethod(m); } if (testMethods.size() > 0) { if (creator == null) try { if (!Modifier.isPublic(testClass.getDeclaredConstructor().getModifiers())) { Print.print("Error: " + testClass + " default constructor must be public"); System.exit(1); } } catch (NoSuchMethodException e) { // Synthesized default constructor; OK } Print.print(testClass.getName()); } for (Method m : testMethods) { Print.printnb(" . " + m.getName() + " "); try { Object testObject = createTestObject(creator); boolean success = false; try { if (m.getReturnType().equals(boolean.class)) success = (Boolean) m.invoke(testObject); else { m.invoke(testObject); success = true; // If no assert fails } } catch (InvocationTargetException e) { // Actual exception is inside e: Print.print(e.getCause()); } Print.print(success ? "" : "(failed)"); testsRun++; if (!success) { failures++; failedTests.add(testClass.getName() + ": " + m.getName()); } if (cleanup != null) cleanup.invoke(testObject, testObject); } catch (Exception e) { throw new RuntimeException(e); } } }
private static <T> T getInstanceFromType(Class<T> targetClass) throws IllegalArgumentException { T instance; try { Constructor<? extends T> constructor; constructor = targetClass.getDeclaredConstructor(); constructor.setAccessible(true); instance = constructor.newInstance(); } catch (Exception e) { instance = DatabaseFileLookupTest.getInstanceFromNonDefaultConstructor(targetClass); } return instance; }
@Override public T create() { Class<T> concreteClass = type.getConcreteClass(); try { Constructor<T> declaredConstructor = concreteClass.getDeclaredConstructor(); declaredConstructor.setAccessible(true); return declaredConstructor.newInstance(); } catch (InvocationTargetException e) { throw UncheckedException.throwAsUncheckedException(e.getTargetException()); } catch (Exception e) { throw UncheckedException.throwAsUncheckedException(e); } }
private void hasOneInstantiatorDefinitionWithEmptyConstructorOnImpl( ClassMeta<?> classMeta, Class<?> impl) throws NoSuchMethodException { assertTrue(classMeta instanceof ArrayClassMeta); final List<InstantiatorDefinition> instantiatorDefinitions = classMeta.getInstantiatorDefinitions(); assertEquals(1, instantiatorDefinitions.size()); final ExecutableInstantiatorDefinition instantiatorDefinition = (ExecutableInstantiatorDefinition) instantiatorDefinitions.get(0); assertEquals(0, instantiatorDefinition.getParameters().length); assertEquals(impl.getDeclaredConstructor(), instantiatorDefinition.getExecutable()); }
@SuppressWarnings("unchecked") private static <T> Constructor<T> getConstructor(Class<T> type) { try { return type.getDeclaredConstructor(); } catch (NoSuchMethodException e) { // Ignore } Constructor[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new IllegalStateException("Class " + type + " should have a single public constructor"); } return constructors[0]; }
/** Set up reflection methods required by the loader */ @SuppressWarnings("unchecked") private boolean prepareLoader() { try { // addURL method is used by the class loader to mAddUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); mAddUrl.setAccessible(true); Formatter minecraftLogFormatter = null; try { Class<? extends Formatter> formatterClass = (Class<? extends Formatter>) Minecraft.class .getClassLoader() .loadClass( ModUtilities.getObfuscatedFieldName( "net.minecraft.src.ConsoleLogFormatter", "em")); Constructor<? extends Formatter> defaultConstructor = formatterClass.getDeclaredConstructor(); defaultConstructor.setAccessible(true); minecraftLogFormatter = defaultConstructor.newInstance(); } catch (Exception ex) { ConsoleLogManager.init(); minecraftLogFormatter = ConsoleLogManager.loggerLogManager.getHandlers()[0].getFormatter(); } logger.setUseParentHandlers(false); StreamHandler consoleHandler = new ConsoleHandler(); if (minecraftLogFormatter != null) consoleHandler.setFormatter(minecraftLogFormatter); logger.addHandler(consoleHandler); FileHandler logFileHandler = new FileHandler( new File(Minecraft.getMinecraftDir(), "LiteLoader.txt").getAbsolutePath()); if (minecraftLogFormatter != null) logFileHandler.setFormatter(minecraftLogFormatter); logger.addHandler(logFileHandler); } catch (Throwable th) { logger.log(Level.SEVERE, "Error initialising LiteLoader", th); return false; } return true; }
private static final Record getTypedObject(int type) { if (type < 0 || type > knownRecords.length) return unknownRecord.getObject(); if (knownRecords[type] != null) return knownRecords[type]; /* Construct the class name by putting the type before "Record". */ String s = Record.class.getPackage().getName() + "." + Type.string(type).replace('-', '_') + "Record"; try { Class c = Class.forName(s); Constructor m = c.getDeclaredConstructor(emptyClassArray); knownRecords[type] = (Record) m.newInstance(emptyObjectArray); } catch (ClassNotFoundException e) { /* This is normal; do nothing */ } catch (Exception e) { if (Options.check("verbose")) System.err.println(e); } if (knownRecords[type] == null) knownRecords[type] = unknownRecord.getObject(); return knownRecords[type]; }
/** * Create a {@code TcpClient.Spec} using the given implementation class. * * @param clientImpl The concrete implementation of {@link TcpClient} to instantiate. */ @SuppressWarnings({"unchecked", "rawtypes"}) public TcpClientSpec(@Nonnull Class<? extends TcpClient> clientImpl) { Assert.notNull(clientImpl, "TcpClient implementation class cannot be null."); try { this.clientImplConstructor = (Constructor<TcpClient<IN, OUT>>) clientImpl.getDeclaredConstructor( Environment.class, Reactor.class, InetSocketAddress.class, ClientSocketOptions.class, SslOptions.class, Codec.class, Collection.class); this.clientImplConstructor.setAccessible(true); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "No public constructor found that matches the signature of the one found in the TcpClient class."); } }
public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine().trim()); Object o; // Solution starts here if (num < 1 || num > Math.pow(2, 30)) throw new Exception(); Solution ob = new Solution(); Class<?> c = Class.forName("Solution$Private"); Constructor<?> constructor = c.getDeclaredConstructor(Solution.class); constructor.setAccessible(true); o = constructor.newInstance(ob); Method m = c.getDeclaredMethod("powerof2", new Class[] {int.class}); m.setAccessible(true); String ans = (String) m.invoke(o, num); System.out.println(num + " is " + ans); // ends here System.out.println( "An instance of class: " + o.getClass().getSimpleName() + " has been created"); } // end of main
/** * Checks if a class fulfills the JavaBeans contract. * * @param cls the class to check */ public static void checkJavaBean(Class<?> cls) { try { Constructor<?> constructor = cls.getDeclaredConstructor(); int classModifiers = cls.getModifiers(); if (Modifier.isInterface(classModifiers)) throw new RuntimeException(cls.getName() + " is an interface"); if (Modifier.isAbstract(classModifiers)) throw new RuntimeException( cls.getName() + " cannot be instantiated - it is an abstract class"); int modifiers = constructor.getModifiers(); if (!Modifier.isPublic(modifiers)) throw new RuntimeException("No public default constructor in " + cls); } catch (NoSuchMethodException e) { throw new RuntimeException("No default constructor in class " + cls); } catch (SecurityException e) { logger.error( "I am not allowed to check the class by using reflection, " + "so I just can hope the class is alright and go on: ", e); } }
@SuppressWarnings("unchecked") LDAPObjectHandler(final Class<T> type) throws LDAPPersistException { this.type = type; final Class<? super T> superclassType = type.getSuperclass(); if (superclassType == null) { superclassHandler = null; } else { final LDAPObject superclassAnnotation = superclassType.getAnnotation(LDAPObject.class); if (superclassAnnotation == null) { superclassHandler = null; } else { superclassHandler = new LDAPObjectHandler(superclassType); } } final TreeMap<String, FieldInfo> fields = new TreeMap<String, FieldInfo>(); final TreeMap<String, GetterInfo> getters = new TreeMap<String, GetterInfo>(); final TreeMap<String, SetterInfo> setters = new TreeMap<String, SetterInfo>(); ldapObject = type.getAnnotation(LDAPObject.class); if (ldapObject == null) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_OBJECT_NOT_ANNOTATED.get(type.getName())); } final LinkedHashMap<String, String> objectClasses = new LinkedHashMap<String, String>(10); final String oc = ldapObject.structuralClass(); if (oc.length() == 0) { structuralClass = getUnqualifiedClassName(type); } else { structuralClass = oc; } final StringBuilder invalidReason = new StringBuilder(); if (PersistUtils.isValidLDAPName(structuralClass, invalidReason)) { objectClasses.put(toLowerCase(structuralClass), structuralClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_STRUCTURAL_CLASS.get( type.getName(), structuralClass, invalidReason.toString())); } auxiliaryClasses = ldapObject.auxiliaryClass(); for (final String auxiliaryClass : auxiliaryClasses) { if (PersistUtils.isValidLDAPName(auxiliaryClass, invalidReason)) { objectClasses.put(toLowerCase(auxiliaryClass), auxiliaryClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_AUXILIARY_CLASS.get( type.getName(), auxiliaryClass, invalidReason.toString())); } } superiorClasses = ldapObject.superiorClass(); for (final String superiorClass : superiorClasses) { if (PersistUtils.isValidLDAPName(superiorClass, invalidReason)) { objectClasses.put(toLowerCase(superiorClass), superiorClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_SUPERIOR_CLASS.get( type.getName(), superiorClass, invalidReason.toString())); } } if (superclassHandler != null) { for (final String s : superclassHandler.objectClassAttribute.getValues()) { objectClasses.put(toLowerCase(s), s); } } objectClassAttribute = new Attribute("objectClass", objectClasses.values()); final String parentDNStr = ldapObject.defaultParentDN(); try { defaultParentDN = new DN(parentDNStr); } catch (LDAPException le) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_DEFAULT_PARENT.get( type.getName(), parentDNStr, le.getMessage()), le); } final String postDecodeMethodName = ldapObject.postDecodeMethod(); if (postDecodeMethodName.length() > 0) { try { postDecodeMethod = type.getDeclaredMethod(postDecodeMethodName); postDecodeMethod.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_POST_DECODE_METHOD.get( type.getName(), postDecodeMethodName, getExceptionMessage(e)), e); } } else { postDecodeMethod = null; } final String postEncodeMethodName = ldapObject.postEncodeMethod(); if (postEncodeMethodName.length() > 0) { try { postEncodeMethod = type.getDeclaredMethod(postEncodeMethodName, Entry.class); postEncodeMethod.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_POST_ENCODE_METHOD.get( type.getName(), postEncodeMethodName, getExceptionMessage(e)), e); } } else { postEncodeMethod = null; } try { constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_NO_DEFAULT_CONSTRUCTOR.get(type.getName()), e); } Field tmpDNField = null; Field tmpEntryField = null; final LinkedList<FieldInfo> tmpRFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpAAFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpCAFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpRDNFields = new LinkedList<FieldInfo>(); for (final Field f : type.getDeclaredFields()) { final LDAPField fieldAnnotation = f.getAnnotation(LDAPField.class); final LDAPDNField dnFieldAnnotation = f.getAnnotation(LDAPDNField.class); final LDAPEntryField entryFieldAnnotation = f.getAnnotation(LDAPEntryField.class); if (fieldAnnotation != null) { f.setAccessible(true); final FieldInfo fieldInfo = new FieldInfo(f, type); final String attrName = toLowerCase(fieldInfo.getAttributeName()); if (fields.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), fieldInfo.getAttributeName())); } else { fields.put(attrName, fieldInfo); } switch (fieldInfo.getFilterUsage()) { case REQUIRED: tmpRFilterFields.add(fieldInfo); break; case ALWAYS_ALLOWED: tmpAAFilterFields.add(fieldInfo); break; case CONDITIONALLY_ALLOWED: tmpCAFilterFields.add(fieldInfo); break; case EXCLUDED: default: break; } if (fieldInfo.includeInRDN()) { tmpRDNFields.add(fieldInfo); } } if (dnFieldAnnotation != null) { f.setAccessible(true); if (fieldAnnotation != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get( type.getName(), "LDAPField", "LDAPDNField", f.getName())); } if (tmpDNField != null) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_MULTIPLE_DN_FIELDS.get(type.getName())); } final int modifiers = f.getModifiers(); if (Modifier.isFinal(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_DN_FIELD_FINAL.get(f.getName(), type.getName())); } else if (Modifier.isStatic(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_DN_FIELD_STATIC.get(f.getName(), type.getName())); } final Class<?> fieldType = f.getType(); if (fieldType.equals(String.class)) { tmpDNField = f; } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_DN_FIELD_TYPE.get( type.getName(), f.getName(), fieldType.getName())); } } if (entryFieldAnnotation != null) { f.setAccessible(true); if (fieldAnnotation != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get( type.getName(), "LDAPField", "LDAPEntryField", f.getName())); } if (tmpEntryField != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_MULTIPLE_ENTRY_FIELDS.get(type.getName())); } final int modifiers = f.getModifiers(); if (Modifier.isFinal(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ENTRY_FIELD_FINAL.get(f.getName(), type.getName())); } else if (Modifier.isStatic(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ENTRY_FIELD_STATIC.get(f.getName(), type.getName())); } final Class<?> fieldType = f.getType(); if (fieldType.equals(ReadOnlyEntry.class)) { tmpEntryField = f; } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_ENTRY_FIELD_TYPE.get( type.getName(), f.getName(), fieldType.getName())); } } } dnField = tmpDNField; entryField = tmpEntryField; requiredFilterFields = Collections.unmodifiableList(tmpRFilterFields); alwaysAllowedFilterFields = Collections.unmodifiableList(tmpAAFilterFields); conditionallyAllowedFilterFields = Collections.unmodifiableList(tmpCAFilterFields); rdnFields = Collections.unmodifiableList(tmpRDNFields); final LinkedList<GetterInfo> tmpRFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpAAFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpCAFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpRDNGetters = new LinkedList<GetterInfo>(); for (final Method m : type.getDeclaredMethods()) { final LDAPGetter getter = m.getAnnotation(LDAPGetter.class); final LDAPSetter setter = m.getAnnotation(LDAPSetter.class); if (getter != null) { m.setAccessible(true); if (setter != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_METHOD_ANNOTATIONS.get( type.getName(), "LDAPGetter", "LDAPSetter", m.getName())); } final GetterInfo methodInfo = new GetterInfo(m, type); final String attrName = toLowerCase(methodInfo.getAttributeName()); if (fields.containsKey(attrName) || getters.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName())); } else { getters.put(attrName, methodInfo); } switch (methodInfo.getFilterUsage()) { case REQUIRED: tmpRFilterGetters.add(methodInfo); break; case ALWAYS_ALLOWED: tmpAAFilterGetters.add(methodInfo); break; case CONDITIONALLY_ALLOWED: tmpCAFilterGetters.add(methodInfo); break; case EXCLUDED: default: // No action required. break; } if (methodInfo.includeInRDN()) { tmpRDNGetters.add(methodInfo); } } if (setter != null) { m.setAccessible(true); final SetterInfo methodInfo = new SetterInfo(m, type); final String attrName = toLowerCase(methodInfo.getAttributeName()); if (fields.containsKey(attrName) || setters.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName())); } else { setters.put(attrName, methodInfo); } } } requiredFilterGetters = Collections.unmodifiableList(tmpRFilterGetters); alwaysAllowedFilterGetters = Collections.unmodifiableList(tmpAAFilterGetters); conditionallyAllowedFilterGetters = Collections.unmodifiableList(tmpCAFilterGetters); rdnGetters = Collections.unmodifiableList(tmpRDNGetters); if (rdnFields.isEmpty() && rdnGetters.isEmpty()) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_NO_RDN_DEFINED.get(type.getName())); } fieldMap = Collections.unmodifiableMap(fields); getterMap = Collections.unmodifiableMap(getters); setterMap = Collections.unmodifiableMap(setters); final TreeSet<String> attrSet = new TreeSet<String>(); final TreeSet<String> lazySet = new TreeSet<String>(); if (ldapObject.requestAllAttributes()) { attrSet.add("*"); attrSet.add("+"); } else { for (final FieldInfo i : fields.values()) { if (i.lazilyLoad()) { lazySet.add(i.getAttributeName()); } else { attrSet.add(i.getAttributeName()); } } for (final SetterInfo i : setters.values()) { attrSet.add(i.getAttributeName()); } } attributesToRequest = new String[attrSet.size()]; attrSet.toArray(attributesToRequest); lazilyLoadedAttributes = new String[lazySet.size()]; lazySet.toArray(lazilyLoadedAttributes); }
public Maven3ServerEmbedderImpl(MavenServerSettings settings) throws RemoteException { File mavenHome = settings.getMavenHome(); if (mavenHome != null) { System.setProperty("maven.home", mavenHome.getPath()); } myConsoleWrapper = new Maven3ServerConsoleLogger(); myConsoleWrapper.setThreshold(settings.getLoggingLevel()); ClassWorld classWorld = new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader()); MavenCli cli = new MavenCli(classWorld) { @Override protected void customizeContainer(PlexusContainer container) { ((DefaultPlexusContainer) container) .setLoggerManager( new BaseLoggerManager() { @Override protected Logger createLogger(String s) { return myConsoleWrapper; } }); } }; Class cliRequestClass; try { cliRequestClass = MavenCli.class.getClassLoader().loadClass("org.apache.maven.cli.MavenCli$CliRequest"); } catch (ClassNotFoundException e) { throw new RuntimeException("Class \"org.apache.maven.cli.MavenCli$CliRequest\" not found"); } Object cliRequest; try { String[] commandLineOptions = new String[settings.getUserProperties().size()]; int idx = 0; for (Map.Entry<Object, Object> each : settings.getUserProperties().entrySet()) { commandLineOptions[idx++] = "-D" + each.getKey() + "=" + each.getValue(); } Constructor constructor = cliRequestClass.getDeclaredConstructor(String[].class, ClassWorld.class); constructor.setAccessible(true); cliRequest = constructor.newInstance(commandLineOptions, classWorld); for (String each : new String[] {"initialize", "cli", "properties", "container"}) { Method m = MavenCli.class.getDeclaredMethod(each, cliRequestClass); m.setAccessible(true); m.invoke(cli, cliRequest); } } catch (InstantiationException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } // reset threshold myContainer = FieldAccessor.get(MavenCli.class, cli, "container"); myContainer.getLoggerManager().setThreshold(settings.getLoggingLevel()); mySystemProperties = FieldAccessor.<Properties>get(cliRequestClass, cliRequest, "systemProperties"); myMavenSettings = buildSettings( FieldAccessor.<SettingsBuilder>get(MavenCli.class, cli, "settingsBuilder"), settings, mySystemProperties, FieldAccessor.<Properties>get(cliRequestClass, cliRequest, "userProperties")); myLocalRepository = createLocalRepository(settings.getSnapshotUpdatePolicy()); }
/** * Instantiate a new {@link ADDFFunctionalGroupHandler} given its class name * * @param theInterface * @return * @throws ClassNotFoundException * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InstantiationException */ @SuppressWarnings("unchecked") protected <I> I newHandler(Class<I> theInterface) { if (theInterface == null) return null; String className = null; try { className = Config.getValueWithGlobalDefault(this.getEngine(), theInterface.getSimpleName()); mLog.info(">>> className = " + className); if (Strings.isNullOrEmpty(className)) { mLog.error( String.format( "Cannot determine classname for %s from configuration source [%s] %s", theInterface.getSimpleName(), Config.getConfigHandler().getSource(), this.getEngine())); return null; } Class<?> clazz = Class.forName(className); if (Modifier.isAbstract(clazz.getModifiers())) { throw new InstantiationError( String.format("Class %s is abstract and cannot be instantiated", className)); } Constructor<ADDFFunctionalGroupHandler> cons = (Constructor<ADDFFunctionalGroupHandler>) clazz.getDeclaredConstructor(new Class<?>[] {DDF.class}); if (cons != null) cons.setAccessible(true); return cons != null ? (I) cons.newInstance(this) : null; } catch (ClassNotFoundException cnfe) { mLog.error( String.format( "Cannot instantiate handler for [%s] %s/%s", this.getEngine(), theInterface.getSimpleName(), className), cnfe); } catch (NoSuchMethodException nsme) { mLog.error( String.format( "Cannot instantiate handler for [%s] %s/%s", this.getEngine(), theInterface.getSimpleName(), className), nsme); } catch (IllegalAccessException iae) { mLog.error( String.format( "Cannot instantiate handler for [%s] %s/%s", this.getEngine(), theInterface.getSimpleName(), className), iae); } catch (InstantiationException ie) { mLog.error( String.format( "Cannot instantiate handler for [%s] %s/%s", this.getEngine(), theInterface.getSimpleName(), className), ie); } catch (InvocationTargetException ite) { mLog.error( String.format( "Cannot instantiate handler for [%s] %s/%s", this.getEngine(), theInterface.getSimpleName(), className), ite); } return null; }
/** * according to .gwt.xml files generates a LinkedMap which has interfaces as keys array of * generators as values keys are sorted according order of <generate-with> elements in .gwt.xml * files * * @param context * @throws UnableToCompleteException */ private void fillUpGeneratorChainMap(TreeLogger logger, GeneratorContext context) throws UnableToCompleteException { GeneratorChain.customGenerators = new LinkedList<AbstractGenerator>(); GeneratorChain.replacers = new LinkedList<AbstractGenerator>(); GeneratorChain.thirdPartyGenerators = new LinkedHashMap<Generator, AbstractGenerator>(); ModuleDef moduleDef = ((CompilerContext) getPrivateField(context, "compilerContext")).getModule(); Rules rules = moduleDef.getRules(); Iterator<Rule> rulesIter = rules.iterator(); while (rulesIter.hasNext()) { Rule rul = rulesIter.next(); Generator gen = null; // =================replace with if (rul instanceof RuleReplaceWith) { String replaceClass = (String) getPrivateField(rul, "replacementTypeName"); gen = new ReplaceByGenerator(replaceClass); // gen = null; // =================generate with } else if (rul instanceof RuleGenerateWith) { Class<? extends Generator> generatorClass = (Class<? extends Generator>) getPrivateField(rul, "generatorClass"); Constructor<?> constructor; try { constructor = generatorClass.getDeclaredConstructor(); } catch (Exception e) { logger.log( Type.ERROR, "Unable to obtain default constructor of generator " + generatorClass); throw new UnableToCompleteException(); } constructor.setAccessible(true); try { gen = (Generator) constructor.newInstance(); } catch (Exception e) { logger.log(Type.ERROR, "Unable to create instance of generator " + generatorClass); throw new UnableToCompleteException(); } } if (gen != null) { if (gen instanceof AbstractGenerator) { GenPredicGroup newGroup = null; AbstractGenerator myGen = (AbstractGenerator) gen; if (GeneratorChain.customGenerators.contains(gen) || GeneratorChain.replacers.contains(gen)) { newGroup = addPredicsToExisting(rul, myGen.getConditions()); myGen.setConditions(newGroup); } else { newGroup = getGroupConditions(rul.getRootCondition().getConditions(), null); myGen.setConditions(newGroup); if (gen instanceof ReplaceByGenerator) { GeneratorChain.replacers.addFirst(myGen); } else { GeneratorChain.customGenerators.addFirst(myGen); } } } else { if (GeneratorChain.thirdPartyGenerators.containsKey(gen)) { AbstractGenerator myGen = GeneratorChain.thirdPartyGenerators.get(gen); GenPredicGroup newGroup = addPredicsToExisting(rul, myGen.getConditions()); myGen.setConditions(newGroup); GeneratorChain.thirdPartyGenerators.put(gen, myGen); } else { AbstractGenerator myGen = new AbstractGenerator() { @Override public String doGenerate( TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { return null; } }; myGen.setConditions(getGroupConditions(rul.getRootCondition().getConditions(), null)); GeneratorChain.thirdPartyGenerators.put(gen, myGen); } } } } }