private int findfd(Object fdObj) throws Exception { Class cl; Field f; Object val, implVal; if ((fdObj instanceof java.net.Socket) || (fdObj instanceof java.net.ServerSocket)) { cl = fdObj.getClass(); f = cl.getDeclaredField("impl"); f.setAccessible(true); val = f.get(fdObj); cl = f.getType(); f = cl.getDeclaredField("fd"); f.setAccessible(true); implVal = f.get(val); cl = f.getType(); f = cl.getDeclaredField("fd"); f.setAccessible(true); return ((Integer) f.get(implVal)).intValue(); } else if (fdObj instanceof java.io.FileDescriptor) { cl = fdObj.getClass(); f = cl.getDeclaredField("fd"); f.setAccessible(true); return ((Integer) f.get(fdObj)).intValue(); } else { throw new IllegalArgumentException("Illegal Object type."); } }
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")); } } }
private KeyStore createKeyStore(@Nullable String path) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { String keyStoreType = KeyStore.getDefaultType(); char[] defaultPassword = "******".toCharArray(); if (path != null) { // If the user provided path, only try to load the keystore at that path. KeyStore keyStore = KeyStore.getInstance(keyStoreType); FileInputStream is = new FileInputStream(path); keyStore.load(is, defaultPassword); return keyStore; } try { // Check if we are on Android. Class version = Class.forName("android.os.Build$VERSION"); // Build.VERSION_CODES.ICE_CREAM_SANDWICH is 14. if (version.getDeclaredField("SDK_INT").getInt(version) >= 14) { // After ICS, Android provided this nice method for loading the keystore, // so we don't have to specify the location explicitly. KeyStore keystore = KeyStore.getInstance("AndroidCAStore"); keystore.load(null, null); return keystore; } else { keyStoreType = "BKS"; path = System.getProperty("java.home") + "/etc/security/cacerts.bks".replace('/', File.separatorChar); } } catch (ClassNotFoundException e) { // NOP. android.os.Build is not present, so we are not on Android. Fall through. } catch (NoSuchFieldException e) { throw new RuntimeException(e); // Should never happen. } catch (IllegalAccessException e) { throw new RuntimeException(e); // Should never happen. } if (path == null) { path = System.getProperty("javax.net.ssl.trustStore"); } if (path == null) { // Try this default system location for Linux/Windows/OSX. path = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar); } try { KeyStore keyStore = KeyStore.getInstance(keyStoreType); FileInputStream is = new FileInputStream(path); keyStore.load(is, defaultPassword); return keyStore; } catch (FileNotFoundException e) { // If we failed to find a system trust store, load our own fallback trust store. This can fail // on Android // but we should never reach it there. KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream is = getClass().getResourceAsStream("cacerts"); keyStore.load(is, defaultPassword); return keyStore; } }
/** * Set the current opcode. This sets four global fields: the currentOpcode, the * currentOpcodeArgTable, the currentFormat and the currentOpcodeSymbolicNames. * * @param opcode The IA32 architecture opcode to make the current opcode */ static void setCurrentOpcode(String opcode) { try { currentOpcode = opcode; currentOpcodeArgTable = (int[]) opcodeArgTables.get(opcode); currentFormat = OperatorFormatTables.getFormat(opcode); Field f = formats.getDeclaredField(currentFormat + "ParameterNames"); currentOpcodeSymbolicNames = (String[]) f.get(null); } catch (Throwable e) { throw new Error("Cannot handle Assembler opcode " + opcode, e); } }
/** * `获取给定对象的属性的值` `@param fieldName 属性名` `@param obj 对象` * * @return */ public static Object getFieldValue(String fieldName, Object obj) { try { Class cls = obj.getClass(); Field field = cls.getDeclaredField(fieldName); return field.get(obj); } catch (Exception e) { e.printStackTrace(); print("Field access error!"); throw new RuntimeException(e); } }
public int getPid(Process process) { try { Class<?> cProcessImpl = process.getClass(); Field fPid = cProcessImpl.getDeclaredField("pid"); if (!fPid.isAccessible()) { fPid.setAccessible(true); } return fPid.getInt(process); } catch (Exception e) { return -1; } }
public static Field makeAccessible(Class<?> target, String fieldName) { try { final Field field = target.getDeclaredField(fieldName); return (Field) AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws IllegalAccessException, InvocationTargetException { if (!field.isAccessible()) field.setAccessible(true); return field; } }); } catch (NoSuchFieldException | PrivilegedActionException e) { System.out.print(""); } // keep quiet IError.printStackTrace(e); } return null; }
// getField: Borrowed from WorldEdit @SuppressWarnings("unchecked") public static <T> T getField(Object from, String name) { Class<?> checkClass = from.getClass(); do { try { Field field = checkClass.getDeclaredField(name); field.setAccessible(true); return (T) field.get(from); } catch (NoSuchFieldException ex) { } catch (IllegalAccessException ex) { } } while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null)); return null; }
private void setMobileDataEnabled() { boolean dataConnection; dataConnection = enable_3g; try { final ConnectivityManager conman = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); final Class conmanClass = Class.forName(conman.getClass().getName()); final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService"); iConnectivityManagerField.setAccessible(true); final Object iConnectivityManager = iConnectivityManagerField.get(conman); final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName()); final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConnectivityManager, dataConnection); } catch (Exception e) { } }
/** * Serializes the given class to the getCurrentDirectory() directory. The static * serializedInstance() method of clazz will be called to get an examplar of clazz. This examplar * will then be serialized out to a file stored in getCurrentDirectory(). * * @param clazz the class to serialize. * @throws RuntimeException if clazz cannot be serialized. This exception has an informative * message and wraps the originally thrown exception as root cause. * @see #getCurrentDirectory() */ private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException { File current = new File(getCurrentDirectory()); if (!current.exists() || !current.isDirectory()) { throw new IllegalStateException( "There is no " + current.getAbsolutePath() + " directory. " + "\nThis is where the serialized classes should be. " + "Please run serializeCurrentDirectory() first."); } try { Field field = clazz.getDeclaredField("serialVersionUID"); int modifiers = field.getModifiers(); boolean _static = Modifier.isStatic(modifiers); boolean _final = Modifier.isFinal(modifiers); field.setAccessible(true); if (!_static || !_final || !(23L == field.getLong(null))) { throw new RuntimeException( "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L"); } int numFields = getNumNonSerialVersionUIDFields(clazz); if (numFields > 0) { Method method = clazz.getMethod("serializableInstance"); Object object = method.invoke(null); File file = new File(current, clazz.getName() + ".ser"); boolean created = file.createNewFile(); FileOutputStream out = new FileOutputStream(file); ObjectOutputStream objOut = new ObjectOutputStream(out); objOut.writeObject(object); out.close(); } // Make entry in list of class fields. ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz); String className = objectStreamClass.getName(); ObjectStreamField[] fields = objectStreamClass.getFields(); @SuppressWarnings("Convert2Diamond") List<String> fieldList = new ArrayList<>(); for (ObjectStreamField objectStreamField : fields) { String fieldName = objectStreamField.getName(); fieldList.add(fieldName); } classFields.put(className, fieldList); } catch (NoSuchFieldException e) { throw new RuntimeException( ("There is no static final long field " + "'serialVersionUID' in " + clazz + ". Please make one and set it " + "to 23L.")); } catch (NoSuchMethodException e) { throw new RuntimeException( "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e); } catch (IllegalAccessException e) { throw new RuntimeException( "The method serializableInstance() of " + "class " + clazz + " is not public.", e); } catch (InvocationTargetException e) { throw new RuntimeException( "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e); } catch (IOException e) { throw new RuntimeException( "Could not create a new, writeable file " + "in " + getCurrentDirectory() + " when trying to serialize " + clazz + ".", e); } }
public Writer getErrorReport( Writer to, final HttpServletRequest request, CharTransformer escape) throws IOException { final Writer logMsg = new StringWriter(); final Writer tee = new org.mmbase.util.ChainedWriter(to, logMsg); Writer msg = tee; LinkedList<Throwable> stack = getStack(); String ticket = new Date().toString(); Map<String, String> props; try { props = org.mmbase.util.ApplicationContextReader.getProperties("mmbase_errorpage"); } catch (javax.naming.NamingException ne) { props = Collections.emptyMap(); log.info(ne); } if (request != null) { { msg.append("Headers\n----------\n"); // request properties for (Object name : Collections.list(request.getHeaderNames())) { msg.append( escape.transform( name + ": " + escape.transform(request.getHeader((String) name)) + "\n")); } } { msg.append("\nAttributes\n----------\n"); Pattern p = requestIgnore; if (p == null && props.get("request_ignore") != null) { p = Pattern.compile(props.get("request_ignore")); } for (Object name : Collections.list(request.getAttributeNames())) { if (p == null || !p.matcher((String) name).matches()) { msg.append( escape.transform(name + ": " + request.getAttribute((String) name) + "\n")); } } } if (Boolean.TRUE.equals(showSession) || (showSession == null && !"false".equals(props.get("show_session")))) { HttpSession ses = request.getSession(false); if (ses != null) { msg.append("\nSession\n----------\n"); Pattern p = sessionIgnore; if (p == null && props.get("session_ignore") != null) { p = Pattern.compile(props.get("session_ignore")); } for (Object name : Collections.list(ses.getAttributeNames())) { if (p == null || !p.matcher((String) name).matches()) { msg.append(escape.transform(name + ": " + ses.getAttribute((String) name) + "\n")); } } } } } msg.append("\n"); msg.append("Misc. properties\n----------\n"); if (request != null) { msg.append("method: ").append(escape.transform(request.getMethod())).append("\n"); msg.append("querystring: ").append(escape.transform(request.getQueryString())).append("\n"); msg.append("requesturl: ") .append(escape.transform(request.getRequestURL().toString())) .append("\n"); } if (Boolean.TRUE.equals(showMMBaseVersion) || (showMMBaseVersion == null && !"false".equals(props.get("show_mmbase_version")))) { msg.append("mmbase version: ").append(org.mmbase.Version.get()).append("\n"); } msg.append("status: ").append("").append(String.valueOf(status)).append("\n\n"); if (request != null) { msg.append("Parameters\n----------\n"); // request parameters Enumeration en = request.getParameterNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); msg.append(name) .append(": ") .append(escape.transform(request.getParameter(name))) .append("\n"); } } msg.append("\nException ") .append(ticket) .append("\n----------\n\n") .append( exception != null ? (escape.transform(exception.getClass().getName())) : "NO EXCEPTION") .append(": "); int wroteCauses = 0; while (!stack.isEmpty()) { Throwable t = stack.removeFirst(); // add stack stacktraces if (t != null) { if (stack.isEmpty()) { // write last message always msg = tee; } String message = t.getMessage(); if (msg != tee) { to.append("\n=== skipped(see log) : ") .append(escape.transform(t.getClass().getName())) .append(": ") .append(message) .append("\n"); } msg.append("\n\n").append(escape.transform(t.getClass().getName() + ": " + message)); StackTraceElement[] stackTrace = t.getStackTrace(); for (StackTraceElement e : stackTrace) { msg.append("\n at ").append(escape.transform(e.toString())); } if (!stack.isEmpty()) { msg.append("\n-------caused:\n"); } wroteCauses++; if (wroteCauses >= MAX_CAUSES) { msg = logMsg; } } } // write errors to log if (status == 500) { try { if (props.get("to") != null && props.get("to").length() > 0) { javax.naming.Context initCtx = new javax.naming.InitialContext(); javax.naming.Context envCtx = (javax.naming.Context) initCtx.lookup("java:comp/env"); Object mailSession = envCtx.lookup("mail/Session"); Class sessionClass = Class.forName("javax.mail.Session"); Class recipientTypeClass = Class.forName("javax.mail.Message$RecipientType"); Class messageClass = Class.forName("javax.mail.internet.MimeMessage"); Object mail = messageClass.getConstructor(sessionClass).newInstance(mailSession); messageClass .getMethod("addRecipients", recipientTypeClass, String.class) .invoke(mail, recipientTypeClass.getDeclaredField("TO").get(null), props.get("to")); messageClass.getMethod("setSubject", String.class).invoke(mail, ticket); mail.getClass().getMethod("setText", String.class).invoke(mail, logMsg.toString()); Class.forName("javax.mail.Transport") .getMethod("send", Class.forName("javax.mail.Message")) .invoke(null, mail); tee.append("\nmailed to (").append(String.valueOf(props)).append(")"); } } catch (Exception nnfe) { tee.append("\nnot mailed (").append(String.valueOf(nnfe)).append(")"); if (log.isDebugEnabled()) { log.debug(nnfe.getMessage(), nnfe); } } log.error("TICKET " + ticket + ":\n" + logMsg); } return to; }
public static Object getAdapterSelf(Class<?> adapterClass, Object adapter) throws NoSuchFieldException, IllegalAccessException { Field self = adapterClass.getDeclaredField("self"); return self.get(adapter); }