protected SocketImpl swapSocketImpl(Socket socket, SocketImpl socketImpl) throws Exception {

    Field implField = ReflectionUtil.getDeclaredField(Socket.class, "impl");

    SocketImpl oldSocketImpl = (SocketImpl) implField.get(socket);

    if (socketImpl == null) {
      Socket unbindSocket = new Socket();

      socketImpl = (SocketImpl) implField.get(unbindSocket);

      Field cmdsockField = ReflectionUtil.getDeclaredField(socketImpl.getClass(), "cmdsock");

      cmdsockField.set(
          socketImpl,
          new Socket() {

            @Override
            public synchronized void close() throws IOException {
              throw new IOException();
            }
          });
    }

    implField.set(socket, socketImpl);

    return oldSocketImpl;
  }
            @Override
            public void map(
                ServiceReference<ModelAdapterBuilder> serviceReference, Emitter<String> emitter) {

              Registry registry = RegistryUtil.getRegistry();

              ModelAdapterBuilder modelAdapterBuilder = registry.getService(serviceReference);

              Type genericInterface =
                  ReflectionUtil.getGenericInterface(
                      modelAdapterBuilder, ModelAdapterBuilder.class);

              if ((genericInterface == null) || !(genericInterface instanceof ParameterizedType)) {

                return;
              }

              ParameterizedType parameterizedType = (ParameterizedType) genericInterface;

              Type[] typeArguments = parameterizedType.getActualTypeArguments();

              if (ArrayUtil.isEmpty(typeArguments) || (typeArguments.length != 2)) {

                return;
              }

              try {
                Class adapteeModelClass = (Class) typeArguments[0];
                Class adaptedModelClass = (Class) typeArguments[1];

                emitter.emit(getKey(adapteeModelClass, adaptedModelClass));
              } catch (ClassCastException cce) {
                return;
              }
            }
Exemple #3
0
  private Map<String, SchedulerResponse> _getMemoryClusteredJobs(
      ClusterSchedulerEngine clusterSchedulerEngine) throws Exception {

    Field field =
        ReflectionUtil.getDeclaredField(ClusterSchedulerEngine.class, "_memoryClusteredJobs");

    Map<String, ObjectValuePair<SchedulerResponse, TriggerState>> memoryJobs =
        (Map<String, ObjectValuePair<SchedulerResponse, TriggerState>>)
            field.get(clusterSchedulerEngine);

    if (memoryJobs.isEmpty()) {
      return Collections.emptyMap();
    }

    Map<String, SchedulerResponse> schedulerResponses =
        new HashMap<String, SchedulerResponse>(memoryJobs.size());

    for (String key : memoryJobs.keySet()) {
      ObjectValuePair<SchedulerResponse, TriggerState> value = memoryJobs.get(key);

      SchedulerResponse schedulerResponse = value.getKey();

      Message message = schedulerResponse.getMessage();

      TriggerState triggerState = value.getValue();

      message.put(SchedulerEngine.JOB_STATE, new JobState(triggerState));

      schedulerResponses.put(key, schedulerResponse);
    }

    return schedulerResponses;
  }
 static {
   try {
     _parentField = ReflectionUtil.getDeclaredField(Category.class, "parent");
   } catch (Exception e) {
     throw new ExceptionInInitializerError(e);
   }
 }
  public DDMFormFieldValueRendererRegistryImpl() {
    Class<?> clazz = getClass();

    Bundle bundle = FrameworkUtil.getBundle(clazz);

    _bundleContext = bundle.getBundleContext();

    Filter filter = null;

    try {
      filter =
          FrameworkUtil.createFilter(
              "(&(objectClass="
                  + DDMFormFieldValueRenderer.class.getName()
                  + ")(!(objectClass="
                  + clazz.getName()
                  + ")))");
    } catch (InvalidSyntaxException ise) {
      ReflectionUtil.throwException(ise);
    }

    _serviceTracker =
        new ServiceTracker<>(
            _bundleContext, filter, new DDMFormFieldValueRendererServiceTrackerCustomizer());

    _serviceTracker.open();
  }
Exemple #6
0
  public void init() throws TemplateException {
    if (_configuration != null) {
      return;
    }

    _configuration = new Configuration();

    try {
      Field field = ReflectionUtil.getDeclaredField(Configuration.class, "cache");

      TemplateCache templateCache = new LiferayTemplateCache(_configuration);

      field.set(_configuration, templateCache);
    } catch (Exception e) {
      throw new TemplateException("Unable to Initialize Freemarker manager");
    }

    _configuration.setDefaultEncoding(StringPool.UTF8);
    _configuration.setLocalizedLookup(PropsValues.FREEMARKER_ENGINE_LOCALIZED_LOOKUP);
    _configuration.setNewBuiltinClassResolver(new LiferayTemplateClassResolver());
    _configuration.setObjectWrapper(new LiferayObjectWrapper());

    try {
      _configuration.setSetting("auto_import", PropsValues.FREEMARKER_ENGINE_MACRO_LIBRARY);
      _configuration.setSetting(
          "template_exception_handler", PropsValues.FREEMARKER_ENGINE_TEMPLATE_EXCEPTION_HANDLER);
    } catch (Exception e) {
      throw new TemplateException("Unable to init freemarker manager", e);
    }
  }
  private static void _disableTransactions() throws Exception {
    if (_log.isDebugEnabled()) {
      _log.debug("Disable transactions");
    }

    PropsValues.SPRING_HIBERNATE_SESSION_DELEGATED = false;

    Field field = ReflectionUtil.getDeclaredField(ServiceBeanAopCacheManager.class, "_annotations");

    field.set(
        null,
        new HashMap<MethodInvocation, Annotation[]>() {

          @Override
          public Annotation[] get(Object key) {
            return _annotations;
          }

          private Annotation[] _annotations =
              new Annotation[] {
                new Skip() {

                  public Class<? extends Annotation> annotationType() {
                    return Skip.class;
                  }
                }
              };
        });
  }
  @Override
  public void addTaglibTheme(
      Map<String, Object> contextObjects,
      String themeName,
      HttpServletRequest request,
      HttpServletResponse response) {

    VelocityTaglib velocityTaglib =
        new VelocityTaglibImpl(request.getServletContext(), request, response, contextObjects);

    contextObjects.put(themeName, velocityTaglib);

    try {
      Class<?> clazz = VelocityTaglib.class;

      Method method = clazz.getMethod("layoutIcon", new Class[] {Layout.class});

      contextObjects.put("velocityTaglib_layoutIcon", method);
    } catch (Exception e) {
      ReflectionUtil.throwException(e);
    }

    // Legacy support

    contextObjects.put("theme", velocityTaglib);
  }
  @AdviseWith(adviceClasses = {PropsUtilAdvice.class})
  @Test
  public void testPrepareRequest() throws Exception {
    PropsUtilAdvice.setProps(
        PropsKeys.INTRABAND_MAILBOX_REAPER_THREAD_ENABLED, Boolean.FALSE.toString());
    PropsUtilAdvice.setProps(
        PropsKeys.INTRABAND_MAILBOX_STORAGE_LIFE, String.valueOf(Long.MAX_VALUE));

    Serializer serializer = new Serializer();

    serializer.writeString(_SERVLET_CONTEXT_NAME);
    serializer.writeObject(new SPIAgentRequest(_mockHttpServletRequest));

    Method depositMailMethod =
        ReflectionUtil.getDeclaredMethod(MailboxUtil.class, "depositMail", ByteBuffer.class);

    long receipt = (Long) depositMailMethod.invoke(null, serializer.toByteBuffer());

    byte[] data = new byte[8];

    BigEndianCodec.putLong(data, 0, receipt);

    HttpClientSPIAgent httpClientSPIAgent =
        new HttpClientSPIAgent(
            _spiConfiguration, new MockRegistrationReference(new MockIntraband()));

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();

    mockHttpServletRequest.setContent(data);

    HttpServletRequest httpServletRequest =
        httpClientSPIAgent.prepareRequest(mockHttpServletRequest);

    Assert.assertNotNull(httpServletRequest.getAttribute(WebKeys.SPI_AGENT_REQUEST));
  }
Exemple #10
0
  @BeforeClass
  public static void setUpClass() throws Exception {
    PortalUtil portalUtil = new PortalUtil();

    portalUtil.setPortal(new PortalImpl());

    PortalUUIDUtil portalUUIDUtil = new PortalUUIDUtil();

    portalUUIDUtil.setPortalUUID(new PortalUUIDImpl());

    Field field = ReflectionUtil.getDeclaredField(LockLocalServiceUtil.class, "_service");

    LockLocalService lockLocalService = new MockLockLocalService();

    field.set(null, lockLocalService);

    field = ClusterableContextThreadLocal.class.getDeclaredField("_contextThreadLocal");

    field.setAccessible(true);

    _threadLocalContext = (ThreadLocal<HashMap<String, Serializable>>) field.get(null);

    Method method = ClusterSchedulerEngine.class.getDeclaredMethod("delete", String.class);

    Clusterable clusterable = method.getAnnotation(Clusterable.class);

    Class<? extends ClusterInvokeAcceptor> clusterInvokeAcceptorClass = clusterable.acceptor();

    Constructor<? extends ClusterInvokeAcceptor> constructor =
        clusterInvokeAcceptorClass.getDeclaredConstructor();

    constructor.setAccessible(true);

    _clusterInvokeAcceptor = constructor.newInstance();
  }
Exemple #11
0
 static {
   try {
     _findClassMethod =
         ReflectionUtil.getDeclaredMethod(ClassLoader.class, "findClass", String.class);
     _getResourceMethod =
         ReflectionUtil.getDeclaredMethod(ClassLoader.class, "getResource", String.class);
     _getResourcesMethod =
         ReflectionUtil.getDeclaredMethod(ClassLoader.class, "getResources", String.class);
     _loadClassMethod =
         ReflectionUtil.getDeclaredMethod(
             ClassLoader.class, "loadClass", String.class, boolean.class);
   } catch (Exception e) {
     if (_log.isErrorEnabled()) {
       _log.error("Unable to locate required methods", e);
     }
   }
 }
 static {
   try {
     _shadowMatchCacheField =
         ReflectionUtil.getDeclaredField(AspectJExpressionPointcut.class, "shadowMatchCache");
   } catch (Exception e) {
     _log.error(e, e);
   }
 }
  private static MockIntraband getIntraband(
      IntrabandPortalCacheManager<?, ?> intraBandPortalCacheManager) throws Exception {

    Field intraBandField =
        ReflectionUtil.getDeclaredField(IntrabandPortalCacheManager.class, "_intraBand");

    return (MockIntraband) intraBandField.get(intraBandPortalCacheManager);
  }
  private static Map<String, PortalCache<?, ?>> getPortalCaches(
      IntrabandPortalCacheManager<?, ?> intraBandPortalCacheManager) throws Exception {

    Field intraBandField =
        ReflectionUtil.getDeclaredField(IntrabandPortalCacheManager.class, "_portalCaches");

    return (Map<String, PortalCache<?, ?>>) intraBandField.get(intraBandPortalCacheManager);
  }
Exemple #15
0
  @Before
  public void setUp() throws Exception {
    _jaasAuthTypeField =
        ReflectionUtil.getDeclaredField(PropsValues.class, "PORTAL_JAAS_AUTH_TYPE");

    _jaasAuthType = (String) _jaasAuthTypeField.get(null);

    _jaasEnabledField = ReflectionUtil.getDeclaredField(PropsValues.class, "PORTAL_JAAS_ENABLE");

    _jaasEnabled = (Boolean) _jaasEnabledField.get(null);

    _jaasEnabledField.set(null, true);

    Configuration.setConfiguration(new JAASConfiguration());

    _user = TestPropsValues.getUser();
  }
  private static MockRegistrationReference getRegistrationReference(
      IntrabandPortalCacheManager<?, ?> intraBandPortalCacheManager) throws Exception {

    Field registrationReferenceField =
        ReflectionUtil.getDeclaredField(
            IntrabandPortalCacheManager.class, "_registrationReference");

    return (MockRegistrationReference) registrationReferenceField.get(intraBandPortalCacheManager);
  }
  protected void closeSocketChannel(SocketChannel socketChannel, FileDescriptor fileDescriptor)
      throws Exception {

    Field fileDescriptorField = ReflectionUtil.getDeclaredField(socketChannel.getClass(), "fd");

    fileDescriptorField.set(socketChannel, fileDescriptor);

    socketChannel.close();
  }
  public BaseSourceProcessor() {
    portalSource = _isPortalSource();

    try {
      _properties = _getProperties();
    } catch (Exception e) {
      ReflectionUtil.throwException(e);
    }
  }
 static {
   try {
     _REPLICATION_THREAD_FIELD =
         ReflectionUtil.getDeclaredField(
             RMIAsynchronousCacheReplicator.class, "replicationThread");
   } catch (Exception e) {
     throw new ExceptionInInitializerError(e);
   }
 }
Exemple #20
0
  private boolean _isMaster(ClusterSchedulerEngine clusterSchedulerEngine) throws Exception {

    Field localClusterNodeAddressField =
        ReflectionUtil.getDeclaredField(ClusterSchedulerEngine.class, "_localClusterNodeAddress");

    String localClusterNodeAddress =
        (String) localClusterNodeAddressField.get(clusterSchedulerEngine);

    Lock lock = MockLockLocalService.getLock();

    return localClusterNodeAddress.equals(lock.getOwner());
  }
  private static void _enableTransactions() throws Exception {
    if (_log.isDebugEnabled()) {
      _log.debug("Enable transactions");
    }

    PropsValues.SPRING_HIBERNATE_SESSION_DELEGATED =
        GetterUtil.getBoolean(PropsUtil.get(PropsKeys.SPRING_HIBERNATE_SESSION_DELEGATED));

    Field field = ReflectionUtil.getDeclaredField(ServiceBeanAopCacheManager.class, "_annotations");

    field.set(null, new ConcurrentHashMap<MethodInvocation, Annotation[]>());
  }
  @Test
  public void testURLTemplateResourceExternalization() throws Exception {
    String templateId = "testId";

    Class<?> clazz = getClass();

    ClassLoader classLoader = clazz.getClassLoader();

    String resourcePath = clazz.getName();

    resourcePath = resourcePath.replace('.', '/') + ".class";

    URL url = classLoader.getResource(resourcePath);

    URLTemplateResource urlTemplateResource = new URLTemplateResource(templateId, url);

    // writeExternal

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    ObjectOutput objectOutput = new MockObjectOutput(unsyncByteArrayOutputStream);

    urlTemplateResource.writeExternal(objectOutput);

    objectOutput.close();

    byte[] externalizedData = unsyncByteArrayOutputStream.toByteArray();

    DataInputStream dataInputStream =
        new DataInputStream(new UnsyncByteArrayInputStream(externalizedData));

    Assert.assertEquals(templateId, dataInputStream.readUTF());
    Assert.assertEquals(url.toExternalForm(), dataInputStream.readUTF());

    // readExternal

    URLTemplateResource newURLTemplateResource = new URLTemplateResource();

    MockObjectInput mockObjectInput =
        new MockObjectInput(new DataInputStream(new UnsyncByteArrayInputStream(externalizedData)));

    newURLTemplateResource.readExternal(mockObjectInput);

    Assert.assertEquals(templateId, newURLTemplateResource.getTemplateId());

    Field templateURLField =
        ReflectionUtil.getDeclaredField(URLTemplateResource.class, "_templateURL");

    Assert.assertEquals(url, templateURLField.get(newURLTemplateResource));
  }
  public Configuration getConfiguration(String pid) {
    try {
      String pidFilter = _getPidFilterString(pid, false);

      Configuration[] configurations = _configurationAdmin.listConfigurations(pidFilter);

      if (configurations != null) {
        return configurations[0];
      }
    } catch (InvalidSyntaxException | IOException ise) {
      ReflectionUtil.throwException(ise);
    }

    return null;
  }
  protected static Class<?> loadClassDirectly(ClassLoader classLoader, String className)
      throws Exception {

    synchronized (classLoader) {
      Method findLoadedClassMethod =
          ReflectionUtil.getDeclaredMethod(ClassLoader.class, "findLoadedClass", String.class);

      Class<?> clazz = (Class<?>) findLoadedClassMethod.invoke(classLoader, className);

      if (clazz == null) {
        Method findClassMethod =
            ReflectionUtil.getDeclaredMethod(ClassLoader.class, "findClass", String.class);

        clazz = (Class<?>) findClassMethod.invoke(classLoader, className);
      }

      Method resolveClassMethod =
          ReflectionUtil.getDeclaredMethod(ClassLoader.class, "resolveClass", Class.class);

      resolveClassMethod.invoke(classLoader, clazz);

      return clazz;
    }
  }
  @Override
  public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {

    try {
      if (_layoutRevision == null) {
        return method.invoke(_layout, arguments);
      }

      String methodName = method.getName();

      if (methodName.equals("getLayoutType")) {
        return _getLayoutType();
      } else if (methodName.equals("toEscapedModel")) {
        if (_layout.isEscapedModel()) {
          return this;
        }

        return _toEscapedModel();
      }

      if (methodName.equals("clone")) {
        return _clone();
      }

      Object bean = _layout;

      if (_layoutRevisionMethodNames.contains(methodName)) {
        try {
          Class<?> layoutRevisionClass = _layoutRevision.getClass();

          method =
              layoutRevisionClass.getMethod(
                  methodName, ReflectionUtil.getParameterTypes(arguments));

          bean = _layoutRevision;
        } catch (NoSuchMethodException nsme) {
          _log.error(nsme, nsme);
        }
      }

      return method.invoke(bean, arguments);
    } catch (InvocationTargetException ite) {
      throw ite.getTargetException();
    }
  }
  @Test
  public void testCacheTemplateResourceExternalization() throws Exception {
    StringTemplateResource stringTemplateResource =
        new StringTemplateResource("testId", "testContent");

    CacheTemplateResource cacheTemplateResource = new CacheTemplateResource(stringTemplateResource);

    // writeExternal

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    ObjectOutput objectOutput = new ObjectOutputStream(unsyncByteArrayOutputStream);

    cacheTemplateResource.writeExternal(objectOutput);

    objectOutput.close();

    byte[] externalizedData = unsyncByteArrayOutputStream.toByteArray();

    ObjectInput objectInput =
        new ObjectInputStream(new UnsyncByteArrayInputStream(externalizedData));

    Assert.assertEquals(cacheTemplateResource.getLastModified(), objectInput.readLong());
    Assert.assertEquals(stringTemplateResource, objectInput.readObject());

    // readExternal

    CacheTemplateResource newCacheTemplateResource = new CacheTemplateResource();

    objectInput = new ObjectInputStream(new UnsyncByteArrayInputStream(externalizedData));

    newCacheTemplateResource.readExternal(objectInput);

    Field templateResourceField =
        ReflectionUtil.getDeclaredField(CacheTemplateResource.class, "_templateResource");

    Assert.assertEquals(
        stringTemplateResource, templateResourceField.get(newCacheTemplateResource));

    Assert.assertEquals(
        cacheTemplateResource.getLastModified(), newCacheTemplateResource.getLastModified());
  }
  public void afterPropertiesSet() {
    String configurationPath = PropsUtil.get(_configPropertyKey);

    if (Validator.isNull(configurationPath)) {
      configurationPath = _DEFAULT_CLUSTERED_EHCACHE_CONFIG_FILE;
    }

    boolean usingDefault = configurationPath.equals(_DEFAULT_CLUSTERED_EHCACHE_CONFIG_FILE);

    Configuration configuration =
        EhcacheConfigurationUtil.getConfiguration(configurationPath, _clusterAware, usingDefault);

    _cacheManager = new CacheManager(configuration);

    FailSafeTimer failSafeTimer = _cacheManager.getTimer();

    failSafeTimer.cancel();

    try {
      Field cacheManagerTimerField =
          ReflectionUtil.getDeclaredField(CacheManager.class, "cacheManagerTimer");

      cacheManagerTimerField.set(_cacheManager, null);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    if (PropsValues.EHCACHE_PORTAL_CACHE_MANAGER_JMX_ENABLED) {
      _managementService =
          new ManagementService(
              _cacheManager,
              _mBeanServer,
              _registerCacheManager,
              _registerCaches,
              _registerCacheConfigurations,
              _registerCacheStatistics);

      _managementService.init();
    }
  }
  protected String getDDMFormFieldValueString(DDMFormFieldValue ddmFormFieldValue) {

    Value value = ddmFormFieldValue.getValue();

    String valueString = value.getString(_locale);

    String type = getDDMFormFieldType(ddmFormFieldValue.getName());

    if (type.equals(DDMFormFieldType.SELECT)) {
      try {
        JSONArray jsonArray = _jsonFactory.createJSONArray(valueString);

        if (jsonArray.length() == 1) {
          valueString = jsonArray.getString(0);
        }
      } catch (JSONException je) {
        ReflectionUtil.throwException(je);
      }
    }

    return valueString;
  }
Exemple #29
0
  public static Properties loadJDK6(Reader reader) throws IOException {
    try {
      Properties properties = new Properties();

      if (_jdk6LoadMethod == null) {
        _jdk6LoadMethod = ReflectionUtil.getDeclaredMethod(Properties.class, "load", Reader.class);
      }

      _jdk6LoadMethod.invoke(properties, reader);

      return properties;
    } catch (Exception e) {
      Throwable cause = e.getCause();

      if (cause instanceof IOException) {
        throw (IOException) cause;
      }

      throw new IllegalStateException(
          "Failed to invoke java.util.Properties.load(Reader reader)", e);
    }
  }
  @Override
  public void init() throws TemplateException {
    if (_configuration != null) {
      return;
    }

    _configuration = new Configuration();

    try {
      Field field = ReflectionUtil.getDeclaredField(Configuration.class, "cache");

      TemplateCache templateCache =
          new LiferayTemplateCache(
              _configuration, _freemarkerEngineConfiguration, templateResourceLoader);

      field.set(_configuration, templateCache);
    } catch (Exception e) {
      throw new TemplateException("Unable to Initialize FreeMarker manager");
    }

    _configuration.setDefaultEncoding(StringPool.UTF8);
    _configuration.setLocalizedLookup(_freemarkerEngineConfiguration.localizedLookup());
    _configuration.setNewBuiltinClassResolver(_templateClassResolver);
    _configuration.setObjectWrapper(new LiferayObjectWrapper());

    try {
      _configuration.setSetting(
          "auto_import", StringUtil.merge(_freemarkerEngineConfiguration.macroLibrary()));
      _configuration.setSetting(
          "template_exception_handler", _freemarkerEngineConfiguration.templateExceptionHandler());
    } catch (Exception e) {
      throw new TemplateException("Unable to init FreeMarker manager", e);
    }

    if (isEnableDebuggerService()) {
      DebuggerService.getBreakpoints("*");
    }
  }