List of usage examples for java.lang System getSecurityManager
public static SecurityManager getSecurityManager()
From source file:org.apache.catalina.core.StandardWrapper.java
/** * Load and initialize an instance of this servlet, if there is not already * at least one initialized instance. This can be used, for example, to * load servlets that are marked in the deployment descriptor to be loaded * at server startup time./* w w w . j a va 2 s . co m*/ */ public synchronized Servlet loadServlet() throws ServletException { // Nothing to do if we already have an instance or an instance pool if (!singleThreadModel && (instance != null)) return instance; PrintStream out = System.out; if (swallowOutput) { SystemLogHandler.startCapture(); } Servlet servlet; try { long t1 = System.currentTimeMillis(); // If this "servlet" is really a JSP file, get the right class. // HOLD YOUR NOSE - this is a kludge that avoids having to do special // case Catalina-specific code in Jasper - it also requires that the // servlet path be replaced by the <jsp-file> element content in // order to be completely effective String actualClass = servletClass; if ((actualClass == null) && (jspFile != null)) { Wrapper jspWrapper = (Wrapper) ((Context) getParent()).findChild(Constants.JSP_SERVLET_NAME); if (jspWrapper != null) actualClass = jspWrapper.getServletClass(); } // Complain if no servlet class has been specified if (actualClass == null) { unavailable(null); throw new ServletException(sm.getString("standardWrapper.notClass", getName())); } // Acquire an instance of the class loader to be used Loader loader = getLoader(); if (loader == null) { unavailable(null); throw new ServletException(sm.getString("standardWrapper.missingLoader", getName())); } ClassLoader classLoader = loader.getClassLoader(); // Special case class loader for a container provided servlet // if (isContainerProvidedServlet(actualClass) && !((Context) getParent()).getPrivileged()) { // If it is a priviledged context - using its own // class loader will work, since it's a child of the container // loader classLoader = this.getClass().getClassLoader(); } // Load the specified servlet class from the appropriate class loader Class classClass = null; try { if (System.getSecurityManager() != null) { final ClassLoader fclassLoader = classLoader; final String factualClass = actualClass; try { classClass = (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { if (fclassLoader != null) { return fclassLoader.loadClass(factualClass); } else { return Class.forName(factualClass); } } }); } catch (PrivilegedActionException pax) { Exception ex = pax.getException(); if (ex instanceof ClassNotFoundException) { throw (ClassNotFoundException) ex; } else { getServletContext().log("Error loading " + fclassLoader + " " + factualClass, ex); } } } else { if (classLoader != null) { classClass = classLoader.loadClass(actualClass); } else { classClass = Class.forName(actualClass); } } } catch (ClassNotFoundException e) { unavailable(null); getServletContext().log("Error loading " + classLoader + " " + actualClass, e); throw new ServletException(sm.getString("standardWrapper.missingClass", actualClass), e); } if (classClass == null) { unavailable(null); throw new ServletException(sm.getString("standardWrapper.missingClass", actualClass)); } // Instantiate and initialize an instance of the servlet class itself try { servlet = (Servlet) classClass.newInstance(); } catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException(sm.getString("standardWrapper.notServlet", actualClass), e); } catch (Throwable e) { unavailable(null); // Restore the context ClassLoader throw new ServletException(sm.getString("standardWrapper.instantiate", actualClass), e); } // Check if loading the servlet in this web application should be // allowed if (!isServletAllowed(servlet)) { throw new SecurityException(sm.getString("standardWrapper.privilegedServlet", actualClass)); } // Special handling for ContainerServlet instances if ((servlet instanceof ContainerServlet) && (isContainerProvidedServlet(actualClass) || ((Context) getParent()).getPrivileged())) { ((ContainerServlet) servlet).setWrapper(this); } classLoadTime = (int) (System.currentTimeMillis() - t1); // Call the initialization method of this servlet try { instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT, servlet); if (System.getSecurityManager() != null) { Class[] classType = new Class[] { ServletConfig.class }; Object[] args = new Object[] { ((ServletConfig) facade) }; SecurityUtil.doAsPrivilege("init", servlet, classType, args); } else { servlet.init(facade); } // Invoke jspInit on JSP pages if ((loadOnStartup >= 0) && (jspFile != null)) { // Invoking jspInit DummyRequest req = new DummyRequest(); req.setServletPath(jspFile); req.setQueryString("jsp_precompile=true"); DummyResponse res = new DummyResponse(); if (System.getSecurityManager() != null) { Class[] classType = new Class[] { ServletRequest.class, ServletResponse.class }; Object[] args = new Object[] { req, res }; SecurityUtil.doAsPrivilege("service", servlet, classType, args); } else { servlet.service(req, res); } } instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet); } catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; } catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; } catch (Throwable f) { getServletContext().log("StandardWrapper.Throwable", f); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException(sm.getString("standardWrapper.initException", getName()), f); } // Register our newly initialized instance singleThreadModel = servlet instanceof SingleThreadModel; if (singleThreadModel) { if (instancePool == null) instancePool = new Stack(); } fireContainerEvent("load", this); loadTime = System.currentTimeMillis() - t1; } finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } } return servlet; }
From source file:org.apache.jasper.runtime.PageContextImpl.java
/** * Proprietary method to evaluate EL expressions. * XXX - This method should go away once the EL interpreter moves * out of JSTL and into its own project. For now, this is necessary * because the standard machinery is too slow. * * @param expression The expression to be evaluated * @param expectedType The expected resulting type * @param pageContext The page context/*from w w w.ja v a 2 s .c o m*/ * @param functionMap Maps prefix and name to Method * @return The result of the evaluation */ public static Object proprietaryEvaluate(final String expression, final Class expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap, final boolean escape) throws ELException { Object retValue; if (System.getSecurityManager() != null) { try { retValue = AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { return elExprEval.evaluate(expression, expectedType, pageContext.getVariableResolver(), functionMap); } }); } catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } } } else { retValue = elExprEval.evaluate(expression, expectedType, pageContext.getVariableResolver(), functionMap); } if (escape) { retValue = XmlEscape(retValue.toString()); } return retValue; }
From source file:org.digidoc4j.main.DigiDoc4JTest.java
void callMainWithoutSystemExit(String[] params) { SecurityManager securityManager = System.getSecurityManager(); forbidSystemExitCall();/*from w ww .j a v a2 s.c o m*/ try { DigiDoc4J.main(params); } catch (DigiDoc4JUtilityException ignore) { } System.setSecurityManager(securityManager); }
From source file:com.sshtools.common.ui.SshToolsApplicationClientPanel.java
/** * * * @param disconnect//from ww w . ja v a 2s .co m */ public void closeConnection(boolean disconnect) { // if (isNeedSave() && (currentConnectionFile != null)) { // Stop save dialog box when not using a pre-existing profile. // Only allow saving of files if allowed by the security manager try { if (System.getSecurityManager() != null) { AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write")); if (JOptionPane.showConfirmDialog(this, "You have unsaved changes to the connection " + ((currentConnectionFile == null) ? "<Untitled>" : currentConnectionFile.getName()) + ".\nDo you want to save the changes now?", "Unsaved changes", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { saveConnection(false, getCurrentConnectionFile(), getCurrentConnectionProfile()); setNeedSave(false); } } } catch (AccessControlException ace) { log.warn("Changes made to connection, but security manager won't allow saving of files."); } } //setCurrentConnectionFile(null); }
From source file:org.apache.cassandra.concurrent.ContinuationsExecutor.java
/** * If there is a security manager, makes sure caller has permission to shut * down threads in general (see shutdownPerm). If this passes, additionally * makes sure the caller is allowed to interrupt each worker thread. This * might not be true even if first check passed, if the SecurityManager * treats some threads specially./*from w w w . j a va2 s.c o m*/ */ private void checkShutdownAccess() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPermission(shutdownPerm); final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { for (Worker w : workers) security.checkAccess(w.thread); } finally { mainLock.unlock(); } } }
From source file:com.sshtools.sshterm.SshTermSessionPanel.java
private void initActions() { // Create the action menu groups registerActionMenu(new SshToolsApplicationPanel.ActionMenu("File", "File", 'f', 0)); registerActionMenu(new SshToolsApplicationPanel.ActionMenu("Edit", "Edit", 'e', 10)); registerActionMenu(new SshToolsApplicationPanel.ActionMenu("View", "View", 'v', 20)); registerActionMenu(new SshToolsApplicationPanel.ActionMenu("Help", "Help", 'h', 90)); actions = new Vector(); connectionPropertiesAction = new ConnectionPropertiesActionImpl(); registerAction(connectionPropertiesAction); // newAction = new NewAction(); // registerAction(newAction); // Only allow opening of files if allowed by the security manager try {/* w ww .j a v a 2 s. c om*/ if (System.getSecurityManager() != null) { AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "read")); } //openAction = new OpenAction(); // registerAction(openAction); playAction = new PlayAction(); registerAction(playAction); } catch (AccessControlException ace) { log.warn("File reading actions are not available"); } // Only allow saving of files if allowed by the security manager try { if (System.getSecurityManager() != null) { AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write")); } // saveAction = new SaveAction(); // registerAction(saveAction); // saveAsAction = new SaveAsAction(); // registerAction(saveAsAction); recordAction = new RecordAction(); registerAction(recordAction); stopAction = new StopAction(); registerAction(stopAction); } catch (AccessControlException ace) { log.warn("File write actions are not available"); } // Only allow editing of connection file if read / write is allowed try { if (System.getSecurityManager() != null) { AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write")); } if (System.getSecurityManager() != null) { AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "read")); } // editAction = new EditActionImpl(); // registerAction(editAction); } catch (AccessControlException ace) { log.warn("Read / write actions are not available"); } // Checking if printing is allowed if (pageFormat != null) { try { if (System.getSecurityManager() != null) { AccessController.checkPermission(new RuntimePermission("queuePrintJob")); } printAction = new PrintActionImpl(); registerAction(printAction); printPreviewAction = new PrintPreviewActionImpl(); registerAction(printPreviewAction); } catch (AccessControlException ace) { log.warn("Print actions are not available"); } } // Always allow refreshing of terminal refreshAction = new RefreshActionImpl(); registerAction(refreshAction); // Always allow closing of connect closeAction = new CloseAction(); registerAction(closeAction); // Copy / Paste try { if (System.getSecurityManager() != null) { AccessController.checkPermission(new AWTPermission("accessClipboard")); } copyAction = new CopyActionImpl(); registerAction(copyAction); pasteAction = new PasteActionImpl(); registerAction(pasteAction); } catch (AccessControlException ace) { } // Theres no point in having the keygen action if we can't write to local file try { if (System.getSecurityManager() != null) { AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write")); } // keygenAction = new KeygenAction(); // registerAction(keygenAction); } catch (AccessControlException ace) { log.warn("Keygen actions is not available"); } // Clear action clearAction = new ClearActionImpl(); registerAction(clearAction); // Remove stuff we dont want deregisterAction(getAction("Options")); setActionVisible("New Window", false); setActionVisible("About", false); }
From source file:org.hyperic.hq.measurement.agent.server.ScheduleThread.java
private ThreadFactory getFactory(final String plugin) { final SecurityManager s = System.getSecurityManager(); final ThreadGroup group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); return new ThreadFactory() { private final AtomicLong num = new AtomicLong(); public Thread newThread(Runnable r) { final Thread rtn = new Thread(group, r); rtn.setDaemon(true);/*from ww w.j a va2s . c om*/ rtn.setName(plugin + "-" + num.getAndIncrement()); return rtn; } }; }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@SuppressWarnings("unchecked") private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getReadMethod() == null) { throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); }//from ww w. j a v a 2 s . c om final Method readMethod = pd.getReadMethod(); try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } Object value; if (System.getSecurityManager() != null) { try { value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return readMethod.invoke(object, (Object[]) null); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { value = readMethod.invoke(object, (Object[]) null); } if (tokens.keys != null) { if (value == null) { if (isAutoGrowNestedPaths()) { value = setDefaultValue(tokens.actualName); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } } String indexedPropertyName = tokens.actualName; // apply indexes and map keys for (int i = 0; i < tokens.keys.length; i++) { String key = tokens.keys[i]; if (value == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } else if (value.getClass().isArray()) { int index = Integer.parseInt(key); value = growArrayIfNecessary(value, index, indexedPropertyName); value = Array.get(value, index); } else if (value instanceof List) { int index = Integer.parseInt(key); List<Object> list = (List<Object>) value; growCollectionIfNecessary(list, index, indexedPropertyName, pd, i + 1); value = list.get(index); } else if (value instanceof Set) { // Apply index to Iterator in case of a Set. Set<Object> set = (Set<Object>) value; int index = Integer.parseInt(key); if (index < 0 || index >= set.size()) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot get element with index " + index + " from Set of size " + set.size() + ", accessed using property path '" + propertyName + "'"); } Iterator<Object> it = set.iterator(); for (int j = 0; it.hasNext(); j++) { Object elem = it.next(); if (j == index) { value = elem; break; } } } else if (value instanceof Map) { Map<Object, Object> map = (Map<Object, Object>) value; Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1); // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); value = map.get(convertedMapKey); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Set nor a Map; returned value was [" + value + "]"); } indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX; } } return value; } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Index of out of bounds in property path '" + propertyName + "'", ex); } catch (NumberFormatException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (TypeMismatchException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (InvocationTargetException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Getter for property '" + actualName + "' threw exception", ex); } catch (Exception ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Illegal attempt to get property '" + actualName + "' threw exception", ex); } }
From source file:org.elasticsearch.plugins.PluginManagerIT.java
public void testThatBasicAuthIsSupportedWithHttps() throws Exception { assumeTrue("test requires security manager to be disabled", System.getSecurityManager() == null); SSLSocketFactory defaultSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); ServerBootstrap serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory()); SelfSignedCertificate ssc = new SelfSignedCertificate("localhost"); try {//w w w .j av a2 s. c o m // Create a trust manager that does not validate certificate chains: SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); final List<HttpRequest> requests = new ArrayList<>(); final SslContext sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new SslHandler(sslContext.newEngine()), new HttpRequestDecoder(), new HttpResponseEncoder(), new LoggingServerHandler(requests)); } }); Channel channel = serverBootstrap.bind(new InetSocketAddress(InetAddress.getByName("localhost"), 0)); int port = ((InetSocketAddress) channel.getLocalAddress()).getPort(); // IO_ERROR because there is no real file delivered... assertStatus( String.format(Locale.ROOT, "install https://user:pass@localhost:%s/foo.zip --verbose --timeout 1s", port), ExitStatus.IO_ERROR); // ensure that we did not try any other data source like download.elastic.co, in case we specified our own local URL assertThat(terminal.getTerminalOutput(), not(hasItem(containsString("download.elastic.co")))); assertThat(requests, hasSize(1)); String msg = String.format(Locale.ROOT, "Request header did not contain Authorization header, terminal output was: %s", terminal.getTerminalOutput()); assertThat(msg, requests.get(0).headers().contains("Authorization"), is(true)); assertThat(msg, requests.get(0).headers().get("Authorization"), is("Basic " + Base64.encodeBytes("user:pass".getBytes(StandardCharsets.UTF_8)))); } finally { HttpsURLConnection.setDefaultSSLSocketFactory(defaultSocketFactory); serverBootstrap.releaseExternalResources(); ssc.delete(); } }
From source file:org.wso2.carbon.core.init.CarbonServerManager.java
/** * Restart the Carbon server/*from w w w . j a v a 2s . co m*/ * * @param isGraceful True, if the server should be gracefully restarted, false, if a * restart should be forced */ private void restart(boolean isGraceful) { createSuperTenantCarbonContext(); SecurityManager secMan = System.getSecurityManager(); if (secMan != null) { secMan.checkPermission(new ManagementPermission("control")); } Runtime.getRuntime().removeShutdownHook(shutdownHook); new JMXServerManager().stopJmxService(); try { ServerStatus.setServerRestarting(); Map<String, TransportInDescription> inTransports = serverConfigContext.getAxisConfiguration() .getTransportsIn(); if (isGraceful) { log.info("Gracefully restarting " + serverName + "..."); new ServerManagement(inTransports, serverConfigContext).startMaintenanceForShutDown(); } else { log.info("Restarting " + serverName + "..."); } try { ServerStatus.setServerRestarting(); } catch (AxisFault e) { String msg = "Cannot set server to restarting mode"; log.error(msg, e); } MBeanRegistrar.unregisterAllMBeans(); CarbonContextHolderBase.unloadTenant(MultitenantConstants.SUPER_TENANT_ID); ClusteringAgent clusteringAgent = serverConfigContext.getAxisConfiguration().getClusteringAgent(); if (clusteringAgent != null) { clusteringAgent.stop(); } if (!CarbonUtils.isRunningInStandaloneMode()) { long waitFor = 5; log.info("Waiting for " + waitFor + " sec before initiating restart"); Thread.sleep(waitFor * 1000); // The H2 DB connections do not get closed if this is not done } new Thread(new Runnable() { public void run() { log.info("Starting a new Carbon instance. Current instance will be shutdown"); log.info("Halting JVM"); System.exit(121); // if (System.getProperty("wrapper.key") != null) { // If Carbon was started using wrapper // WrapperManager.restart(); // } else { // If carbon was started using wso2server.sh/.bat // System.exit(121); // } } }).start(); } catch (Exception e) { String msg = "Cannot set server to restarting mode"; log.error(msg, e); } }