private void establishSecurityContext(InvocationRequest invocation) throws Exception {
    SecurityContext newSC = SecurityActions.createAndSetSecurityContext(securityDomain);

    // Set the SecurityManagement on the context
    SecurityActions.setSecurityManagement(newSC, securityManagement);
    log.trace("establishSecurityIdentity:SecCtx=" + SecurityActions.trace(newSC));
  }
Example #2
0
 /** Publishes the endpoints declared to the provided WSEndpointDeploymentUnit */
 public List<Endpoint> publish(ServiceTarget target, WSEndpointDeploymentUnit unit)
     throws Exception {
   List<DeploymentAspect> aspects = DeploymentAspectsProvider.getSortedDeploymentAspects();
   ClassLoader origClassLoader = SecurityActions.getContextClassLoader();
   Deployment dep = null;
   try {
     SecurityActions.setContextClassLoader(
         ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader());
     WSDeploymentBuilder.getInstance().build(unit);
     dep = unit.getAttachment(WSAttachmentKeys.DEPLOYMENT_KEY);
     dep.addAttachment(ServiceTarget.class, target);
     DeploymentAspectManager dam = new DeploymentAspectManagerImpl();
     dam.setDeploymentAspects(aspects);
     dam.deploy(dep);
   } finally {
     if (dep != null) {
       dep.removeAttachment(ServiceTarget.class);
     }
     SecurityActions.setContextClassLoader(origClassLoader);
   }
   Deployment deployment = unit.getAttachment(WSAttachmentKeys.DEPLOYMENT_KEY);
   deployment.addAttachment(
       StandardContext.class,
       startWebApp(host, unit)); // TODO simplify and use findChild later in destroy()/stopWebApp()
   return deployment.getService().getEndpoints();
 }
  /**
   * Obtains the username/password credentials from the environment
   *
   * @return
   */
  private static UsernamePasswordCredentials getCredentials() {
    // Obtain the username and password
    final String username = SecurityActions.getEnvironmentVariable(ENV_VAR_NAME_TWITTER_USERNAME);
    final String password = SecurityActions.getEnvironmentVariable(ENV_VAR_NAME_TWITTER_PASSWORD);

    // Return as unified view
    final UsernamePasswordCredentials creds = new UsernamePasswordCredentials();
    creds.username = username;
    creds.password = password;
    return creds;
  }
  protected void verifyPassword(VerifyPasswordCallback vpc) throws NamingException {
    String credential = vpc.getValue();

    ClassLoader currentTCCL = SecurityActions.getContextClassLoader();
    if (currentTCCL != null) SecurityActions.setContextClassLoader(null);

    String baseDN = options.get(BASE_CTX_DN);
    String baseFilter = options.get(BASE_FILTER_OPT);

    InitialLdapContext ctx = this.constructInitialLdapContext(bindDN, bindCredential);
    bindDNAuthentication(ctx, userName, credential, baseDN, baseFilter);
    vpc.setVerified(true);
  }
 /**
  * Stops the container
  *
  * @throws IllegalStateException if the container is not running
  */
 public synchronized void stop() {
   if (!started) {
     throw WeldMessages.MESSAGES.notStarted("WeldContainer");
   }
   ClassLoader oldTccl = SecurityActions.getContextClassLoader();
   try {
     SecurityActions.setContextClassLoader(deployment.getModule().getClassLoader());
     bootstrap.shutdown();
   } finally {
     SecurityActions.setContextClassLoader(oldTccl);
     ModuleGroupSingletonProvider.removeClassLoader(deployment.getModule().getClassLoader());
   }
   started = false;
 }
Example #6
0
  /**
   * Utility method which loads the given properties file and returns a Properties object containing
   * the key,value pairs in that file. The properties files should be in the class path as this
   * method looks to the thread context class loader (TCL) to locate the resource. If the TCL is a
   * URLClassLoader the findResource(String) method is first tried. If this fails or the TCL is not
   * a URLClassLoader getResource(String) is tried. If not, an absolute path is tried.
   *
   * @param propertiesName - the name of the properties file resource
   * @return the loaded properties file if found
   * @exception java.io.IOException thrown if the properties file cannot be found or loaded
   */
  static Properties loadProperties(String propertiesName) throws IOException {
    Properties bundle = null;
    ClassLoader loader = SecurityActions.getContextClassLoader();
    URL url = null;
    // First check for local visibility via a URLClassLoader.findResource
    if (loader instanceof URLClassLoader) {
      URLClassLoader ucl = (URLClassLoader) loader;
      url = SecurityActions.findResource(ucl, propertiesName);
      PicketBoxLogger.LOGGER.traceAttemptToLoadResource(propertiesName);
    }
    // Do a general resource search
    if (url == null) {
      url = loader.getResource(propertiesName);
      if (url == null) {
        try {
          url = new URL(propertiesName);
        } catch (MalformedURLException mue) {
          PicketBoxLogger.LOGGER.debugFailureToOpenPropertiesFromURL(mue);
          File tmp = new File(propertiesName);
          if (tmp.exists()) url = tmp.toURI().toURL();
        }
      }
    }
    if (url == null) {
      throw PicketBoxMessages.MESSAGES.unableToFindPropertiesFile(propertiesName);
    }

    Properties defaults = new Properties();
    bundle = new Properties(defaults);
    if (url != null) {
      InputStream is = null;
      try {
        is = SecurityActions.openStream(url);
      } catch (PrivilegedActionException e) {
        throw new IOException(e.getLocalizedMessage());
      }
      if (is != null) {
        try {
          bundle.load(is);
        } finally {
          safeClose(is);
        }
      } else {
        throw PicketBoxMessages.MESSAGES.unableToLoadPropertiesFile(propertiesName);
      }
      PicketBoxLogger.LOGGER.tracePropertiesFileLoaded(propertiesName, bundle.keySet());
    }

    return bundle;
  }
Example #7
0
  public synchronized void start(StartContext context) throws StartException {
    try {
      final JMSServerManager jmsServer =
          new JMSServerManagerImpl(
              hornetQServer.getValue(),
              new AS7BindingRegistry(context.getController().getServiceContainer()));

      try {
        // FIXME - we also need the TCCL here in case the JMSServerManager starts the HornetQServer
        final ClassLoader loader = getClass().getClassLoader();
        SecurityActions.setContextClassLoader(loader);
        jmsServer.start();

        // FIXME - this check is a work-around for AS7-3658
        if (!hornetQServer.getValue().getConfiguration().isBackup()) {
          hornetQServer
              .getValue()
              .getRemotingService()
              .allowInvmSecurityOverride(
                  new HornetQPrincipal(
                      HornetQDefaultCredentials.getUsername(),
                      HornetQDefaultCredentials.getPassword()));
        } else {
          hornetQServer
              .getValue()
              .registerActivateCallback(
                  new ActivateCallback() {
                    public void preActivate() {}

                    public void activated() {
                      hornetQServer
                          .getValue()
                          .getRemotingService()
                          .allowInvmSecurityOverride(
                              new HornetQPrincipal(
                                  HornetQDefaultCredentials.getUsername(),
                                  HornetQDefaultCredentials.getPassword()));
                    }

                    public void deActivate() {}
                  });
        }
      } finally {
        SecurityActions.setContextClassLoader(null);
      }
      this.jmsServer = jmsServer;
    } catch (Exception e) {
      throw new StartException(e);
    }
  }
Example #8
0
  /**
   * System property substitution
   *
   * @param input The input string
   * @return The output
   */
  private String getSubstitutionValue(String input) throws XMLStreamException {
    if (input == null || input.trim().equals("")) return input;
    while ((input.indexOf("${")) != -1) {
      int from = input.indexOf("${");
      int to = input.indexOf("}");
      int dv = input.indexOf(":", from + 2);

      if (dv != -1) {
        if (dv > to) dv = -1;
      }

      String systemProperty = "";
      String defaultValue = "";
      String s = input.substring(from + 2, to);
      if (dv == -1) {
        if ("/".equals(s)) {
          systemProperty = File.separator;
        } else if (":".equals(s)) {
          systemProperty = File.pathSeparator;
        } else {
          systemProperty = SecurityActions.getSystemProperty(s);
        }
      } else {
        s = input.substring(from + 2, dv);
        systemProperty = SecurityActions.getSystemProperty(s);
        defaultValue = input.substring(dv + 1, to);
      }
      String prefix = "";
      String postfix = "";

      if (from != 0) {
        prefix = input.substring(0, from);
      }

      if (to + 1 < input.length() - 1) {
        postfix = input.substring(to + 1);
      }

      if (systemProperty != null && !systemProperty.trim().equals("")) {
        input = prefix + systemProperty + postfix;
      } else if (defaultValue != null && !defaultValue.trim().equals("")) {
        input = prefix + defaultValue + postfix;
      } else {
        input = prefix + postfix;
        log.debugf("System property %s not set", s);
      }
    }
    return input;
  }
 /**
  * Makes a dynamic stub class, if it does not already exist.
  *
  * @param myClass The class to create a stub for
  * @return The dynamic stub class
  */
 public static Class<?> makeStubClass(final Class<?> myClass) {
   final String stubClassName = myClass + "_Stub";
   ClassLoader cl = SecurityActions.getContextClassLoader();
   if (cl == null) {
     cl = myClass.getClassLoader();
   }
   if (cl == null) {
     throw EjbMessages.MESSAGES.couldNotFindClassLoaderForStub(stubClassName);
   }
   Class<?> theClass;
   try {
     theClass = cl.loadClass(stubClassName);
   } catch (ClassNotFoundException e) {
     try {
       final ClassFile clazz = IIOPStubCompiler.compile(myClass, stubClassName);
       theClass = clazz.define(cl);
     } catch (RuntimeException ex) {
       // there is a possibility that another thread may have defined the same class in the
       // meantime
       try {
         theClass = cl.loadClass(stubClassName);
       } catch (ClassNotFoundException e1) {
         EjbLogger.EJB3_LOGGER.dynamicStubCreationFailed(stubClassName, ex);
         throw ex;
       }
     }
   }
   return theClass;
 }
Example #10
0
 private ObjectFactory factoryFromReference(
     final Reference reference, final Hashtable<?, ?> environment) throws Exception {
   if (reference instanceof ModularReference) {
     return factoryFromModularReference(ModularReference.class.cast(reference), environment);
   }
   return factoryFromReference(reference, SecurityActions.getContextClassLoader(), environment);
 }
Example #11
0
 /**
  * Create a new {@link DatatypeFactory}
  *
  * @return
  * @throws DatatypeConfigurationException
  */
 public static DatatypeFactory newDatatypeFactory() throws DatatypeConfigurationException {
   boolean tccl_jaxp =
       SystemPropertiesUtil.getSystemProperty(GeneralConstants.TCCL_JAXP, "false")
           .equalsIgnoreCase("true");
   ClassLoader prevTCCL = SecurityActions.getTCCL();
   try {
     if (tccl_jaxp) {
       SecurityActions.setTCCL(XMLTimeUtil.class.getClassLoader());
     }
     return DatatypeFactory.newInstance();
   } finally {
     if (tccl_jaxp) {
       SecurityActions.setTCCL(prevTCCL);
     }
   }
 }
Example #12
0
  /**
   * Validate
   *
   * @param vo The validate object
   * @param rb The resource bundle
   * @return The list of failures found; <code>null</code> if none
   */
  @SuppressWarnings("unchecked")
  public List<Failure> validate(Validate vo, ResourceBundle rb) {
    if (vo != null
        && Key.MANAGED_CONNECTION_FACTORY == vo.getKey()
        && vo.getClazz() != null
        && ManagedConnectionFactory.class.isAssignableFrom(vo.getClazz())) {
      boolean error = true;
      Class clz = vo.getClazz();

      while (error && !clz.equals(Object.class)) {
        try {
          SecurityActions.getDeclaredMethod(clz, "hashCode", (Class[]) null);
          error = false;
        } catch (Throwable t) {
          clz = clz.getSuperclass();
        }
      }

      if (error) {
        List<Failure> failures = new ArrayList<Failure>(1);

        Failure failure =
            new Failure(
                Severity.ERROR, SECTION, rb.getString("mcf.MCFHashCode"), vo.getClazz().getName());
        failures.add(failure);

        return failures;
      }
    }

    return null;
  }
 public void stop() {
   ClassLoader old = getTccl();
   try {
     setTccl(servletContext.getClassLoader());
     this.started = false;
     final Map<String, SessionPersistenceManager.PersistentSession> objectData = new HashMap<>();
     for (String sessionId : sessionManager.getTransientSessions()) {
       Session session = sessionManager.getSession(sessionId);
       if (session != null) {
         final HttpSessionEvent event =
             new HttpSessionEvent(SecurityActions.forSession(session, servletContext, false));
         final Map<String, Object> sessionData = new HashMap<>();
         for (String attr : session.getAttributeNames()) {
           final Object attribute = session.getAttribute(attr);
           sessionData.put(attr, attribute);
           if (attribute instanceof HttpSessionActivationListener) {
             ((HttpSessionActivationListener) attribute).sessionWillPassivate(event);
           }
         }
         objectData.put(
             sessionId,
             new PersistentSession(
                 new Date(
                     session.getLastAccessedTime() + (session.getMaxInactiveInterval() * 1000)),
                 sessionData));
       }
     }
     sessionPersistenceManager.persistSessions(deploymentName, objectData);
     this.data.clear();
   } finally {
     setTccl(old);
   }
 }
 // [TODO] Remove this hack when the TCK setup can configure the subsystem properly
 Object getPropertyWithSystemFallback(Map<String, Object> props, String key) {
   Object value = props.get(key);
   if (value == null) {
     value = SecurityActions.getSystemProperty(key);
   }
   return value;
 }
Example #15
0
  @Override
  public byte[] query(AdvancedCache<byte[], byte[]> cache, byte[] query) {
    try {
      SerializationContext serCtx =
          ProtobufMetadataManagerImpl.getSerializationContextInternal(cache.getCacheManager());
      QueryRequest request =
          ProtobufUtil.fromByteArray(serCtx, query, 0, query.length, QueryRequest.class);

      Configuration cacheConfiguration = SecurityActions.getCacheConfiguration(cache);
      boolean isIndexed = cacheConfiguration.indexing().index().isEnabled();
      boolean isCompatMode = cacheConfiguration.compatibility().enabled();
      SearchManager searchManager =
          isIndexed ? Search.getSearchManager(cache) : null; // this also checks access permissions
      RemoteQueryEngine queryEngine =
          new RemoteQueryEngine(cache, searchManager, isCompatMode, serCtx);

      long startOffset = request.getStartOffset() == null ? -1 : request.getStartOffset();
      int maxResults = request.getMaxResults() == null ? -1 : request.getMaxResults();
      Map<String, Object> namedParameters = getNamedParameters(request);
      Query q =
          queryEngine.buildQuery(
              null, request.getJpqlString(), namedParameters, startOffset, maxResults);

      QueryResponse response = makeResponse(q);
      return ProtobufUtil.toByteArray(serCtx, response);
    } catch (IOException e) {
      throw log.errorExecutingQuery(e);
    }
  }
 /**
  * Creates an {@link EJBInvocationHandler} for the passed <code>locator</code> and associates this
  * invocation handler with the passed <code>ejbClientContextIdentifier</code>
  *
  * @param ejbClientContextIdentifier (Optional) EJB client context identifier. Can be null.
  * @param locator The {@link EJBLocator} cannot be null.
  */
 EJBInvocationHandler(
     final EJBClientContextIdentifier ejbClientContextIdentifier, final EJBLocator<T> locator) {
   if (locator == null) {
     throw Logs.MAIN.paramCannotBeNull("EJB locator");
   }
   this.ejbClientContextIdentifier = ejbClientContextIdentifier;
   this.locator = locator;
   async = false;
   if (locator instanceof StatefulEJBLocator) {
     // set the weak affinity to the node on which the session was created
     final String sessionOwnerNode = ((StatefulEJBLocator) locator).getSessionOwnerNode();
     if (sessionOwnerNode != null) {
       this.setWeakAffinity(new NodeAffinity(sessionOwnerNode));
     }
   }
   // scan for annotations on the view class, if necessary
   final String annotationScanEnabledSysPropVal =
       SecurityActions.getSystemProperty(ENABLE_ANNOTATION_SCANNING_SYSTEM_PROPERTY);
   if (annotationScanEnabledSysPropVal != null
       && Boolean.valueOf(annotationScanEnabledSysPropVal.trim())) {
     scanAnnotationsOnViewClass();
   } else {
     // let's for the sake of potential performance optimization, add an attachment which lets the
     // EJBReceiver(s) and any other decision making
     // code to decide whether it can entirely skip any logic related to "hints" (like
     // @org.jboss.ejb.client.annotation.CompressionHint)
     putAttachment(AttachmentKeys.HINTS_DISABLED, true);
   }
 }
Example #17
0
  /**
   * Get the system property value if the string is of the format ${sysproperty}
   *
   * <p>You can insert default value when the system property is not set, by separating it at the
   * beginning with ::
   *
   * <p><b>Examples:</b>
   *
   * <p>${idp} should resolve to a value if the system property "idp" is set.
   *
   * <p>${idp::http://localhost:8080} will resolve to http://localhost:8080 if the system property
   * "idp" is not set.
   *
   * @param str
   * @return
   */
  public static String getSystemPropertyAsString(String str) {
    if (str == null) throw logger.nullArgumentError("str");
    if (str.contains("${")) {
      Pattern pattern = Pattern.compile("\\$\\{([^}]+)}");
      Matcher matcher = pattern.matcher(str);

      StringBuffer buffer = new StringBuffer();
      String sysPropertyValue = null;

      while (matcher.find()) {
        String subString = matcher.group(1);
        String defaultValue = "";

        // Look for default value
        if (subString.contains("::")) {
          int index = subString.indexOf("::");
          defaultValue = subString.substring(index + 2);
          subString = subString.substring(0, index);
        }
        sysPropertyValue = SecurityActions.getSystemProperty(subString, defaultValue);
        if (sysPropertyValue.isEmpty()) {
          throw logger.systemPropertyMissingError(matcher.group(1));
        }
        matcher.appendReplacement(buffer, sysPropertyValue);
      }

      matcher.appendTail(buffer);
      str = buffer.toString();
    }
    return str;
  }
Example #18
0
 private Iterable<Metadata<Extension>> getExtensions(
     ClassLoader classLoader, Bootstrap bootstrap) {
   Set<Metadata<Extension>> result = new HashSet<Metadata<Extension>>();
   if (discoveryEnabled) {
     Iterables.addAll(result, bootstrap.loadExtensions(classLoader));
   }
   if (!extensions.isEmpty()) {
     result.addAll(extensions);
   }
   // Ensure that WeldSEBeanRegistrant is present
   WeldSEBeanRegistrant weldSEBeanRegistrant = null;
   for (Metadata<Extension> metadata : result) {
     if (metadata.getValue().getClass().getName().equals(WeldSEBeanRegistrant.class.getName())) {
       weldSEBeanRegistrant = (WeldSEBeanRegistrant) metadata.getValue();
       break;
     }
   }
   if (weldSEBeanRegistrant == null) {
     try {
       weldSEBeanRegistrant = SecurityActions.newInstance(WeldSEBeanRegistrant.class);
       result.add(
           new MetadataImpl<Extension>(
               weldSEBeanRegistrant,
               SYNTHETIC_LOCATION_PREFIX + WeldSEBeanRegistrant.class.getName()));
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
   if (!beanBuilders.isEmpty()) {
     weldSEBeanRegistrant.setBeanBuilders(beanBuilders);
   }
   return result;
 }
 public HttpSession getSession(final String sessionId) {
   final SessionManager sessionManager = context.getDeployment().getSessionManager();
   Session session = sessionManager.getSession(sessionId);
   if (session != null) {
     return SecurityActions.forSession(session, this, false, sessionManager);
   }
   return null;
 }
  private EntitiesDescriptorType parseMDFile() throws ParsingException {
    InputStream is = SecurityActions.loadStream(getClass(), SP_MD_FILE);

    if (is == null) throw logger.nullValueError(SP_MD_FILE);

    SAMLParser parser = new SAMLParser();
    return (EntitiesDescriptorType) parser.parse(is);
  }
 public void stop() {
   log.debug("stop");
   try {
     SecurityActions.shutdownScheduler(sched);
   } catch (SchedulerException e) {
     throw new RuntimeException(e);
   }
 }
Example #22
0
 /**
  * Invokes this method with the provided arguments applying provided mapper
  *
  * @param args object
  * @param mapper if null no mappings are applied method will be invoked using args directly. in
  *     this case the keys of the map gotta be the parameters names as defined in wsdl/wsconsume
  *     generated classes
  * @return {@link InvocationResultImpl}
  * @throws WiseWebServiceException There are 4 known failure conditions - The wsdl (url) could not
  *     be found - The wsdl is password protected - The endpoint (url) could not be found - The
  *     endpoint is password protected
  * @throws InvocationException invocation issue
  * @throws IllegalArgumentException illegal argument
  * @throws MappingException mapping issue
  */
 @SuppressWarnings("unchecked")
 public InvocationResultImpl invoke(Object args, WiseMapper mapper)
     throws WiseWebServiceException, InvocationException, IllegalArgumentException,
         MappingException {
   if (mapper == null) {
     return this.invoke((Map<String, Object>) args);
   }
   ClassLoader oldLoader = SecurityActions.getContextClassLoader();
   Map<String, Object> mappingResults;
   try {
     SecurityActions.setContextClassLoader(this.getEndpoint().getClassLoader());
     mappingResults = mapper.applyMapping(args);
   } finally {
     SecurityActions.setContextClassLoader(oldLoader);
   }
   return this.invoke(mappingResults);
 }
  public HttpSession getSession(
      final ServletContextImpl originalServletContext,
      final HttpServerExchange exchange,
      boolean create) {
    SessionConfig c = originalServletContext.getSessionConfig();
    ConvergedHttpSessionFacade httpSession = exchange.getAttachment(sessionAttachmentKey);
    if (httpSession != null && httpSession.isValidIntern()) {
      exchange.removeAttachment(sessionAttachmentKey);
      httpSession = null;
    }
    if (httpSession == null) {
      final SessionManager sessionManager = context.getDeployment().getSessionManager();
      Session session = sessionManager.getSession(exchange, c);
      if (session != null) {
        httpSession =
            (ConvergedHttpSessionFacade)
                SecurityActions.forSession(session, this, false, sessionManager);
        exchange.putAttachment(sessionAttachmentKey, httpSession);
      } else if (create) {

        String existing = c.findSessionId(exchange);
        if (originalServletContext != this.context) {
          // this is a cross context request
          // we need to make sure there is a top level session
          originalServletContext.getSession(originalServletContext, exchange, true);
        } else if (existing != null) {
          c.clearSession(exchange, existing);
        }

        final Session newSession = sessionManager.createSession(exchange, c);
        httpSession =
            (ConvergedHttpSessionFacade)
                SecurityActions.forSession(newSession, this, true, sessionManager);
        // call access after creation to set LastAccessTime at sipAppSession.
        httpSession.access();
        // add delegate to InMemorySession to call sipAppSession.access(), when necessary:
        ((ConvergedInMemorySessionManager) sessionManager)
            .addConvergedSessionDeletegateToSession(
                newSession.getId(), httpSession.getConvergedSessionDelegate());

        exchange.putAttachment(sessionAttachmentKey, httpSession);
      }
    }
    return httpSession;
  }
  // adds offline mode from system property
  private Settings enrichWithOfflineMode(Settings settings) {

    String goOffline = SecurityActions.getProperty(ALT_MAVEN_OFFLINE);
    if (goOffline != null && goOffline.length() > 0) {
      settings.setOffline(Boolean.valueOf(goOffline));
    }

    return settings;
  }
  /* (non-Javadoc)
   * @see org.jboss.arquillian.spi.ServiceLoader#onlyOne(java.lang.Class)
   */
  public <T> T onlyOne(Class<T> serviceClass) {
    Validate.notNull(serviceClass, "ServiceClass must be provided");

    Set<Class<? extends T>> serviceImpls =
        load(serviceClass, SecurityActions.getThreadContextClassLoader());
    verifyOnlyOneOrSameImplementation(serviceClass, serviceImpls);

    return createInstance(serviceImpls.iterator().next());
  }
 private Properties loadProperties(final String name) throws IOException {
   ClassLoader classLoader = SecurityActions.getContextClassLoader();
   URL url = classLoader.getResource(name);
   try (InputStream is = url.openStream()) {
     Properties props = new Properties();
     props.load(is);
     return props;
   }
 }
 private void initializeTempDir(
     final ServletContextImpl servletContext, final DeploymentInfo deploymentInfo) {
   if (deploymentInfo.getTempDir() != null) {
     servletContext.setAttribute(ServletContext.TEMPDIR, deploymentInfo.getTempDir());
   } else {
     servletContext.setAttribute(
         ServletContext.TEMPDIR, new File(SecurityActions.getSystemProperty("java.io.tmpdir")));
   }
 }
  /**
   * Obtains a Twitter client for the username and password as specified from the environment. If
   * the environment is not fully set up, an {@link IllegalStateException} will be raised noting the
   * environment variables expected to be in place. To avoid the ISE first check for the integrity
   * of the environment by using {@link
   * EnvironmentSpecificTwitterClientUtil#isSupportedEnvironment()}
   *
   * @throws IllegalStateException If the environment does not support creation of a Twitter client
   */
  static Twitter getTwitterClient() throws IllegalStateException {
    // Obtain the username and password
    final String username = SecurityActions.getEnvironmentVariable(ENV_VAR_NAME_TWITTER_USERNAME);
    final String password = SecurityActions.getEnvironmentVariable(ENV_VAR_NAME_TWITTER_PASSWORD);

    /*
     * We're only supported if both the username and password have been set
     */
    if (!isSupportedEnvironment()) {
      throw new IllegalStateException(MSG_UNSUPPORTED_ENVIRONMENT);
    }

    // Get a Twitter client
    final Twitter twitterClient = new Twitter(username, password);

    // Return
    return twitterClient;
  }
Example #29
0
 /** {@inheritDoc} */
 public void stop(StopContext context) {
   final T service = getValue();
   // Handle Stop
   log.debugf("Stopping Service: %s", context.getController().getName());
   try {
     Method stopMethod = service.getClass().getMethod("stop");
     ClassLoader old =
         SecurityActions.setThreadContextClassLoader(service.getClass().getClassLoader());
     try {
       stopMethod.invoke(service);
     } finally {
       SecurityActions.resetThreadContextClassLoader(old);
     }
   } catch (NoSuchMethodException e) {
   } catch (Exception e) {
     log.error("Failed to execute legacy service stop", e);
   }
 }
  private static Method findMethod2(Class clazz, String name, String desc) {
    Method[] methods = SecurityActions.getDeclaredMethods(clazz);
    int n = methods.length;
    for (int i = 0; i < n; i++)
      if (methods[i].getName().equals(name) && makeDescriptor(methods[i]).equals(desc))
        return methods[i];

    return null;
  }