private static void netxsurgery() throws Exception { /* Force off NetX codebase classloading. */ Class<?> nxc; try { nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader"); } catch (ClassNotFoundException e1) { try { nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader"); } catch (ClassNotFoundException e2) { throw (new Exception("No known NetX on classpath")); } } ClassLoader cl = MainFrame.class.getClassLoader(); if (!nxc.isInstance(cl)) { throw (new Exception("Not running from a NetX classloader")); } Field cblf, lf; try { cblf = nxc.getDeclaredField("codeBaseLoader"); lf = nxc.getDeclaredField("loaders"); } catch (NoSuchFieldException e) { throw (new Exception("JNLPClassLoader does not conform to its known structure")); } cblf.setAccessible(true); lf.setAccessible(true); Set<Object> loaders = new HashSet<Object>(); Stack<Object> open = new Stack<Object>(); open.push(cl); while (!open.empty()) { Object cur = open.pop(); if (loaders.contains(cur)) continue; loaders.add(cur); Object curl; try { curl = lf.get(cur); } catch (IllegalAccessException e) { throw (new Exception("Reflection accessibility not available even though set")); } for (int i = 0; i < Array.getLength(curl); i++) { Object other = Array.get(curl, i); if (nxc.isInstance(other)) open.push(other); } } for (Object cur : loaders) { try { cblf.set(cur, null); } catch (IllegalAccessException e) { throw (new Exception("Reflection accessibility not available even though set")); } } }
public <T extends Item> T getItem(Class<T> c) { for (int i = 0; i < items.length; i++) { if (c.isInstance(items[i])) return c.cast(items[i]); } return null; }
protected final AbstractAudioChunk findChunk(List<AbstractAudioChunk> chunks, Class c) { for (Iterator<AbstractAudioChunk> i = chunks.iterator(); i.hasNext(); ) { AbstractAudioChunk chunk = i.next(); if (c.isInstance(chunk)) return chunk; } return null; }
/** * Checks that FileChannel map throws one of the expected exceptions when invoked with the given * inputs. */ private static void checkException( FileChannel fc, MapMode mode, long position, long size, Class<?>... expected) throws IOException { Exception exc = null; try { fc.map(mode, position, size); } catch (Exception actual) { exc = actual; } if (exc != null) { for (Class<?> clazz : expected) { if (clazz.isInstance(exc)) { return; } } } System.err.println("Expected one of"); for (Class<?> clazz : expected) { System.out.println(clazz); } if (exc == null) { throw new RuntimeException("No expection thrown"); } else { throw new RuntimeException("Unexpected exception thrown", exc); } }
/** * Removes the property of the given type. * * @return The property that was just removed. * @since 1.279 */ public <T extends JobProperty> T removeProperty(Class<T> clazz) throws IOException { for (JobProperty<? super JobT> p : properties) { if (clazz.isInstance(p)) { removeProperty(p); return clazz.cast(p); } } return null; }
/** * Searches the current debug scope, bottom up, for a context object that is an instance of a * given type. The first such object found is returned. */ @SuppressWarnings("unchecked") public static <T> T contextLookup(Class<T> clazz) { if (ENABLED) { for (Object o : context()) { if (clazz.isInstance(o)) { return ((T) o); } } } return null; }
private void expect(Class<?> c) { if (!c.isInstance(stack.peek())) { throw new IllegalStateException( "Internal stack error: " + "Expected '" + c.getName() + "' found '" + stack.peek().getClass().getName() + "'"); } }
public static <E extends Exception> VirtualFileVisitor.Result visitChildrenRecursively( @NotNull VirtualFile file, @NotNull VirtualFileVisitor visitor, @NotNull Class<E> eClass) throws E { try { return visitChildrenRecursively(file, visitor); } catch (VisitorException e) { final Throwable cause = e.getCause(); if (eClass.isInstance(cause)) { throw eClass.cast(cause); } throw e; } }
/** * Convenience method for searching above the given component in the component hierarchy and * returns the first object of the given type it finds, or <code>null</code> if no such parent was * found. * * <p>The reason this method exists is for tidyness of the calling code, as no longer a explicit * cast is needed. * * @param aType the type of the parent to find, cannot be <code>null</code>; * @param aComponent the component to search in the hierarchy, cannot be <code>null</code>. * @return the requested ancestor, or <code>null</code> if not found. * @see SwingUtilities#getAncestorOfClass(Class, Component) */ @SuppressWarnings("unchecked") public static <T> T getAncestorOfClass(final Class<T> aType, final Component aComponent) { if ((aComponent == null) || (aType == null)) { return null; } Container parent = aComponent.getParent(); while ((parent != null) && !(aType.isInstance(parent))) { parent = parent.getParent(); } return (T) parent; }
public SOAPMessage get(Object endPoint) throws SOAPException { if (closed) { log.severe("SAAJ0011.p2p.get.already.closed.conn"); throw new SOAPExceptionImpl("Connection is closed"); } Class urlEndpointClass = null; try { urlEndpointClass = Class.forName("javax.xml.messaging.URLEndpoint"); } catch (Exception ex) { // Do nothing. URLEndpoint is available only when JAXM is there. } if (urlEndpointClass != null) { if (urlEndpointClass.isInstance(endPoint)) { String url = null; try { Method m = urlEndpointClass.getMethod("getURL", (Class[]) null); url = (String) m.invoke(endPoint, (Object[]) null); } catch (Exception ex) { log.severe("SAAJ0004.p2p.internal.err"); throw new SOAPExceptionImpl("Internal error: " + ex.getMessage()); } try { endPoint = new URL(url); } catch (MalformedURLException mex) { log.severe("SAAJ0005.p2p."); throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage()); } } } if (endPoint instanceof java.lang.String) { try { endPoint = new URL((String) endPoint); } catch (MalformedURLException mex) { log.severe("SAAJ0006.p2p.bad.URL"); throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage()); } } if (endPoint instanceof URL) try { SOAPMessage response = doGet((URL) endPoint); return response; } catch (Exception ex) { throw new SOAPExceptionImpl(ex); } else throw new SOAPExceptionImpl("Bad endPoint type " + endPoint); }
@SuppressWarnings("unchecked") public static <T> List<T> contextSnapshot(Class<T> clazz) { if (ENABLED) { List<T> result = new ArrayList<>(); for (Object o : context()) { if (clazz.isInstance(o)) { result.add((T) o); } } return result; } else { return Collections.emptyList(); } }
/** * Return the first fetch response item of the given class for the given message number. * * @param r the responses * @param msgno the message number * @param c the class * @param <T> the type of fetch item * @return the fetch item */ public static <T extends Item> T getItem(Response[] r, int msgno, Class<T> c) { if (r == null) return null; for (int i = 0; i < r.length; i++) { if (r[i] == null || !(r[i] instanceof FetchResponse) || ((FetchResponse) r[i]).getNumber() != msgno) continue; FetchResponse f = (FetchResponse) r[i]; for (int j = 0; j < f.items.length; j++) { if (c.isInstance(f.items[j])) return c.cast(f.items[j]); } } return null; }
/** * Return all fetch response items of the given class for the given message number. * * @param r the responses * @param msgno the message number * @param c the class * @param <T> the type of fetch items * @return the list of fetch items * @since JavaMail 1.5.2 */ public static <T extends Item> List<T> getItems(Response[] r, int msgno, Class<T> c) { List<T> items = new ArrayList<T>(); if (r == null) return items; for (int i = 0; i < r.length; i++) { if (r[i] == null || !(r[i] instanceof FetchResponse) || ((FetchResponse) r[i]).getNumber() != msgno) continue; FetchResponse f = (FetchResponse) r[i]; for (int j = 0; j < f.items.length; j++) { if (c.isInstance(f.items[j])) items.add(c.cast(f.items[j])); } } return items; }
private static boolean checkType( String what, Object object, Class wrongClass, boolean isException) { final String type = isException ? "exception" : "object"; final String rendered = isException ? "thrown" : "returned"; System.out.println("For " + type + " " + rendered + " by " + what + ":"); if (wrongClass.isInstance(object)) { System.out.println("TEST FAILS: " + type + " loaded by test " + "classloader"); return false; } String className = object.getClass().getName(); if (!className.equals(wrongClass.getName())) { System.out.println( "TEST FAILS: " + rendered + " " + type + " has wrong class name: " + className); return false; } System.out.println( "Test passes: " + rendered + " " + type + " has same class name but is not same class"); return true; }
public SOAPMessage call(SOAPMessage message, Object endPoint) throws SOAPException { if (closed) { log.severe("SAAJ0003.p2p.call.already.closed.conn"); throw new SOAPExceptionImpl("Connection is closed"); } Class urlEndpointClass = null; ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { if (loader != null) { urlEndpointClass = loader.loadClass(JAXM_URLENDPOINT); } else { urlEndpointClass = Class.forName(JAXM_URLENDPOINT); } } catch (ClassNotFoundException ex) { // Do nothing. URLEndpoint is available only when JAXM is there. log.finest("SAAJ0090.p2p.endpoint.available.only.for.JAXM"); } if (urlEndpointClass != null) { if (urlEndpointClass.isInstance(endPoint)) { String url = null; try { Method m = urlEndpointClass.getMethod("getURL", (Class[]) null); url = (String) m.invoke(endPoint, (Object[]) null); } catch (Exception ex) { // TBD -- exception chaining log.log(Level.SEVERE, "SAAJ0004.p2p.internal.err", ex); throw new SOAPExceptionImpl("Internal error: " + ex.getMessage()); } try { endPoint = new URL(url); } catch (MalformedURLException mex) { log.log(Level.SEVERE, "SAAJ0005.p2p.", mex); throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage()); } } } if (endPoint instanceof java.lang.String) { try { endPoint = new URL((String) endPoint); } catch (MalformedURLException mex) { log.log(Level.SEVERE, "SAAJ0006.p2p.bad.URL", mex); throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage()); } } if (endPoint instanceof URL) try { SOAPMessage response = post(message, (URL) endPoint); return response; } catch (Exception ex) { // TBD -- chaining? throw new SOAPExceptionImpl(ex); } else { log.severe("SAAJ0007.p2p.bad.endPoint.type"); throw new SOAPExceptionImpl("Bad endPoint type " + endPoint); } }
/** * Process and loop until told to stop. A callback_done will stop the loop and will return a * result. Otherwise null is returned. */ public Object run() throws CommandException { Object result = null; boolean shutdown = false; boolean closeWhenDone = true; Commands.ValueObject valueObject = new Commands.ValueObject(); // Working value object so not continually recreated. InvokableValueSender valueSender = new InvokableValueSender(); // Working valuesender so not continually recreated. try { boolean doLoop = true; /** * Note: In the cases below you will see a lot of finally clauses that null variables out. * This is because this is a long running loop, and variables declared within blocks are not * garbage collected until the method is terminated, so these variables once set would never * be GC'd. The nulling at the end of the case makes sure that any of those objects set are * now available for garbage collection when necessary. */ while (doLoop && isConnected()) { byte cmd = 0; try { if (LINUX_1_3) socket.setSoTimeout(1000); // Linux 1.3 bug, see comment on LINUX_1_3 cmd = in.readByte(); if (LINUX_1_3 && isConnected()) socket.setSoTimeout(0); // Linux 1.3 bug, see comment on LINUX_1_3 } catch (InterruptedIOException e) { continue; // Timeout, try again } switch (cmd) { case Commands.QUIT_CONNECTION: doLoop = false; break; // Close this connection case Commands.TERMINATE_SERVER: doLoop = false; shutdown = true; // Shutdown everything break; case Commands.GET_CLASS: String className = in.readUTF(); Class aClass = null; Class superClass = null; String superClassName = null; boolean added = false; try { aClass = Class.forName( className); // Turns out using JNI format for array type will work fine. added = server.getIdentityID(aClass, valueObject); boolean isInterface = aClass.isInterface(); boolean isAbstract = java.lang.reflect.Modifier.isAbstract(aClass.getModifiers()); superClass = aClass.getSuperclass(); superClassName = (superClass != null) ? superClass.getName() : ""; // $NON-NLS-1$ out.writeByte(Commands.GET_CLASS_RETURN); out.writeInt(valueObject.objectID); out.writeBoolean(isInterface); out.writeBoolean(isAbstract); out.writeUTF(superClassName); out.flush(); } catch (ClassNotFoundException e) { valueObject.set(); Commands.sendErrorCommand(out, Commands.GET_CLASS_NOT_FOUND, valueObject); } catch (ExceptionInInitializerError e) { sendException(e.getException(), valueObject, out); } catch (LinkageError e) { sendException(e, valueObject, out); } catch (Throwable e) { // Something bad, did we add a class? If we did remove it from the table. if (added) server.removeObject(server.getObject(valueObject.objectID)); throw e; } finally { // clear out for GC to work. className = null; aClass = null; superClass = null; superClassName = null; valueObject.set(); } break; case Commands.GET_CLASS_FROM_ID: int classID = in.readInt(); try { aClass = (Class) server.getObject(classID); boolean isInterface = aClass.isInterface(); boolean isAbstract = java.lang.reflect.Modifier.isAbstract(aClass.getModifiers()); superClass = aClass.getSuperclass(); superClassName = (superClass != null) ? superClass.getName() : ""; // $NON-NLS-1$ out.writeByte(Commands.GET_CLASS_ID_RETURN); out.writeUTF(aClass.getName()); out.writeBoolean(isInterface); out.writeBoolean(isAbstract); out.writeUTF(superClassName); out.flush(); } catch (ClassCastException e) { valueObject.set(); Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject); } finally { // clear out for GC to work. aClass = null; superClass = null; superClassName = null; valueObject.set(); } break; case Commands.GET_OBJECT_DATA: int objectID = in.readInt(); Object anObject = null; try { anObject = server.getObject(objectID); valueObject.setObjectID(objectID, server.getIdentityID(anObject.getClass())); Commands.writeValue(out, valueObject, true); } catch (ClassCastException e) { valueObject.set(); Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject); } finally { anObject = null; // Clear out for GC to work valueObject.set(); } break; case Commands.RELEASE_OBJECT: int id = in.readInt(); server.removeObject(server.getObject(id)); break; case Commands.NEW_INIT_STRING: classID = in.readInt(); // ID Of class to do new upon. String initString = in.readUTF(); // The init string. Object newValue = null; Class theClass = null; try { theClass = (Class) server.getObject(classID); if (theClass == null) { // The class wasn't found. So imply ClassNotFound exception. throw new ClassNotFoundException(); } InitializationStringParser parser = null; try { parser = InitializationStringParser.createParser(initString); newValue = parser.evaluate(); boolean primitive = parser.isPrimitive(); // If expected class is Void.TYPE, that means don't test the type of the result // to verify if correct type, just return what it really is. if (theClass != Void.TYPE && primitive != theClass.isPrimitive()) { valueObject.set(); Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject); continue; // Goto next command. } if (primitive) { try { // Need to do special tests for compatibility and assignment. sendObject( newValue, classID != Commands.VOID_TYPE ? classID : server.getIdentityID(parser.getExpectedType()), valueObject, out, true); // This will make sure it goes out as the correct primitive type } catch (ClassCastException e) { // The returned type is not of the correct type for what is expected. valueObject.set(); Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject); continue; // Goto next command } } else { if (newValue != null) { // Test to see if they are compatible. (Null can be assigned to any object, // so that is why it was tested out above). // If expected class is Void.TYPE, that means don't test the type of the result // to verify if correct type, just return what it really is. if (theClass != Void.TYPE && !theClass.isInstance(newValue)) { // The returned type is not of the correct type for what is expected. valueObject.set(); Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject); continue; // Goto next command } } sendObject( newValue, NOT_A_PRIMITIVE, valueObject, out, true); // Send out as an object. } } catch (InitializationStringEvaluationException e) { if (e instanceof EvaluationException) { // Want to return the real exception. sendException(e.getOriginalException(), valueObject, out); } else { // Couldn't be evaluated, return an error for this. setExceptionIntoValue(e.getOriginalException(), valueObject); Commands.sendErrorCommand(out, Commands.CANNOT_EVALUATE_STRING, valueObject); } } finally { parser = null; // Clear out for GC to work } } catch (Throwable e) { sendException(e, valueObject, out); } finally { // Clear out for GC to work initString = null; theClass = null; newValue = null; valueObject.set(); } break; case Commands.INVOKE: Object target = null; Object[] parms = null; Class returnType = null; java.lang.reflect.Method aMethod = null; try { int methodID = in.readInt(); // ID of method to invoke aMethod = (java.lang.reflect.Method) server.getObject(methodID); // Method to invoke Commands.readValue(in, valueObject); target = getInvokableObject(valueObject); Commands.readValue(in, valueObject); if (valueObject.type == Commands.ARRAY_IDS) { // It is an array containing IDs, as it normally would be. valueSender.initialize(valueObject); Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false); parms = (Object[]) valueSender.getArray(); } else { // It is all objects or null, so it should be an Object[] or null. If not, then this // is an error. parms = (Object[]) valueObject.anObject; } if (!aMethod.isAccessible()) aMethod.setAccessible( true); // We will allow all to occur. Let access control be handled by IDE and // compiler. newValue = aMethod.invoke(target, parms); returnType = aMethod.getReturnType(); if (returnType.isPrimitive()) { int returnTypeID = server.getIdentityID(returnType); // Need to tell sendObject the correct primitive type. sendObject(newValue, returnTypeID, valueObject, out, true); } else { sendObject( newValue, NOT_A_PRIMITIVE, valueObject, out, true); // Just send the object back. sendObject knows how to iterpret the type } } catch (CommandException e) { throw e; // Throw it again. These we don't want to come up as an exception proxy. // These should end the thread. } catch (java.lang.reflect.InvocationTargetException e) { // This is a wrappered exception. Return the wrappered one so it looks like // it was the real one. (Sometimes the method being invoked is on a // java.lang.reflect.Constructor.newInstance, // which in turn is an InvocationTargetException, so we will go until we don't have an // InvocationTargetException. Throwable t = e; do { t = ((java.lang.reflect.InvocationTargetException) t).getTargetException(); } while (t instanceof java.lang.reflect.InvocationTargetException); sendException(t, valueObject, out); } catch (Throwable e) { sendException(e, valueObject, out); // Turn it into a exception proxy on the client. } finally { // Clear out for GC to work valueObject.set(); parms = null; target = null; aMethod = null; returnType = null; newValue = null; valueSender.clear(); } break; case Commands.INVOKE_WITH_METHOD_PASSED: aClass = null; String methodName = null; Class[] parmTypes = null; target = null; parms = null; returnType = null; aMethod = null; try { Commands.readValue(in, valueObject); aClass = (Class) getInvokableObject(valueObject); // The class that has the method. methodName = in.readUTF(); Commands.readValue(in, valueObject); if (valueObject.type == Commands.ARRAY_IDS) { // It is an array containing IDs, as it normally would be. valueSender.initialize(valueObject); Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false); parmTypes = (Class[]) valueSender.getArray(); } else { // It null, so it should be an null. If not, then this is an error. parmTypes = null; } aMethod = aClass.getMethod(methodName, parmTypes); // Now we get the info for the invocation of the method and execute it. Commands.readValue(in, valueObject); target = getInvokableObject(valueObject); Commands.readValue(in, valueObject); if (valueObject.type == Commands.ARRAY_IDS) { // It is an array containing IDs, as it normally would be. valueSender.initialize(valueObject); Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false); parms = (Object[]) valueSender.getArray(); } else { // It is all objects or null, so it should be an Object[] or null. If not, then this // is an error. parms = (Object[]) valueObject.anObject; } if (!aMethod.isAccessible()) aMethod.setAccessible( true); // We will allow all to occur. Let access control be handled by IDE and // compiler. newValue = aMethod.invoke(target, parms); returnType = aMethod.getReturnType(); if (returnType.isPrimitive()) { int returnTypeID = server.getIdentityID(returnType); // Need to tell sendObject the correct primitive type. sendObject(newValue, returnTypeID, valueObject, out, true); } else { sendObject( newValue, NOT_A_PRIMITIVE, valueObject, out, true); // Just send the object back. sendObject knows how to iterpret the type } } catch (CommandException e) { throw e; // Throw it again. These we don't want to come up as an exception proxy. // These should end the thread. } catch (java.lang.reflect.InvocationTargetException e) { // This is a wrappered exception. Return the wrappered one so it looks like // it was the real one. (Sometimes the method being invoked is on a // java.lang.reflect.Constructor.newInstance, // which in turn is an InvocationTargetException, so we will go until we don't have an // InvocationTargetException. Throwable t = e; do { t = ((java.lang.reflect.InvocationTargetException) t).getTargetException(); } while (t instanceof java.lang.reflect.InvocationTargetException); sendException(t, valueObject, out); } catch (Throwable e) { sendException(e, valueObject, out); // Turn it into a exception proxy on the client. } finally { aClass = null; methodName = null; parmTypes = null; // Clear out for GC to work valueObject.set(); parms = null; target = null; aMethod = null; returnType = null; newValue = null; valueSender.clear(); } break; case Commands.GET_ARRAY_CONTENTS: try { target = server.getObject(in.readInt()); // Array to get the ids for. valueObject.setArrayIDS( new ArrayContentsRetriever(target), Array.getLength(target), Commands.OBJECT_CLASS); Commands.writeValue(out, valueObject, true); // Write it back as a value command. } catch (CommandException e) { throw e; // Throw it again. These we don't want to come up as an exception proxy. // These should end the thread. } catch (Throwable e) { sendException(e, valueObject, out); // Turn it into a exception proxy on the client. } finally { target = null; valueObject.set(); } break; case Commands.CALLBACK_DONE: try { if (connectionThread != null) { valueObject.set(); Commands.sendErrorCommand(out, Commands.UNKNOWN_COMMAND_SENT, valueObject); } else { try { Commands.readBackValue(in, valueObject, Commands.NO_TYPE_CHECK); if (valueObject.type == Commands.ARRAY_IDS) { // It is an array containing IDs, as it normally would be. valueSender.initialize(valueObject); Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false); result = valueSender.getArray(); } else { result = getInvokableObject(valueObject); } doLoop = false; // We need to terminate and return result closeWhenDone = false; // Don't close, we will continue. } catch (CommandErrorException e) { // There was an command error on the other side. This means // connection still good, but don't continue the callback processing. doLoop = false; // We need to terminate and return result closeWhenDone = false; // Don't close, we will continue. throw e; // Let it go on out. } } } finally { valueObject.set(); valueSender.clear(); } break; case Commands.ERROR: try { // Got an error command. Don't know what to do but read the // value and simply print it out. Commands.readValue(in, valueObject); result = getInvokableObject(valueObject); System.out.println("Error sent to server: Result=" + result); // $NON-NLS-1$ } finally { valueObject.set(); } break; case Commands.EXPRESSION_TREE_COMMAND: try { processExpressionCommand(valueObject, valueSender); } finally { valueObject.set(); valueSender.clear(); } break; default: // Unknown command. We don't know how long it is, so we need to shut the connection // down. System.err.println("Error: Invalid cmd send to server: Cmd=" + cmd); // $NON-NLS-1$ doLoop = false; closeWhenDone = true; break; } } } catch (EOFException e) { // This is ok. It means that the connection on the other side was terminated. // So just accept this and go down. } catch (CommandException e) { throw e; } catch (SocketException e) { if (socket != null) throw new UnexpectedExceptionCommandException( false, e); // socket null means a valid close request } catch (Throwable e) { e.printStackTrace(); } finally { if (closeWhenDone) { try { for (Iterator itr = expressionProcessors.values().iterator(); itr.hasNext(); ) { ExpressionProcesserController exp = (ExpressionProcesserController) itr.next(); exp.close(); } } finally { expressionProcessors.clear(); } if (in != null) try { in.close(); } catch (Exception e) { } in = null; if (out != null) try { out.close(); } catch (Exception e) { } out = null; close(); } } if (closeWhenDone && connectionThread != null) server.removeConnectionThread(connectionThread); if (shutdown) server.requestShutdown(); return result; }
private Object getParam( final Class<?> pClass, final String pName, final ParamType pType, final String pXpath, final HttpMessage pMessage) throws XmlException { Object result = null; switch (pType) { case GET: result = getParamGet(pName, pMessage); break; case POST: result = getParamPost(pName, pMessage); break; case QUERY: result = getParamGet(pName, pMessage); if (result == null) { result = getParamPost(pName, pMessage); } break; case VAR: result = mPathParams.get(pName); break; case XPATH: result = getParamXPath(pClass, pXpath, pMessage.getBody()); break; case BODY: result = getBody(pClass, pMessage); break; case ATTACHMENT: result = getAttachment(pClass, pName, pMessage); break; case PRINCIPAL: { final Principal principal = pMessage.getUserPrincipal(); if (pClass.isAssignableFrom(String.class)) { result = principal.getName(); } else { result = principal; } break; } } // XXX generizice this and share the same approach to unmarshalling in ALL code // TODO support collection/list parameters if ((result != null) && (!pClass.isInstance(result))) { if ((Types.isPrimitive(pClass) || (Types.isPrimitiveWrapper(pClass))) && (result instanceof String)) { try { result = Types.parsePrimitive(pClass, ((String) result)); } catch (NumberFormatException e) { throw new HttpResponseException( HttpServletResponse.SC_BAD_REQUEST, "The argument given is invalid", e); } } else if (Enum.class.isAssignableFrom(pClass)) { @SuppressWarnings({"rawtypes"}) final Class clazz = pClass; @SuppressWarnings("unchecked") final Enum<?> tmpResult = Enum.valueOf(clazz, result.toString()); result = tmpResult; } else if (result instanceof Node) { XmlDeserializer factory = pClass.getAnnotation(XmlDeserializer.class); if (factory != null) { try { result = factory .value() .newInstance() .deserialize(XmlStreaming.newReader(new DOMSource((Node) result))); } catch (IllegalAccessException | InstantiationException e) { throw new XmlException(e); } } else { result = JAXB.unmarshal(new DOMSource((Node) result), pClass); } } else { final String s = result.toString(); // Only wrap when we don't start with < final char[] requestBody = (s.startsWith("<") ? s : "<wrapper>" + s + "</wrapper>").toCharArray(); if (requestBody.length > 0) { result = JAXB.unmarshal(new CharArrayReader(requestBody), pClass); } else { result = null; } } } return result; }
/** * Performs conversions on argument types if needed and invokes the underlying Java method or * constructor. * * <p>Implements Function.call. * * @see gov.nbcs.rp.common.js.javascript.Function#call( Context, Scriptable, Scriptable, Object[]) */ public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { Object result; boolean checkMethodResult = false; if (parmsLength < 0) { if (parmsLength == VARARGS_METHOD) { Object[] invokeArgs = {cx, thisObj, args, this}; result = member.invoke(null, invokeArgs); checkMethodResult = true; } else { boolean inNewExpr = (thisObj == null); Boolean b = inNewExpr ? Boolean.TRUE : Boolean.FALSE; Object[] invokeArgs = {cx, args, this, b}; result = (member.isCtor()) ? member.newInstance(invokeArgs) : member.invoke(null, invokeArgs); } } else { if (!isStatic) { Class clazz = member.getDeclaringClass(); if (!clazz.isInstance(thisObj)) { boolean compatible = false; if (thisObj == scope) { Scriptable parentScope = getParentScope(); if (scope != parentScope) { // Call with dynamic scope for standalone function, // use parentScope as thisObj compatible = clazz.isInstance(parentScope); if (compatible) { thisObj = parentScope; } } } if (!compatible) { // Couldn't find an object to call this on. throw ScriptRuntime.typeError1("msg.incompat.call", functionName); } } } Object[] invokeArgs; if (parmsLength == args.length) { // Do not allocate new argument array if java arguments are // the same as the original js ones. invokeArgs = args; for (int i = 0; i != parmsLength; ++i) { Object arg = args[i]; Object converted = convertArg(cx, scope, arg, typeTags[i]); if (arg != converted) { if (invokeArgs == args) { invokeArgs = (Object[]) args.clone(); } invokeArgs[i] = converted; } } } else if (parmsLength == 0) { invokeArgs = ScriptRuntime.emptyArgs; } else { invokeArgs = new Object[parmsLength]; for (int i = 0; i != parmsLength; ++i) { Object arg = (i < args.length) ? args[i] : Undefined.instance; invokeArgs[i] = convertArg(cx, scope, arg, typeTags[i]); } } if (member.isMethod()) { result = member.invoke(thisObj, invokeArgs); checkMethodResult = true; } else { result = member.newInstance(invokeArgs); } } if (checkMethodResult) { if (hasVoidReturn) { result = Undefined.instance; } else if (returnTypeTag == JAVA_UNSUPPORTED_TYPE) { result = cx.getWrapFactory().wrap(cx, scope, result, null); } // XXX: the code assumes that if returnTypeTag == JAVA_OBJECT_TYPE // then the Java method did a proper job of converting the // result to JS primitive or Scriptable to avoid // potentially costly Context.javaToJS call. } return result; }
/** Gets the specific property, or null if the propert is not configured for this job. */ public <T extends JobProperty> T getProperty(Class<T> clazz) { for (JobProperty p : properties) { if (clazz.isInstance(p)) return clazz.cast(p); } return null; }
/** Type-munging for field setting and method invocation. Conforms to LC3 specification */ static Object coerceTypeImpl(Class<?> type, Object value) { if (value != null && value.getClass() == type) { return value; } switch (getJSTypeCode(value)) { case JSTYPE_NULL: // raise error if type.isPrimitive() if (type.isPrimitive()) { reportConversionError(value, type); } return null; case JSTYPE_UNDEFINED: if (type == ScriptRuntime.StringClass || type == ScriptRuntime.ObjectClass) { return "undefined"; } else { reportConversionError("undefined", type); } break; case JSTYPE_BOOLEAN: // Under LC3, only JS Booleans can be coerced into a Boolean value if (type == Boolean.TYPE || type == ScriptRuntime.BooleanClass || type == ScriptRuntime.ObjectClass) { return value; } else if (type == ScriptRuntime.StringClass) { return value.toString(); } else { reportConversionError(value, type); } break; case JSTYPE_NUMBER: if (type == ScriptRuntime.StringClass) { return ScriptRuntime.toString(value); } else if (type == ScriptRuntime.ObjectClass) { return coerceToNumber(Double.TYPE, value); } else if ((type.isPrimitive() && type != Boolean.TYPE) || ScriptRuntime.NumberClass.isAssignableFrom(type)) { return coerceToNumber(type, value); } else { reportConversionError(value, type); } break; case JSTYPE_STRING: if (type == ScriptRuntime.StringClass || type.isInstance(value)) { return value; } else if (type == Character.TYPE || type == ScriptRuntime.CharacterClass) { // Special case for converting a single char string to a // character // Placed here because it applies *only* to JS strings, // not other JS objects converted to strings if (((String) value).length() == 1) { return new Character(((String) value).charAt(0)); } else { return coerceToNumber(type, value); } } else if ((type.isPrimitive() && type != Boolean.TYPE) || ScriptRuntime.NumberClass.isAssignableFrom(type)) { return coerceToNumber(type, value); } else { reportConversionError(value, type); } break; case JSTYPE_JAVA_CLASS: if (value instanceof Wrapper) { value = ((Wrapper) value).unwrap(); } if (type == ScriptRuntime.ClassClass || type == ScriptRuntime.ObjectClass) { return value; } else if (type == ScriptRuntime.StringClass) { return value.toString(); } else { reportConversionError(value, type); } break; case JSTYPE_JAVA_OBJECT: case JSTYPE_JAVA_ARRAY: if (value instanceof Wrapper) { value = ((Wrapper) value).unwrap(); } if (type.isPrimitive()) { if (type == Boolean.TYPE) { reportConversionError(value, type); } return coerceToNumber(type, value); } else { if (type == ScriptRuntime.StringClass) { return value.toString(); } else { if (type.isInstance(value)) { return value; } else { reportConversionError(value, type); } } } break; case JSTYPE_OBJECT: if (type == ScriptRuntime.StringClass) { return ScriptRuntime.toString(value); } else if (type.isPrimitive()) { if (type == Boolean.TYPE) { reportConversionError(value, type); } return coerceToNumber(type, value); } else if (type.isInstance(value)) { return value; } else if (type == ScriptRuntime.DateClass && value instanceof NativeDate) { double time = ((NativeDate) value).getJSTimeValue(); // XXX: This will replace NaN by 0 return new Date((long) time); } else if (type.isArray() && value instanceof NativeArray) { // Make a new java array, and coerce the JS array components // to the target (component) type. NativeArray array = (NativeArray) value; long length = array.getLength(); Class<?> arrayType = type.getComponentType(); Object Result = Array.newInstance(arrayType, (int) length); for (int i = 0; i < length; ++i) { try { Array.set(Result, i, coerceType(arrayType, array.get(i, array))); } catch (EvaluatorException ee) { reportConversionError(value, type); } } return Result; } else if (value instanceof Wrapper) { value = ((Wrapper) value).unwrap(); if (type.isInstance(value)) return value; reportConversionError(value, type); } else if (type.isInterface() && value instanceof Callable) { // Try to use function as implementation of Java interface. // // XXX: Currently only instances of ScriptableObject are // supported since the resulting interface proxies should // be reused next time conversion is made and generic // Callable has no storage for it. Weak references can // address it but for now use this restriction. if (value instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject) value; Object key = Kit.makeHashKeyFromPair(COERCED_INTERFACE_KEY, type); Object old = so.getAssociatedValue(key); if (old != null) { // Function was already wrapped return old; } Context cx = Context.getContext(); Object glue = InterfaceAdapter.create(cx, type, (Callable) value); // Store for later retrival glue = so.associateValue(key, glue); return glue; } reportConversionError(value, type); } else { reportConversionError(value, type); } break; } return value; }
/** * Derive a ranking based on how "natural" the conversion is. The special value CONVERSION_NONE * means no conversion is possible, and CONVERSION_NONTRIVIAL signals that more type conformance * testing is required. Based on <a * href="http://www.mozilla.org/js/liveconnect/lc3_method_overloading.html">"preferred method * conversions" from Live Connect 3</a> */ static int getConversionWeight(Object fromObj, Class<?> to) { int fromCode = getJSTypeCode(fromObj); switch (fromCode) { case JSTYPE_UNDEFINED: if (to == ScriptRuntime.StringClass || to == ScriptRuntime.ObjectClass) { return 1; } break; case JSTYPE_NULL: if (!to.isPrimitive()) { return 1; } break; case JSTYPE_BOOLEAN: // "boolean" is #1 if (to == Boolean.TYPE) { return 1; } else if (to == ScriptRuntime.BooleanClass) { return 2; } else if (to == ScriptRuntime.ObjectClass) { return 3; } else if (to == ScriptRuntime.StringClass) { return 4; } break; case JSTYPE_NUMBER: if (to.isPrimitive()) { if (to == Double.TYPE) { return 1; } else if (to != Boolean.TYPE) { return 1 + getSizeRank(to); } } else { if (to == ScriptRuntime.StringClass) { // native numbers are #1-8 return 9; } else if (to == ScriptRuntime.ObjectClass) { return 10; } else if (ScriptRuntime.NumberClass.isAssignableFrom(to)) { // "double" is #1 return 2; } } break; case JSTYPE_STRING: if (to == ScriptRuntime.StringClass) { return 1; } else if (to.isInstance(fromObj)) { return 2; } else if (to.isPrimitive()) { if (to == Character.TYPE) { return 3; } else if (to != Boolean.TYPE) { return 4; } } break; case JSTYPE_JAVA_CLASS: if (to == ScriptRuntime.ClassClass) { return 1; } else if (to == ScriptRuntime.ObjectClass) { return 3; } else if (to == ScriptRuntime.StringClass) { return 4; } break; case JSTYPE_JAVA_OBJECT: case JSTYPE_JAVA_ARRAY: Object javaObj = fromObj; if (javaObj instanceof Wrapper) { javaObj = ((Wrapper) javaObj).unwrap(); } if (to.isInstance(javaObj)) { return CONVERSION_NONTRIVIAL; } if (to == ScriptRuntime.StringClass) { return 2; } else if (to.isPrimitive() && to != Boolean.TYPE) { return (fromCode == JSTYPE_JAVA_ARRAY) ? CONVERSION_NONE : 2 + getSizeRank(to); } break; case JSTYPE_OBJECT: // Other objects takes #1-#3 spots if (to == fromObj.getClass()) { // No conversion required return 1; } if (to.isArray()) { if (fromObj instanceof NativeArray) { // This is a native array conversion to a java array // Array conversions are all equal, and preferable to object // and string conversion, per LC3. return 1; } } else if (to == ScriptRuntime.ObjectClass) { return 2; } else if (to == ScriptRuntime.StringClass) { return 3; } else if (to == ScriptRuntime.DateClass) { if (fromObj instanceof NativeDate) { // This is a native date to java date conversion return 1; } } else if (to.isInterface()) { if (fromObj instanceof Function) { // See comments in coerceType if (to.getMethods().length == 1) { return 1; } } return 11; } else if (to.isPrimitive() && to != Boolean.TYPE) { return 3 + getSizeRank(to); } break; } return CONVERSION_NONE; }