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;
  }
Exemplo n.º 2
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;
  }
Exemplo n.º 3
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();
  }
Exemplo n.º 4
0
 static {
   try {
     _parentField = ReflectionUtil.getDeclaredField(Category.class, "parent");
   } catch (Exception e) {
     throw new ExceptionInInitializerError(e);
   }
 }
Exemplo n.º 5
0
  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;
                  }
                }
              };
        });
  }
Exemplo n.º 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);
    }
  }
Exemplo n.º 7
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 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);
  }
 static {
   try {
     _shadowMatchCacheField =
         ReflectionUtil.getDeclaredField(AspectJExpressionPointcut.class, "shadowMatchCache");
   } catch (Exception e) {
     _log.error(e, e);
   }
 }
 static {
   try {
     _REPLICATION_THREAD_FIELD =
         ReflectionUtil.getDeclaredField(
             RMIAsynchronousCacheReplicator.class, "replicationThread");
   } catch (Exception e) {
     throw new ExceptionInInitializerError(e);
   }
 }
  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();
  }
Exemplo n.º 14
0
  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[]>());
  }
Exemplo n.º 15
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());
  }
  @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));
  }
  @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();
    }
  }
  @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("*");
    }
  }
  @Test
  public void testTransferResponse() throws Exception {

    // Exception

    MockRegistrationReference mockRegistrationReference =
        new MockRegistrationReference(new MockIntraband());

    HttpClientSPIAgent httpClientSPIAgent =
        new HttpClientSPIAgent(_spiConfiguration, mockRegistrationReference);

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();

    mockHttpServletRequest.setAttribute(
        WebKeys.SPI_AGENT_REQUEST, new SPIAgentRequest(_mockHttpServletRequest));

    RecordSPIAgentResponse recordSPIAgentResponse = new RecordSPIAgentResponse();

    mockHttpServletRequest.setAttribute(WebKeys.SPI_AGENT_RESPONSE, recordSPIAgentResponse);

    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    mockHttpServletRequest.setAttribute(
        WebKeys.SPI_AGENT_ORIGINAL_RESPONSE, mockHttpServletResponse);

    Exception exception = new Exception();

    httpClientSPIAgent.transferResponse(
        mockHttpServletRequest,
        new BufferCacheServletResponse(new MockHttpServletResponse()),
        exception);

    Assert.assertNull(mockHttpServletRequest.getAttribute(WebKeys.SPI_AGENT_REQUEST));
    Assert.assertNull(mockHttpServletRequest.getAttribute(WebKeys.SPI_AGENT_RESPONSE));
    Assert.assertSame(exception, recordSPIAgentResponse.exception);
    Assert.assertNull(mockHttpServletRequest.getAttribute(WebKeys.SPI_AGENT_ORIGINAL_RESPONSE));
    Assert.assertEquals(8, mockHttpServletResponse.getContentLength());
    Assert.assertNull(recordSPIAgentResponse._request);
    Assert.assertNull(recordSPIAgentResponse._bufferCacheServletResponse);
    Assert.assertSame(mockRegistrationReference, recordSPIAgentResponse._registrationReference);
    Assert.assertSame(
        mockHttpServletResponse.getOutputStream(), recordSPIAgentResponse._outputStream);

    // Response

    SPIAgentRequest spiAgentRequest = new SPIAgentRequest(_mockHttpServletRequest);

    File tempFile = File.createTempFile(HttpClientSPIAgentTest.class.getName(), null);

    Assert.assertTrue(tempFile.exists());

    spiAgentRequest.requestBodyFile = tempFile;

    mockHttpServletRequest.setAttribute(WebKeys.SPI_AGENT_REQUEST, spiAgentRequest);

    recordSPIAgentResponse = new RecordSPIAgentResponse();

    mockHttpServletRequest.setAttribute(WebKeys.SPI_AGENT_RESPONSE, recordSPIAgentResponse);

    mockHttpServletResponse = new MockHttpServletResponse();

    mockHttpServletRequest.setAttribute(
        WebKeys.SPI_AGENT_ORIGINAL_RESPONSE, mockHttpServletResponse);

    BufferCacheServletResponse bufferCacheServletResponse =
        new BufferCacheServletResponse(new MockHttpServletResponse());

    httpClientSPIAgent.transferResponse(mockHttpServletRequest, bufferCacheServletResponse, null);

    Assert.assertFalse(tempFile.exists());
    Assert.assertNull(mockHttpServletRequest.getAttribute(WebKeys.SPI_AGENT_REQUEST));
    Assert.assertNull(mockHttpServletRequest.getAttribute(WebKeys.SPI_AGENT_RESPONSE));
    Assert.assertNull(recordSPIAgentResponse.exception);
    Assert.assertNull(mockHttpServletRequest.getAttribute(WebKeys.SPI_AGENT_ORIGINAL_RESPONSE));
    Assert.assertEquals(8, mockHttpServletResponse.getContentLength());
    Assert.assertSame(mockHttpServletRequest, recordSPIAgentResponse._request);
    Assert.assertSame(
        bufferCacheServletResponse, recordSPIAgentResponse._bufferCacheServletResponse);
    Assert.assertSame(mockRegistrationReference, recordSPIAgentResponse._registrationReference);
    Assert.assertSame(
        mockHttpServletResponse.getOutputStream(), recordSPIAgentResponse._outputStream);

    // Undeletable request body file

    spiAgentRequest = new SPIAgentRequest(_mockHttpServletRequest);

    tempFile = File.createTempFile(HttpClientSPIAgentTest.class.getName(), null);

    Assert.assertTrue(tempFile.exists());

    spiAgentRequest.requestBodyFile = tempFile;

    mockHttpServletRequest.setAttribute(WebKeys.SPI_AGENT_REQUEST, spiAgentRequest);

    recordSPIAgentResponse = new RecordSPIAgentResponse();

    mockHttpServletRequest.setAttribute(WebKeys.SPI_AGENT_RESPONSE, recordSPIAgentResponse);

    mockHttpServletResponse = new MockHttpServletResponse();

    mockHttpServletRequest.setAttribute(
        WebKeys.SPI_AGENT_ORIGINAL_RESPONSE, mockHttpServletResponse);

    bufferCacheServletResponse = new BufferCacheServletResponse(new MockHttpServletResponse());

    Assert.assertTrue(tempFile.delete());

    httpClientSPIAgent.transferResponse(mockHttpServletRequest, bufferCacheServletResponse, null);

    Class<?> clazz = Class.forName("java.io.DeleteOnExitHook");

    Field filesField = ReflectionUtil.getDeclaredField(clazz, "files");

    Set<String> files = (Set<String>) filesField.get(null);

    Assert.assertTrue(files.contains(tempFile.getPath()));
  }