Example usage for java.lang System identityHashCode

List of usage examples for java.lang System identityHashCode

Introduction

In this page you can find the example usage for java.lang System identityHashCode.

Prototype

@HotSpotIntrinsicCandidate
public static native int identityHashCode(Object x);

Source Link

Document

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().

Usage

From source file:com.amossys.hooker.hookers.Hooker.java

protected void hookMethodsWithOutputs(final HookerListener listener, final String className,
        final Map<String, Integer> methods, final Map<String, Object> outputs)
        throws HookerInitializationException {

    final String hookerName = this.getHookerName();

    MS.hookClassLoad(className, new MS.ClassLoadHook() {

        @SuppressWarnings({ "unchecked", "rawtypes" })
        public void classLoaded(Class<?> resources) {

            /**/*  w ww  .  j av a2s  . co m*/
             * Based on the name of the method, we retrieve all the possibilities
             */
            Map<GenericDeclaration, String> methodsToHook = new HashMap<GenericDeclaration, String>();
            boolean found;
            for (String methodName : methods.keySet()) {
                found = false;

                /**
                 * Checks if the requested method is a constructor or not
                 */
                if (className.substring(className.lastIndexOf('.') + 1).equals(methodName)) {
                    found = true;
                    for (int iConstructor = 0; iConstructor < resources
                            .getConstructors().length; iConstructor++) {
                        methodsToHook.put(resources.getConstructors()[iConstructor], methodName);
                    }
                } else {
                    for (Method m : resources.getMethods()) {
                        if (m.getName().equals(methodName)) {
                            found = true;
                            methodsToHook.put(m, methodName);
                        }
                    }
                }
                if (!found) {
                    SubstrateMain.log(new StringBuilder("No method found with name ").append(className)
                            .append(":").append(methodName).toString());
                }
            }

            for (final GenericDeclaration pMethod : methodsToHook.keySet()) {
                final String methodName = methodsToHook.get(pMethod);
                if (SubstrateMain.DEBUG_MODE) {
                    SubstrateMain.log(new StringBuilder("Hooking method ").append(className).append(":")
                            .append(methodName).toString());
                }

                // To debug Substrate if you have a stacktrace
                // for (Class param : ((Method) pMethod).getParameterTypes()) {
                // SubstrateMain.log("   Param: " + param.getSimpleName());
                // }

                final int intrusiveLevelFinal = methods.get(methodName);

                final MS.MethodPointer<Object, Object> old = new MethodPointer<Object, Object>();
                MS.hookMethod_(resources, (Member) pMethod, new MS.MethodHook() {
                    public Object invoked(final Object resources, final Object... args) throws Throwable {

                        if (ApplicationConfig.isFiltered() || ApplicationConfig.getPackageName() == null) {
                            return old.invoke(resources, args);
                        }

                        if (isSelfHooking((Member) pMethod)) {
                            SubstrateMain.log(
                                    "Self hooking detected on method '" + ((Member) pMethod).getName() + "'.");
                            return old.invoke(resources, args);
                        }

                        final String packName = ApplicationConfig.getPackageName();
                        final Context appContext = ApplicationConfig.getContext();

                        InterceptEvent event = null;

                        if (packName != null && appContext != null) {

                            // Open the connection to the service if not yet bound
                            if (!serviceConnection.isBoundToTheService()) {
                                serviceConnection.doBindService(appContext);
                            }

                            // Create the intercept event for this hook
                            event = new InterceptEvent(hookerName, intrusiveLevelFinal,
                                    System.identityHashCode(resources), packName, className, methodName);

                            //TODO: We should also save the parameters value before the call.
                            //      it requires to clone the parameters
                            //      and save them in the event if their value is different after the call

                            /**
                             * If specified, we execute the before method of the provided listener
                             */
                            if (listener != null) {
                                listener.before(className, pMethod, resources, event);
                            }

                        }

                        /**
                         * We invoke the original method and capture the result
                         */
                        Object result = old.invoke(resources, args);

                        // if requested we modify the output value of the invocation
                        if (outputs != null && outputs.containsKey(methodName)) {

                            if (result == null || outputs.get(methodName) == null
                                    || result.getClass().isAssignableFrom(outputs.get(methodName).getClass())) {
                                result = outputs.get(methodName);
                            } else {
                                SubstrateMain.log("Cannot replace method " + methodName + " output with "
                                        + outputs.get(methodName) + ": types are incompatible.", false);
                            }
                        }

                        // Store the result in the event (if available)
                        if (event != null && appContext != null) {

                            // Register the parameters of the method call in the event
                            if (args != null) {
                                for (Object arg : args) {
                                    if (arg != null) {
                                        String argValue = getStringRepresentationOfAttribute(arg);
                                        event.addParameter(arg.getClass().getName(), argValue);
                                    } else {
                                        event.addParameter(null, null);
                                    }
                                }
                            }

                            // if the invocation returned something we store it in the event
                            if (result != null) {
                                String strResult = getStringRepresentationOfAttribute(result);
                                event.setReturns(result.getClass().getName(), strResult);
                            } else {
                                event.setReturns(null, null);
                            }

                            /**
                             * if specified, we execute the after method of the provided listener
                             */
                            if (listener != null) {
                                listener.after(className, pMethod, resources, event);
                            }

                            insertEvent(event, appContext);
                        }

                        return result;
                    }

                    /**
                     * Computes if we are self hooking ourselves. To do so, we generate a stack trace to retrieve
                     * the caller list of the current invocation and check no Hooker appears after the second entry of the stack trace.
                     * @param pMethod 
                     * @param pMethod 
                     * @return true if we are self-hooking
                     */
                    private boolean isSelfHooking(Member pMethod) {
                        boolean selfHooking = false;
                        StackTraceElement[] stackTrace = new Throwable().getStackTrace();
                        if (stackTrace.length > 2) {
                            for (int i = 2; i < stackTrace.length; i++) {
                                if (stackTrace[i].getClassName().startsWith(Hooker.class.getName())) {
                                    selfHooking = true;
                                    break;
                                }
                            }
                        }
                        return selfHooking;
                    }

                }, old);
            }

        }
    });

}

From source file:de.ailis.midi4js.Midi4JS.java

/**
 * Returns all currently open receivers.
 *
 * @param deviceHandle//from  ww  w.  j av a  2  s. c o m
 *            The device handle.
 * @return All currently open receivers in form of a JSON-encoded string
 *         which describes an array of receiver handles.
 * @throws JSONException
 *             When JSON data could not be constructed.
 */
public String getReceivers(final int deviceHandle) throws JSONException {
    final MidiDevice device = resolveDeviceHandle(deviceHandle);
    final JSONStringer json = new JSONStringer();
    json.array();
    for (final Receiver receiver : device.getReceivers()) {
        json.value(System.identityHashCode(receiver));
    }
    json.endArray();
    return json.toString();
}

From source file:de.hybris.platform.core.TenantRestartTest.java

private void assertEqualListeners(final InvalidationTopic topicAfter, final InvalidationTopic topicBefore) {
    final List<InvalidationListener> listenersBefore = getListenersViaReflection(topicBefore);
    final List<InvalidationListener> listenersAfter = getListenersViaReflection(topicAfter);

    Assertions.assertThat(listenersAfter.size()).isEqualTo(listenersBefore.size());

    final List<InvalidationListener> copyBefore = new ArrayList<InvalidationListener>(listenersBefore);
    for (final InvalidationListener before : listenersBefore) {
        final int hashBefore = System.identityHashCode(before);
        for (final InvalidationListener after : listenersAfter) {
            final int hashAfter = System.identityHashCode(after);
            if (hashAfter == hashBefore) {
                copyBefore.remove(before);
                break;
            }//w w  w .  ja  v a2 s . c om
        }

    }

    Assert.assertTrue(copyBefore.isEmpty());
}

From source file:com.redhat.example.rules.unittest.RuleFactWatcher.java

private void checkAttributes(String ruleName, Timing timing, Object actual, ExpectedRecord expect) {
    int id = System.identityHashCode(actual);
    for (Map.Entry<String, Object> entry : expect.map.entrySet()) {
        // filter out meta attributes
        if (!Constants.parentRowKey.equals(entry.getKey()) && !Constants.typeAttributeStr.equals(entry.getKey())
                && !testSkipMap.get(entry.getKey())) {
            String key = entry.getKey();
            Object expectedValueString = entry.getValue();
            Object actualValue = null;
            Object expectedValue = null;
            boolean toBeChecked = false;
            actualValue = getProperty(actual, key);
            if (!StringUtils.isEmpty((String) expectedValueString)) {
                toBeChecked = true;// w w w.  j a v a2s.  c om
                if (Constants.nullCheckStr.equals(expectedValueString)) {
                    expectedValue = null;
                } else if (Constants.emptyCheckStr.equals(expectedValueString)) {
                    expectedValue = "";
                } else {
                    expectedValue = getProperty(expect.fact, key);
                }
            }
            String keyValue = "";
            String attrName = key;
            String className = clazz.getSimpleName();
            String changeStr = null;
            if (toBeChecked) {
                if (actual instanceof MapEntry) {
                    if (attrName.startsWith(Constants.keyAttributeStr)) {
                        Object o = ((MapEntry) actual).key;
                        className = keyClass.getSimpleName();
                        id = System.identityHashCode(o);
                        attrName = "";
                    } else {
                        keyValue = ((MapEntry) actual).key.toString();
                        Object o = ((MapEntry) actual).value;
                        className = clazz.getSimpleName();
                        id = System.identityHashCode(o);
                        attrName = "";
                    }
                } else {
                    if (attrName.equals(Constants.valueAttributeStr) && isImmutable(actual.getClass())) {
                        attrName = "";
                    }
                }

                if (timing == Timing.BEFORE) {
                    registerValue(actual, attrName, actualValue);
                } else if (timing == Timing.AFTER) {
                    changeStr = getChangeString(actual, attrName, actualValue);
                    printAnAttribute(ruleName, className, id, attrName, changeStr, actualValue, expectedValue,
                            keyValue);
                } else { // (timing == Timing.INSERT)
                    registerValue(actual, attrName, Constants.unknownValueLavel);
                    changeStr = getChangeString(actual, attrName, actualValue);
                    printAnAttribute(ruleName, className, id, attrName, changeStr, actualValue, expectedValue,
                            keyValue);
                }
            }
        }
    }
}

From source file:org.mule.component.AbstractComponent.java

protected String getName() {
    StringBuffer sb = new StringBuffer();
    if (flowConstruct != null) {
        sb.append(flowConstruct.getName());
        sb.append(".");
    }//from  w ww .j a  v a2  s  .c o  m
    sb.append("component");
    if (!(flowConstruct instanceof Service || flowConstruct instanceof SimpleService)) {
        sb.append(".");
        sb.append(System.identityHashCode(this));
    }
    return sb.toString();
}

From source file:org.apache.hadoop.hdfs.client.ShortCircuitReplica.java

/**
 * Convert the replica to a string for debugging purposes.
 * Note that we can't take the lock here.
 *//*from  w ww  .j  a v  a  2 s. c  o m*/
@Override
public String toString() {
    return new StringBuilder().append("ShortCircuitReplica{").append("key=").append(key)
            .append(", metaHeader.version=").append(metaHeader.getVersion()).append(", metaHeader.checksum=")
            .append(metaHeader.getChecksum()).append(", ident=").append("0x")
            .append(Integer.toHexString(System.identityHashCode(this))).append(", creationTimeMs=")
            .append(creationTimeMs).append("}").toString();
}

From source file:org.apache.axis2.jaxws.runtime.description.marshal.impl.MarshalServiceRuntimeDescriptionImpl.java

/**
 * Java does not provide a way to uniquely identify an object.  This makes
 * it difficult to distinguish one object from another in a trace.  The
 * default Object.toString() produces a string of the form:
 * /*from   w ww. j a  v  a  2 s .c o  m*/
 *      obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode())
 * 
 * This is "as-good-as-it-gets".  If 'hashCode' has been overridden, it gets
 * worse. Specifically, if hashCode has been overriden such that:
 * 
 *      obj1.equals(obj2)  ==> obj1.hashCode() == obj2.hashCode()
 * 
 * then it becomes impossible to distinguish between obj1 and obj2 in a trace:
 * - dumping values is (almost) guaranteed to reveal that both have same content.
 * - dumping hashCode (see Object.toString() comment above) gives same hashCode.
 * 
 * [For example, JNDI Reference objects exhibit this behavior]
 * 
 * The purpose of getObjectIdentity is to attempt to duplicate the "original"
 * behavior of Object.toString().  On some JVMs, the 'original' hashCode
 * corresponds to a memory reference to the object - which is unique.
 * 
 * This is NOT guaranteed to work on all JVMs.  But again, this seems to be
 * "as-good-as-it-gets".
 *  
 * @return obj.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(obj));
 */
private static String getObjectIdentity(Object obj) {
    if (obj == null) {
        return "null";
    }
    return obj.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(obj));
}

From source file:org.vaadin.spring.events.internal.ScopedEventBus.java

@Override
public String toString() {
    return String.format("%s[id=%x, eventScope=%s, parentEventBus=%s]", getClass().getSimpleName(),
            System.identityHashCode(this), eventScope, parentEventBus);
}

From source file:org.apache.ranger.plugin.policyengine.RangerPolicyEngineImpl.java

@Override
public void preProcess(RangerAccessRequest request) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerPolicyEngineImpl.preProcess(" + request + ")");
    }/* w ww.  j  a  va2 s .c  om*/

    setResourceServiceDef(request);
    if (request instanceof RangerAccessRequestImpl) {
        ((RangerAccessRequestImpl) request).extractAndSetClientIPAddress(useForwardedIPAddress,
                trustedProxyAddresses);
    }

    RangerAccessRequestUtil.setCurrentUserInContext(request.getContext(), request.getUser());

    List<RangerContextEnricher> enrichers = allContextEnrichers;

    if (!CollectionUtils.isEmpty(enrichers)) {

        for (RangerContextEnricher enricher : enrichers) {

            RangerPerfTracer perf = null;

            if (RangerPerfTracer.isPerfTraceEnabled(PERF_CONTEXTENRICHER_REQUEST_LOG)) {
                perf = RangerPerfTracer.getPerfTracer(PERF_CONTEXTENRICHER_REQUEST_LOG,
                        "RangerContextEnricher.enrich(requestHashCode="
                                + Integer.toHexString(System.identityHashCode(request)) + ", enricherName="
                                + enricher.getName() + ")");
            }

            enricher.enrich(request);

            RangerPerfTracer.log(perf);
        }

    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerPolicyEngineImpl.preProcess(" + request + ")");
    }
}