private void addControllerServlet(Class<?> klass) throws InstantiationException, IllegalAccessException { assert klass != null; ControllerServlet servlet = null; Controller controller; if (Controller.class.isAssignableFrom(klass)) { controller = controllerFactory.createController(klass.asSubclass(Controller.class)); } else { SimpleControllerWrapper.checkValidSimpleControllerClass(klass); SimpleControllerWrapper simpleController = SimpleControllerWrapper.createInstance(controllerFactory.createController(klass)); configure(simpleController); controller = simpleController; } URL url = klass.getAnnotation(URL.class); servlet = new ControllerServlet(controller); AllowedHttpMethods httpMethods = klass.getAnnotation(AllowedHttpMethods.class); if (httpMethods != null) { servlet.setValidHttpMethods(httpMethods.value()); } ControllerServlet.AfterControllerAction action = null; if (klass.isAnnotationPresent(ForwardTo.class)) { action = new ControllerServlet.ForwardAction(klass.getAnnotation(ForwardTo.class).value()); } else if (klass.isAnnotationPresent(RedirectTo.class)) { action = new ControllerServlet.ForwardAction(klass.getAnnotation(RedirectTo.class).value()); } servlet.setAfterControllerAction(action); ServletRegistration.Dynamic dynamic = context.addServlet(klass.getSimpleName(), servlet); dynamic.addMapping(url.value()); }
/** * Calculates (with varying degree of error) the memory used by a specific kind of object. It is * best to call this method multiple times to get an accurate reading. * * @param <E> the type of object * @param factory the object factory * @return the amount of memory (in bytes) one instance of a class uses */ public static <E> long calculateMemoryUsage(ObjectFactory<E> factory) { @SuppressWarnings("unused") // creating the first unused object pulls the class definition into memory if it already hasn't // been. E handle = factory.createObject(); long mem0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long mem1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); handle = null; // basically force garbage collection to run System.runFinalization(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); mem0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); handle = factory.createObject(); System.runFinalization(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); mem1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); return mem1 - mem0; }
/** Empty constructor used by JAXB. */ public DomainSetType( final SpatialDomainType spatialDomain, final TimeSequenceType temporalDomain) { ObjectFactory factory = new ObjectFactory(); content = new ArrayList<JAXBElement<?>>(); if (spatialDomain != null) content.add(factory.createSpatialDomain(spatialDomain)); if (temporalDomain != null) content.add(factory.createTemporalDomain(temporalDomain)); }
private static Logger createLogger(ConfLogger confLog) { Logger logger = new Logger(confLog.getLogName()); logger.setLevel(confLog.getLevel()); Set<ConfHandler> handlerSet = confLog.getHandlers(); for (ConfHandler confHandler : handlerSet) { if (confHandler instanceof ConFileHandler) { ConFileHandler conFileHandler = (ConFileHandler) confHandler; Handler handler = ObjectFactory.getFileHandler(); FileHandler fileHandler = (FileHandler) handler; fileHandler.setName(conFileHandler.getName()); fileHandler.setFileName(conFileHandler.getFileName()); fileHandler.setFormater(conFileHandler.getFormate()); try { fileHandler.init(); } catch (IOException ex) { ex.printStackTrace(); } // to do: check it logger.addHandler(fileHandler); } else if (confHandler instanceof ConfHandler) { Handler handler = ObjectFactory.getConsoleHandler(); handler.setName(confHandler.getName()); logger.addHandler(handler); } } return logger; }
/** * Creates an object for the given URL scheme id using the supplied urlInfo. * * <p>If urlInfo is null, the result is a context for resolving URLs with the scheme id 'scheme'. * If urlInfo is a URL, the result is a context named by the URL. Names passed to this context is * assumed to be relative to this context (i.e. not a URL). For example, if urlInfo is * "ldap://ldap.wiz.com/o=Wiz,c=us", the resulting context will be that pointed to by "o=Wiz,c=us" * on the server 'ldap.wiz.com'. Subsequent names that can be passed to this context will be LDAP * names relative to this context (e.g. cn="Barbs Jensen"). If urlInfo is an array of URLs, the * URLs are assumed to be equivalent in terms of the context to which they refer. The resulting * context is like that of the single URL case. If urlInfo is of any other type, that is handled * by the context factory for the URL scheme. * * @param scheme the URL scheme id for the context * @param urlInfo information used to create the context * @param name name of this object relative to <code>nameCtx</code> * @param nameCtx Context whose provider resource file will be searched for package prefix values * (or null if none) * @param environment Environment properties for creating the context * @see javax.naming.InitialContext */ private static Object getURLObject( String scheme, Object urlInfo, Name name, Context nameCtx, Hashtable<?, ?> environment) throws NamingException { // e.g. "ftpURLContextFactory" ObjectFactory factory = (ObjectFactory) ResourceManager.getFactory( Context.URL_PKG_PREFIXES, environment, nameCtx, "." + scheme + "." + scheme + "URLContextFactory", defaultPkgPrefix); if (factory == null) return null; // Found object factory try { return factory.getObjectInstance(urlInfo, name, nameCtx, environment); } catch (NamingException e) { throw e; } catch (Exception e) { NamingException ne = new NamingException(); ne.setRootCause(e); throw ne; } }
/** * Private worker method to attempt to use org.apache.env.Which. * * @param myContext an <code>ExpressionContext</code> passed in by the extension mechanism. This * must be an XPathContext. * @param factoryDocument providing createElement services, etc. * @return a Node with environment info; null if any error */ private static Node checkEnvironmentUsingWhich( ExpressionContext myContext, Document factoryDocument) { final String WHICH_CLASSNAME = "org.apache.env.Which"; final String WHICH_METHODNAME = "which"; final Class WHICH_METHOD_ARGS[] = { java.util.Hashtable.class, java.lang.String.class, java.lang.String.class }; try { // Use reflection to try to find xml-commons utility 'Which' Class clazz = ObjectFactory.findProviderClass(WHICH_CLASSNAME, ObjectFactory.findClassLoader(), true); if (null == clazz) return null; // Fully qualify names since this is the only method they're used in java.lang.reflect.Method method = clazz.getMethod(WHICH_METHODNAME, WHICH_METHOD_ARGS); Hashtable report = new Hashtable(); // Call the method with our Hashtable, common options, and ignore return value Object[] methodArgs = {report, "XmlCommons;Xalan;Xerces;Crimson;Ant", ""}; Object returnValue = method.invoke(null, methodArgs); // Create a parent to hold the report and append hash to it Node resultNode = factoryDocument.createElement("checkEnvironmentExtension"); org.apache.xml.utils.Hashtree2Node.appendHashToNode( report, "whichReport", resultNode, factoryDocument); return resultNode; } catch (Throwable t) { // Simply return null; no need to report error return null; } }
public static MESSAGE createFiletransfer( List<String> receivers, byte[] data, Map<String, String> parameters) { ObjectFactory objectFactory = new ObjectFactory(); MESSAGE request = objectFactory.createMESSAGE(); request.setParameters(objectFactory.createMESSAGEParameters()); request.setReceivers(objectFactory.createMESSAGEReceivers()); request.setType(REQUEST); request.setName(Request.FILETRANSFER); if (data != null) { request.setData(data); } if (receivers != null) { for (String receiver : receivers) { request.getReceivers().getReceiver().add(receiver); } } if (parameters != null) { Set<String> paramKeys = parameters.keySet(); for (String key : paramKeys) { MESSAGE.Parameters.Parameter msgParamter = objectFactory.createMESSAGEParametersParameter(); msgParamter.setName(key); msgParamter.setValue(parameters.get(key)); request.getParameters().getParameter().add(msgParamter); } } return request; }
/** * Returns a vector with all constructors named <code>_fname</code> after stripping its namespace * or <code>null</code> if no such methods exist. */ private Vector findConstructors() { Vector result = null; final String namespace = _fname.getNamespace(); final int nArgs = _arguments.size(); try { if (_clazz == null) { _clazz = ObjectFactory.findProviderClass(_className, ObjectFactory.findClassLoader(), true); if (_clazz == null) { final ErrorMsg msg = new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR, _className); getParser().reportError(Constants.ERROR, msg); } } final Constructor[] constructors = _clazz.getConstructors(); for (int i = 0; i < constructors.length; i++) { final int mods = constructors[i].getModifiers(); // Is it public, static and same number of args ? if (Modifier.isPublic(mods) && constructors[i].getParameterTypes().length == nArgs) { if (result == null) { result = new Vector(); } result.addElement(constructors[i]); } } } catch (ClassNotFoundException e) { final ErrorMsg msg = new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR, _className); getParser().reportError(Constants.ERROR, msg); } return result; }
@RubyLevelMethod(name = "open") public static RubyValue open(RubyValue receiver, RubyArray args, RubyBlock block) { String filename = args.get(0).toStr(); RubyIO io; if (args.size() <= 1) { io = ObjectFactory.createFile(filename, "r"); } else if (args.get(1) instanceof RubyFixnum) { String mode = "r"; int i = args.get(1).toInt(); if ((i & RDWR) != 0) { mode = mode + "w"; } io = ObjectFactory.createFile(filename, mode); } else { RubyString mode = (RubyString) args.get(1); io = ObjectFactory.createFile(filename, mode.toString()); } if (null == block) { return io; } else { RubyValue v = block.invoke(receiver, io); io.close(); return v; } }
public static MESSAGE createCommand(String name, Map<String, String> parameters) { ObjectFactory objectFactory = new ObjectFactory(); MESSAGE request = objectFactory.createMESSAGE(); request.setParameters(objectFactory.createMESSAGEParameters()); request.setReceivers(objectFactory.createMESSAGEReceivers()); request.setType(COMMAND); if (name != null) { request.setName(name); } // if (receivers != null) { // for (String receiver : receivers) { // request.getReceivers().getReceiver().add(receiver); // } // } if (parameters != null) { Set<String> paramKeys = parameters.keySet(); for (String key : paramKeys) { MESSAGE.Parameters.Parameter msgParamter = objectFactory.createMESSAGEParametersParameter(); msgParamter.setName(key); msgParamter.setValue(parameters.get(key)); request.getParameters().getParameter().add(msgParamter); } } return request; }
@Test public void shouldRetrieveAdminToken() throws IOException, JAXBException { JAXBContext coreJaxbContext = JAXBContext.newInstance( org.openstack.docs.identity.api.v2.ObjectFactory.class, com.rackspace.docs.identity.api.ext.rax_auth.v1.ObjectFactory.class); ByteArrayOutputStream baos = new ByteArrayOutputStream(); AuthenticateResponse response = getServiceResponse(); ObjectFactory factory = new ObjectFactory(); Marshaller marshaller = coreJaxbContext.createMarshaller(); marshaller.marshal(factory.createAccess(response), baos); baos.flush(); baos.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); ServiceClientResponse resp = new ServiceClientResponse(200, is); when(client.post( anyString(), anyString(), anyMapOf(String.class, String.class), anyString(), eq(MediaType.APPLICATION_XML_TYPE))) .thenReturn(resp); provider = new AdminTokenProvider(client, "authUrl", "user", "pass"); String adminToken = provider.getAdminToken(); assertTrue(adminToken.equals("tokenid")); }
protected RubyValue doStep(RubyValue toArg, RubyValue stepArg, RubyBlock block) { if ((toArg instanceof RubyFixnum) && (stepArg instanceof RubyFixnum)) { int i = this.value_; int end = ((RubyFixnum) toArg).value_; int diff = ((RubyFixnum) stepArg).value_; if (diff > 0) { while (i <= end) { RubyValue v = block.invoke(this, ObjectFactory.createFixnum(i)); if (block.breakedOrReturned()) { return v; } i += diff; } } else { while (i >= end) { RubyValue v = block.invoke(this, ObjectFactory.createFixnum(i)); if (block.breakedOrReturned()) { return v; } i += diff; } } return this; } return super.doStep(toArg, stepArg, block); }
public void testSingletonCreation() { final ObjectFactory objectFactory = LibBaseBoot.getInstance().getObjectFactory(); final ObjectFactorySingleton objectFactorySingleton1 = objectFactory.get(ObjectFactorySingleton.class); final ObjectFactorySingleton objectFactorySingleton2 = objectFactory.get(ObjectFactorySingleton.class); assertTrue(objectFactorySingleton1 == objectFactorySingleton2); }
public static void addContentAt(MESSAGE message, String name, byte[] data, int position) { ObjectFactory objectFactory = new ObjectFactory(); MESSAGE.Contents.Content content = objectFactory.createMESSAGEContentsContent(); content.setName(name); content.setValue(data); message.getContents().getContent().add(position, content); }
public static void addParameterAt(MESSAGE message, String name, String parameter, int position) { ObjectFactory objectFactory = new ObjectFactory(); MESSAGE.Parameters.Parameter msgParamter = objectFactory.createMESSAGEParametersParameter(); msgParamter.setName(name); msgParamter.setValue(parameter); message.getParameters().getParameter().add(position, msgParamter); }
/** Loads a single Object or converts the literal into an Object. */ public Object getObject(Value value) throws RepositoryException { assert value != null; if (value instanceof Literal) return of.createObject((Literal) value); Resource resource = (Resource) value; RDFObject cached = cached(resource); if (cached != null) return cached; return cache(of.createObject(resource, types.getTypes(resource))); }
private boolean isEntity(Class<?> type) { if (type == null) return false; for (Class<?> face : type.getInterfaces()) { if (of.isNamedConcept(face)) return true; } if (of.isNamedConcept(type)) return true; return isEntity(type.getSuperclass()); }
private Source sendBean() throws Exception { System.out.println("**** sendBean ******"); SayHelloResponse resp = new SayHelloResponse(); resp.setReturn("WebSvcTest-Hello"); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectFactory factory = new ObjectFactory(); jaxbContext.createMarshaller().marshal(factory.createSayHelloResponse(resp), bout); return new StreamSource(new ByteArrayInputStream(bout.toByteArray())); }
/** build a new HTTP object. */ public HTTP(final RequestMethodType get, final RequestMethodType post) { ObjectFactory factory = new ObjectFactory(); this.getOrPost = new ArrayList<JAXBElement<RequestMethodType>>(); if (get != null) { this.getOrPost.add(factory.createHTTPGet(get)); } if (post != null) { this.getOrPost.add(factory.createHTTPPost(post)); } }
/** * Prints the memory used by an object. * * @param <E> the type of class * @param factory the object factory */ public static <E> void showMemoryUsage(ObjectFactory<E> factory) { long mem = calculateMemoryUsage(factory); System.out.println( factory.getClass().getName() + " produced " + factory.createObject().getClass().getName() + " which took " + mem + " bytes"); }
@RubyLevelMethod(name = ">") public RubyValue opGt(RubyValue v) { if (v instanceof RubyFixnum) { return ObjectFactory.createBoolean(this.value_ > ((RubyFixnum) v).value_); } else if (v instanceof RubyFloat) { return ObjectFactory.createBoolean(this.value_ > v.toFloat()); } return coerceRelop(RubyID.gtID, v); }
int doStuff(int number1, int number2) throws AddNumbersFault_Exception { if (number1 < 0 || number2 < 0) { ObjectFactory of = new ObjectFactory(); AddNumbersFault fb = of.createAddNumbersFault(); fb.setDetail("Negative numbers cant be added!"); fb.setMessage("Numbers: " + number1 + ", " + number2); throw new AddNumbersFault_Exception(fb.getMessage(), fb); } return number1 + number2; }
/** Build a new Binary comparison operator */ public BinaryComparisonOpType(final LiteralType literal, final PropertyNameType propertyName) { if (this.expression == null) { this.expression = new ArrayList<JAXBElement<?>>(); } if (propertyName != null) { this.expression.add(FACTORY.createPropertyName(propertyName)); } if (literal != null) { this.expression.add(FACTORY.createLiteral(literal)); } }
/** * Creates an instance of an object for the specified object and environment. * * <p>If an object factory builder has been installed, it is used to create a factory for creating * the object. Otherwise, the following rules are used to create the object: * * <ol> * <li>If <code>refInfo</code> is a <code>Reference</code> or <code>Referenceable</code> * containing a factory class name, use the named factory to create the object. Return * <code>refInfo</code> if the factory cannot be created. Under JDK 1.1, if the factory * class must be loaded from a location specified in the reference, a * <tt>SecurityManager</tt> must have been installed or the factory creation will fail. If * an exception is encountered while creating the factory, it is passed up to the caller. * <li>If <tt>refInfo</tt> is a <tt>Reference</tt> or <tt>Referenceable</tt> with no factory * class name, and the address or addresses are <tt>StringRefAddr</tt>s with address type * "URL", try the URL context factory corresponding to each URL's scheme id to create the * object (see <tt>getURLContext()</tt>). If that fails, continue to the next step. * <li>Use the object factories specified in the <tt>Context.OBJECT_FACTORIES</tt> property of * the environment, and of the provider resource file associated with <tt>nameCtx</tt>, in * that order. The value of this property is a colon-separated list of factory class names * that are tried in order, and the first one that succeeds in creating an object is the one * used. If none of the factories can be loaded, return <code>refInfo</code>. If an * exception is encountered while creating the object, the exception is passed up to the * caller. * </ol> * * <p>Service providers that implement the <tt>DirContext</tt> interface should use * <tt>DirectoryManager.getObjectInstance()</tt>, not this method. Service providers that * implement only the <tt>Context</tt> interface should use this method. * * <p>Note that an object factory (an object that implements the ObjectFactory interface) must be * public and must have a public constructor that accepts no arguments. * * <p>The <code>name</code> and <code>nameCtx</code> parameters may optionally be used to specify * the name of the object being created. <code>name</code> is the name of the object, relative to * context <code>nameCtx</code>. This information could be useful to the object factory or to the * object implementation. If there are several possible contexts from which the object could be * named -- as will often be the case -- it is up to the caller to select one. A good rule of * thumb is to select the "deepest" context available. If <code>nameCtx</code> is null, <code>name * </code> is relative to the default initial context. If no name is being specified, the <code> * name</code> parameter should be null. * * @param refInfo The possibly null object for which to create an object. * @param name The name of this object relative to <code>nameCtx</code>. Specifying a name is * optional; if it is omitted, <code>name</code> should be null. * @param nameCtx The context relative to which the <code>name</code> parameter is specified. If * null, <code>name</code> is relative to the default initial context. * @param environment The possibly null environment to be used in the creation of the object * factory and the object. * @return An object created using <code>refInfo</code>; or <code>refInfo</code> if an object * cannot be created using the algorithm described above. * @exception NamingException if a naming exception was encountered while attempting to get a URL * context, or if one of the factories accessed throws a NamingException. * @exception Exception if one of the factories accessed throws an exception, or if an error was * encountered while loading and instantiating the factory and object classes. A factory * should only throw an exception if it does not want other factories to be used in an attempt * to create an object. See ObjectFactory.getObjectInstance(). * @see #getURLContext * @see ObjectFactory * @see ObjectFactory#getObjectInstance */ public static Object getObjectInstance( Object refInfo, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { ObjectFactory factory; // Use builder if installed ObjectFactoryBuilder builder = getObjectFactoryBuilder(); if (builder != null) { // builder must return non-null factory factory = builder.createObjectFactory(refInfo, environment); return factory.getObjectInstance(refInfo, name, nameCtx, environment); } // Use reference if possible Reference ref = null; if (refInfo instanceof Reference) { ref = (Reference) refInfo; } else if (refInfo instanceof Referenceable) { ref = ((Referenceable) (refInfo)).getReference(); } Object answer; if (ref != null) { String f = ref.getFactoryClassName(); if (f != null) { // if reference identifies a factory, use exclusively factory = getObjectFactoryFromReference(ref, f); if (factory != null) { return factory.getObjectInstance(ref, name, nameCtx, environment); } // No factory found, so return original refInfo. // Will reach this point if factory class is not in // class path and reference does not contain a URL for it return refInfo; } else { // if reference has no factory, check for addresses // containing URLs answer = processURLAddrs(ref, name, nameCtx, environment); if (answer != null) { return answer; } } } // try using any specified factories answer = createObjectFromFactories(refInfo, name, nameCtx, environment); return (answer != null) ? answer : refInfo; }
@Override public void configure(Object o) throws Exception { Class<?> type = o.getClass(); Field[] fields = type.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Inject.class)) { ObjectFactory factory = ObjectFactory.getInstance(); Object object = factory.createObject(field.getType()); field.setAccessible(true); field.set(o, object); } } }
// @RubyLevelMethod(name="downcase") public RubyString downcase() { int length = this.sb_.length(); if (length == 0) { return ObjectFactory.createString(); } char[] ca = new char[length]; this.sb_.getChars(0, length, ca, 0); for (int i = 0; i < ca.length; i++) { ca[i] = Character.toLowerCase(ca[i]); } return ObjectFactory.createString(new StringBuffer().append(ca)); }
@SuppressWarnings("unchecked") public <T> T refresh(T object) throws RepositoryException { Resource resource = findResource(object); if (object instanceof Refreshable) { ((Refreshable) object).refresh(); } Set<URI> types = this.types.getTypes(resource); Class<?> proxy = of.getObjectClass(resource, types); RDFObject cached = cached(resource); if (cached != null && cached != object && cached instanceof Refreshable) { ((Refreshable) cached).refresh(); } if (cached != null && cached.getClass().equals(proxy)) return (T) cached; return (T) cache(of.createBean(resource, proxy)); }
static { SerializerFactory factory; String list; StringTokenizer token; String className; // The default factories are always registered first, // any factory specified in the properties file and supporting // the same method will override the default factory. factory = new SerializerFactoryImpl(Method.XML); registerSerializerFactory(factory); factory = new SerializerFactoryImpl(Method.HTML); registerSerializerFactory(factory); factory = new SerializerFactoryImpl(Method.XHTML); registerSerializerFactory(factory); factory = new SerializerFactoryImpl(Method.TEXT); registerSerializerFactory(factory); list = System.getProperty(FactoriesProperty); if (list != null) { token = new StringTokenizer(list, " ;,:"); while (token.hasMoreTokens()) { className = token.nextToken(); try { factory = (SerializerFactory) ObjectFactory.newInstance( className, SerializerFactory.class.getClassLoader(), true); if (_factories.containsKey(factory.getSupportedMethod())) _factories.put(factory.getSupportedMethod(), factory); } catch (Exception except) { } } } }
// @RubyLevelMethod(name="nitems") public RubyValue nitems() { int n = 0; for (int i = 0; i < size(); i++) { if (get(i) != RubyConstant.QNIL) n++; } return ObjectFactory.createFixnum(n); }
/** * Explicitly adds the types to the entity. * * @return the entity with new composed types */ public Object addDesignations(Object entity, URI... types) throws RepositoryException { if (entity instanceof RDFObjectBehaviour) { RDFObjectBehaviour support = (RDFObjectBehaviour) entity; Object delegate = support.getBehaviourDelegate(); if (delegate != entity) { return addDesignations(delegate, types); } } assert types != null && types.length > 0; Resource resource = findResource(entity); Set<URI> list = new HashSet<URI>(4); getTypes(entity.getClass(), list); boolean autoCommit = isAutoCommit(); if (autoCommit) { setAutoCommit(false); } try { for (URI type : types) { this.types.addTypeStatement(resource, type); list.add(type); } if (autoCommit) { setAutoCommit(true); } } finally { if (autoCommit && !isAutoCommit()) { rollback(); setAutoCommit(true); } } return cache(of.createObject(resource, list)); }