private static Future<Void> startDeletionThread(@NotNull final File... tempFiles) { final RunnableFuture<Void> deleteFilesTask = new FutureTask<Void>( new Runnable() { @Override public void run() { final Thread currentThread = Thread.currentThread(); final int priority = currentThread.getPriority(); currentThread.setPriority(Thread.MIN_PRIORITY); try { for (File tempFile : tempFiles) { delete(tempFile); } } finally { currentThread.setPriority(priority); } } }, null); try { // attempt to execute on pooled thread final Class<?> aClass = Class.forName("com.intellij.openapi.application.ApplicationManager"); final Method getApplicationMethod = aClass.getMethod("getApplication"); final Object application = getApplicationMethod.invoke(null); final Method executeOnPooledThreadMethod = application.getClass().getMethod("executeOnPooledThread", Runnable.class); executeOnPooledThreadMethod.invoke(application, deleteFilesTask); } catch (Exception ignored) { new Thread(deleteFilesTask, "File deletion thread").start(); } return deleteFilesTask; }
static { if (!Boolean.getBoolean(GridSystemProperties.GG_JETTY_LOG_NO_OVERRIDE)) { String ctgrJetty = "org.eclipse.jetty"; // WARN for this category. String ctgrJettyUtil = "org.eclipse.jetty.util.log"; // ERROR for this... String ctgrJettyUtilComp = "org.eclipse.jetty.util.component"; // ...and this. try { Class<?> logCls = Class.forName("org.apache.log4j.Logger"); Object logJetty = logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJetty); Object logJettyUtil = logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJettyUtil); Object logJettyUtilComp = logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJettyUtilComp); Class<?> lvlCls = Class.forName("org.apache.log4j.Level"); Object warnLvl = lvlCls.getField("WARN").get(null); Object errLvl = lvlCls.getField("ERROR").get(null); logJetty.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, warnLvl); logJettyUtil.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, errLvl); logJettyUtilComp.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, errLvl); } catch (Exception ignored) { // No-op. } } }
private boolean findAllTestedAndInjectableFieldsInTestClassHierarchy( @NotNull Class<?> testClass) { Class<?> classWithFields = testClass; do { Field[] fields = classWithFields.getDeclaredFields(); findTestedAndInjectableFields(fields); classWithFields = classWithFields.getSuperclass(); } while (classWithFields.getClassLoader() != null); return !testedFields.isEmpty(); }
/** * Returns compact class host. * * @param obj Object to compact. * @return String. */ @Nullable public static Object compactObject(Object obj) { if (obj == null) return null; if (obj instanceof Enum) return obj.toString(); if (obj instanceof String || obj instanceof Boolean || obj instanceof Number) return obj; if (obj instanceof Collection) { Collection col = (Collection) obj; Object[] res = new Object[col.size()]; int i = 0; for (Object elm : col) res[i++] = compactObject(elm); return res; } if (obj.getClass().isArray()) { Class<?> arrType = obj.getClass().getComponentType(); if (arrType.isPrimitive()) { if (obj instanceof boolean[]) return Arrays.toString((boolean[]) obj); if (obj instanceof byte[]) return Arrays.toString((byte[]) obj); if (obj instanceof short[]) return Arrays.toString((short[]) obj); if (obj instanceof int[]) return Arrays.toString((int[]) obj); if (obj instanceof long[]) return Arrays.toString((long[]) obj); if (obj instanceof float[]) return Arrays.toString((float[]) obj); if (obj instanceof double[]) return Arrays.toString((double[]) obj); } Object[] arr = (Object[]) obj; int iMax = arr.length - 1; StringBuilder sb = new StringBuilder("["); for (int i = 0; i <= iMax; i++) { sb.append(compactObject(arr[i])); if (i != iMax) sb.append(", "); } sb.append("]"); return sb.toString(); } return U.compact(obj.getClass().getName()); }
/** * Constructs new instance of the specified class. * * @param exp Expected class for the new instance. * @param clsName Class name to create new instance for. * @param <T> Expected class type for the new instance. * @return New instance of specified class. * @throws GridClientException If loading failed. */ private static <T> T newInstance(Class<T> exp, String clsName) throws GridClientException { Object obj; try { obj = Class.forName(clsName).newInstance(); } // Catch all for convenience. catch (Exception e) { throw new GridClientException("Failed to create class instance: " + clsName, e); } return exp.cast(obj); }
/** {@inheritDoc} */ @Override public void start() throws GridException { if (ctx.isEnterprise()) { Package pkg = getClass().getPackage(); if (pkg == null) throw new GridException( "Internal error (package object was not found) for: " + getClass().getName()); if (ctx.isEnterprise()) { try { Class<?> cls = Class.forName(pkg.getName() + ".GridEnterpriseSecureSessionHandler"); sesHnd = (GridSecureSessionHandler) cls.getConstructor(GridSecureSessionSpi[].class) .newInstance(new Object[] {getProxies()}); } catch (ClassNotFoundException e) { throw new GridException( "Failed to create enterprise secure session handler (implementing class " + "was not found)", e); } catch (InvocationTargetException e) { throw new GridException( "Failed to create enterprise secure session handler (target constructor " + "has thrown an exception", e.getCause()); } catch (InstantiationException e) { throw new GridException( "Failed to create enterprise secure session handler (object cannot be " + "instantiated)", e); } catch (NoSuchMethodException e) { throw new GridException( "Failed to create enterprise secure session handler (target constructor " + "could not be found)", e); } catch (IllegalAccessException e) { throw new GridException( "Failed to create enterprise secure session handler (object access is not" + " allowed)", e); } } } else sesHnd = new GridCommunitySecureSessionHandler(); startSpi(); if (log.isDebugEnabled()) log.debug(startInfo()); }
/** {@inheritDoc} */ @Nullable @Override public GridDeployment explicitDeploy(Class<?> cls, ClassLoader clsLdr) throws GridException { try { // Make sure not to deploy peer loaded tasks with non-local class loader, // if local one exists. if (clsLdr.getClass().equals(GridDeploymentClassLoader.class)) clsLdr = clsLdr.getParent(); GridDeployment dep; synchronized (mux) { boolean deployed = spi.register(clsLdr, cls); if (deployed) { dep = getDeployment(cls.getName()); if (dep == null) { GridDeploymentResource rsrc = spi.findResource(cls.getName()); if (rsrc != null && rsrc.getClassLoader() == clsLdr) { dep = deploy( ctx.config().getDeploymentMode(), rsrc.getClassLoader(), rsrc.getResourceClass(), rsrc.getName()); } } if (dep != null) { recordDeploy(cls, cls.getName(), true); } } else { dep = getDeployment(cls.getName()); } } return dep; } catch (GridSpiException e) { recordDeployFailed(cls, clsLdr, true); // Avoid double wrapping. if (e.getCause() instanceof GridException) { throw (GridException) e.getCause(); } throw new GridException("Failed to deploy class: " + cls.getName(), e); } }
/** * Log task mapped. * * @param log Logger. * @param clazz Task class. * @param nodes Mapped nodes. */ public static void logMapped( @Nullable IgniteLogger log, Class<?> clazz, Collection<ClusterNode> nodes) { log0( log, U.currentTimeMillis(), String.format("[%s]: MAPPED: %s", clazz.getSimpleName(), U.toShortString(nodes))); }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public <T> T unwrap(Class<T> cls) { if (cls.isAssignableFrom(CacheEntry.class) && ver != null) return (T) new CacheEntryImplEx<>(getKey(), getValue(), ver); return super.unwrap(cls); }
/** * Log finished. * * @param log Logger. * @param clazz Class. * @param start Start time. */ public static void logFinish(@Nullable IgniteLogger log, Class<?> clazz, long start) { final long end = U.currentTimeMillis(); log0( log, end, String.format( "[%s]: FINISHED, duration: %s", clazz.getSimpleName(), formatDuration(end - start))); }
/** * Log message. * * @param log Logger. * @param msg Message to log. * @param clazz class. * @param start start time. * @return Time when message was logged. */ public static long log(@Nullable IgniteLogger log, String msg, Class<?> clazz, long start) { final long end = U.currentTimeMillis(); log0( log, end, String.format( "[%s]: %s, duration: %s", clazz.getSimpleName(), msg, formatDuration(end - start))); return end; }
/** * Gets alias for a class. * * @param dep Deployment. * @param cls Class. * @return Alias for a class. */ private String getAlias(GridDeployment dep, Class<?> cls) { String alias = cls.getName(); if (isTask(cls)) { GridTaskName ann = dep.annotation(cls, GridTaskName.class); if (ann != null) { alias = ann.value(); } } return alias; }
/** {@inheritDoc} */ @Override public HadoopJob createJob(Class<? extends HadoopJob> jobCls, HadoopJobId jobId, IgniteLogger log) throws IgniteCheckedException { assert jobCls != null; try { Constructor<? extends HadoopJob> constructor = jobCls.getConstructor(HadoopJobId.class, HadoopDefaultJobInfo.class, IgniteLogger.class); return constructor.newInstance(jobId, this, log); } // NB: java.lang.NoClassDefFoundError may be thrown from Class#getConstructor() call. catch (Throwable t) { if (t instanceof Error) throw (Error) t; throw new IgniteCheckedException(t); } }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { id = in.readInt(); String clsName = in.readUTF(); if (clsName == null) innerSplit = in.readObject(); else { // Split wrapper only used when classes available in our classpath, so Class.forName is ok // here. Class<Writable> cls = (Class<Writable>) Class.forName(clsName); try { innerSplit = U.newInstance(cls); } catch (GridException e) { throw new IOException(e); } ((Writable) innerSplit).readFields(in); } }
/** {@inheritDoc} */ @Override public void onDeployed(Class<?> cls) { assert !Thread.holdsLock(mux); boolean isTask = isTask(cls); String msg = (isTask ? "Task" : "Class") + " was deployed in SHARED or CONTINUOUS mode: " + cls; int type = isTask ? EVT_TASK_DEPLOYED : EVT_CLASS_DEPLOYED; if (ctx.event().isRecordable(type)) { GridDeploymentEvent evt = new GridDeploymentEvent(); evt.nodeId(ctx.localNodeId()); evt.message(msg); evt.type(type); evt.alias(cls.getName()); ctx.event().record(evt); } if (log.isInfoEnabled()) log.info(msg); }
/** * Log start. * * @param log Logger. * @param clazz Class. * @param start Start time. */ public static void logStart(@Nullable IgniteLogger log, Class<?> clazz, long start) { log0(log, start, "[" + clazz.getSimpleName() + "]: STARTED"); }
/** * @param depMode Deployment mode. * @param ldr Class loader to deploy. * @param cls Class. * @param alias Class alias. * @return Deployment. */ @SuppressWarnings({"ConstantConditions"}) private GridDeployment deploy( GridDeploymentMode depMode, ClassLoader ldr, Class<?> cls, String alias) { assert Thread.holdsLock(mux); LinkedList<GridDeployment> cachedDeps = null; GridDeployment dep = null; // Find existing class loader info. for (LinkedList<GridDeployment> deps : cache.values()) { for (GridDeployment d : deps) { if (d.classLoader() == ldr) { // Cache class and alias. d.addDeployedClass(cls, alias); cachedDeps = deps; dep = d; break; } } if (cachedDeps != null) { break; } } if (cachedDeps != null) { assert dep != null; cache.put(alias, cachedDeps); if (!cls.getName().equals(alias)) { // Cache by class name as well. cache.put(cls.getName(), cachedDeps); } return dep; } GridUuid ldrId = GridUuid.randomUuid(); long seqNum = seq.incrementAndGet(); String userVer = getUserVersion(ldr); dep = new GridDeployment(depMode, ldr, ldrId, seqNum, userVer, cls.getName(), true); dep.addDeployedClass(cls, alias); LinkedList<GridDeployment> deps = F.addIfAbsent(cache, alias, F.<GridDeployment>newLinkedList()); if (!deps.isEmpty()) { for (GridDeployment d : deps) { if (!d.isUndeployed()) { U.error( log, "Found more than one active deployment for the same resource " + "[cls=" + cls + ", depMode=" + depMode + ", dep=" + d + ']'); return null; } } } // Add at the beginning of the list for future fast access. deps.addFirst(dep); if (!cls.getName().equals(alias)) { // Cache by class name as well. cache.put(cls.getName(), deps); } if (log.isDebugEnabled()) { log.debug("Created new deployment: " + dep); } return dep; }