Example usage for java.lang System getSecurityManager

List of usage examples for java.lang System getSecurityManager

Introduction

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

Prototype

public static SecurityManager getSecurityManager() 

Source Link

Document

Gets the system-wide security manager.

Usage

From source file:org.apache.myfaces.ov2021.application.jsp.JspStateManagerImpl.java

protected Object deserializeView(Object state) {
    if (log.isLoggable(Level.FINEST))
        log.finest("Entering deserializeView");

    if (state instanceof byte[]) {
        if (log.isLoggable(Level.FINEST))
            log.finest("Processing deserializeView - deserializing serialized state. Bytes : "
                    + ((byte[]) state).length);

        try {/*from w w w.  ja  va  2 s  .  c  om*/
            ByteArrayInputStream bais = new ByteArrayInputStream((byte[]) state);
            InputStream is = bais;
            if (is.read() == COMPRESSED_FLAG) {
                is = new GZIPInputStream(is);
            }
            ObjectInputStream ois = null;
            try {
                final ObjectInputStream in = new MyFacesObjectInputStream(is);
                ois = in;
                Object object = null;
                if (System.getSecurityManager() != null) {
                    object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object[]>() {
                        public Object[] run()
                                throws PrivilegedActionException, IOException, ClassNotFoundException {
                            return new Object[] { in.readObject(), in.readObject() };
                        }
                    });
                } else {
                    object = new Object[] { in.readObject(), in.readObject() };
                }
                return object;
            } finally {
                if (ois != null) {
                    ois.close();
                    ois = null;
                }
            }
        } catch (PrivilegedActionException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        } catch (IOException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        } catch (ClassNotFoundException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        }
    } else if (state instanceof Object[]) {
        if (log.isLoggable(Level.FINEST))
            log.finest("Exiting deserializeView - state not serialized.");

        return state;
    } else if (state == null) {
        log.severe("Exiting deserializeView - this method should not be called with a null-state.");
        return null;
    } else {
        log.severe("Exiting deserializeView - this method should not be called with a state of type : "
                + state.getClass());
        return null;
    }
}

From source file:org.languagetool.gui.Main.java

public static void main(String[] args) {
    if (System.getSecurityManager() == null) {
        JnaTools.setBugWorkaroundProperty();
    }//from  w w w . ja  va2s  . co  m
    LocalStorage localStorage = new LocalStorage();
    LocaleBean bean = localStorage.loadProperty("gui.locale", LocaleBean.class);
    if (bean != null) {
        Locale.setDefault(bean.asLocale());
    }
    Main prg = new Main(localStorage);
    if (args.length == 1 && (args[0].equals("-t") || args[0].equals("--tray"))) {
        // dock to systray on startup
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    prg.createGUI();
                    prg.setTrayMode(true);
                    prg.hideToTray();
                } catch (Exception e) {
                    Tools.showError(e);
                    System.exit(1);
                }
            }
        });
    } else if (args.length == 1 && (args[0].equals("-h") || args[0].equals("--help"))) {
        printUsage();
    } else if (args.length == 0 || args.length == 1) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    prg.createGUI();
                    prg.showGUI();
                    if (args.length == 1) {
                        prg.loadFile(new File(args[0]));
                    }
                } catch (Exception e) {
                    Tools.showError(e);
                }
            }
        });
    } else {
        printUsage();
        System.exit(1);
    }
}

From source file:org.wso2.carbon.core.init.CarbonServerManager.java

/**
 * Forced shutdown/*from   w ww.java  2 s .  c  o m*/
 */
public void shutdown() {
    createSuperTenantCarbonContext();
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    log.info("Shutting down " + serverName + "...");
    if (!isShutdownTriggeredByShutdownHook) {
        Runtime.getRuntime().removeShutdownHook(shutdownHook);
    }
    try {
        try {
            ServerStatus.setServerShuttingDown();
        } catch (AxisFault e) {
            String msg = "Cannot set server to shutdown mode";
            log.error(msg, e);
        }
        CarbonCoreServiceComponent.shutdown();
        //            stopListenerManager();
        new JMXServerManager().stopJmxService();
        log.info("Shutting down OSGi framework...");
        EclipseStarter.shutdown();
        log.info("Shutdown complete");
        log.info("Halting JVM");
        if (!isShutdownTriggeredByShutdownHook) {
            System.exit(0);
        }
    } catch (Exception e) {
        log.error("Error occurred while shutting down " + serverName, e);
        if (!isShutdownTriggeredByShutdownHook) {
            System.exit(1);
        }
    }
}

From source file:org.apache.catalina.core.StandardWrapper.java

/**
 * Unload all initialized instances of this servlet, after calling the
 * <code>destroy()</code> method for each instance.  This can be used,
 * for example, prior to shutting down the entire servlet engine, or
 * prior to reloading all of the classes from the Loader associated with
 * our Loader's repository.//from   w  ww  .  j  a  v a  2  s  .c o  m
 *
 * @exception ServletException if an exception is thrown by the
 *  destroy() method
 */
public synchronized void unload() throws ServletException {

    // Nothing to do if we have never loaded the instance
    if (!singleThreadModel && (instance == null))
        return;
    unloading = true;

    // Loaf a while if the current instance is allocated
    // (possibly more than once if non-STM)
    if (countAllocated > 0) {
        int nRetries = 0;
        while ((nRetries < 21) && (countAllocated > 0)) {
            if ((nRetries % 10) == 0) {
                log.info(sm.getString("standardWrapper.waiting", new Integer(countAllocated)));
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                ;
            }
            nRetries++;
        }
    }

    ClassLoader oldCtxClassLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader classLoader = instance.getClass().getClassLoader();

    PrintStream out = System.out;
    if (swallowOutput) {
        SystemLogHandler.startCapture();
    }

    // Call the servlet destroy() method
    try {
        instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_DESTROY_EVENT, instance);

        Thread.currentThread().setContextClassLoader(classLoader);
        if (System.getSecurityManager() != null) {
            SecurityUtil.doAsPrivilege("destroy", instance);
            SecurityUtil.remove(instance);
        } else {
            instance.destroy();
        }

        instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_DESTROY_EVENT, instance);
    } catch (Throwable t) {
        instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_DESTROY_EVENT, instance, t);
        instance = null;
        instancePool = null;
        nInstances = 0;
        fireContainerEvent("unload", this);
        unloading = false;
        throw new ServletException(sm.getString("standardWrapper.destroyException", getName()), t);
    } finally {
        // restore the context ClassLoader
        Thread.currentThread().setContextClassLoader(oldCtxClassLoader);
        // Write captured output
        if (swallowOutput) {
            String log = SystemLogHandler.stopCapture();
            if (log != null && log.length() > 0) {
                if (getServletContext() != null) {
                    getServletContext().log(log);
                } else {
                    out.println(log);
                }
            }
        }
    }

    // Deregister the destroyed instance
    instance = null;

    if (singleThreadModel && (instancePool != null)) {
        try {
            Thread.currentThread().setContextClassLoader(classLoader);
            while (!instancePool.isEmpty()) {
                if (System.getSecurityManager() != null) {
                    SecurityUtil.doAsPrivilege("destroy", ((Servlet) instancePool.pop()));
                    SecurityUtil.remove(instance);
                } else {
                    ((Servlet) instancePool.pop()).destroy();
                }
            }
        } catch (Throwable t) {
            instancePool = null;
            nInstances = 0;
            unloading = false;
            fireContainerEvent("unload", this);
            throw new ServletException(sm.getString("standardWrapper.destroyException", getName()), t);
        } finally {
            // restore the context ClassLoader
            Thread.currentThread().setContextClassLoader(oldCtxClassLoader);
        }
        instancePool = null;
        nInstances = 0;
    }

    singleThreadModel = false;

    unloading = false;
    fireContainerEvent("unload", this);

}

From source file:org.kchine.r.server.http.frontend.CommandServlet.java

public void init(ServletConfig sConfig) throws ServletException {
    super.init(sConfig);
    log.info("command servlet init");
    if (_rkit == null) {
        PoolUtils.injectSystemProperties(true);
        ServerDefaults.init();/* w w  w  .j a  v  a 2s  . co m*/
    }
    PoolUtils.initRmiSocketFactory();
    getServletContext().setAttribute("SESSIONS_MAP", new HashMap<String, HttpSession>());
    getServletContext().setAttribute("SESSIONS_ATTRIBUTES_MAP", new HashMap<String, HashMap<String, Object>>());
    getServletContext().setAttribute("R_SESSIONS", new HashMap<RServices, HttpSession>());

    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new YesSecurityManager());
    }
}

From source file:org.apache.coyote.http11.Http11Processor.java

/**
 * When committing the response, we have to validate the set of headers, as
 * well as setup the response filters./*w  w w  .  j  a  v a2 s  . c  om*/
 */
protected void prepareResponse() {

    boolean entityBody = true;
    contentDelimitation = false;

    OutputFilter[] outputFilters = outputBuffer.getFilters();

    if (http09 == true) {
        // HTTP/0.9
        outputBuffer.addActiveFilter(outputFilters[Constants.IDENTITY_FILTER]);
        return;
    }

    int statusCode = response.getStatus();
    if ((statusCode == 204) || (statusCode == 205) || (statusCode == 304)) {
        // No entity body
        outputBuffer.addActiveFilter(outputFilters[Constants.VOID_FILTER]);
        entityBody = false;
        contentDelimitation = true;
    }

    MessageBytes methodMB = request.method();
    if (methodMB.equals("HEAD")) {
        // No entity body
        outputBuffer.addActiveFilter(outputFilters[Constants.VOID_FILTER]);
        contentDelimitation = true;
    }

    // Check for compression
    boolean useCompression = false;
    if (entityBody && (compressionLevel > 0)) {
        useCompression = isCompressable();

        // Change content-length to -1 to force chunking
        if (useCompression) {
            response.setContentLength(-1);
        }
    }

    MimeHeaders headers = response.getMimeHeaders();
    if (!entityBody) {
        response.setContentLength(-1);
    } else {
        String contentType = response.getContentType();
        if (contentType != null) {
            headers.setValue("Content-Type").setString(contentType);
        }
        String contentLanguage = response.getContentLanguage();
        if (contentLanguage != null) {
            headers.setValue("Content-Language").setString(contentLanguage);
        }
    }

    int contentLength = response.getContentLength();
    if (contentLength != -1) {
        response.getMimeHeaders().setValue("Content-Length").setInt(contentLength);
        outputBuffer.addActiveFilter(outputFilters[Constants.IDENTITY_FILTER]);
        contentDelimitation = true;
    } else {
        if (entityBody && http11 && keepAlive) {
            outputBuffer.addActiveFilter(outputFilters[Constants.CHUNKED_FILTER]);
            contentDelimitation = true;
            response.addHeader("Transfer-Encoding", "chunked");
        }
    }

    if (useCompression) {
        outputBuffer.addActiveFilter(outputFilters[Constants.GZIP_FILTER]);
        // FIXME: Make content-encoding generation dynamic
        response.setHeader("Content-Encoding", "gzip");
        // Make Proxies happy via Vary (from mod_deflate)
        response.setHeader("Vary", "Accept-Encoding");
    }

    // Add date header
    if (!response.containsHeader("Date")) {

        String date = null;
        if (System.getSecurityManager() != null) {
            date = (String) AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return FastHttpDateFormat.getCurrentDate();
                }
            });
        } else {
            date = FastHttpDateFormat.getCurrentDate();
        }
        response.addHeader("Date", date);
    }

    // Add server header
    response.addHeader("Server", Constants.SERVER);

    // Add transfer encoding header
    // FIXME

    if ((entityBody) && (!contentDelimitation)) {
        // Mark as close the connection after the request, and add the 
        // connection: close header
        keepAlive = false;
    }

    // If we know that the request is bad this early, add the
    // Connection: close header.
    keepAlive = keepAlive && !statusDropsConnection(statusCode);
    if (!keepAlive) {
        response.addHeader("Connection", "close");
    } else if (!http11) {
        response.addHeader("Connection", "Keep-Alive");
    }

    // Build the response header
    outputBuffer.sendStatus();

    int size = headers.size();
    for (int i = 0; i < size; i++) {
        outputBuffer.sendHeader(headers.getName(i), headers.getValue(i));
    }
    outputBuffer.endHeaders();

}

From source file:org.springframework.beans.BeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;//from w  ww .jav  a2  s  .co  m
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // TODO: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // 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);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.resolvedDescriptor;
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().resolvedDescriptor = pd;
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        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);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:org.apache.coyote.tomcat5.CoyoteRequest.java

/**
 * Set the Principal who has been authenticated for this Request.  This
 * value is also used to calculate the value to be returned by the
 * <code>getRemoteUser()</code> method.
 *
 * @param principal The user Principal// www  . j  a  va 2 s  .com
 */
public void setUserPrincipal(Principal principal) {

    if (System.getSecurityManager() != null) {
        HttpSession session = getSession(false);
        if ((subject != null) && (!subject.getPrincipals().contains(principal))) {
            subject.getPrincipals().add(principal);
        } else if (session != null && session.getAttribute(Globals.SUBJECT_ATTR) == null) {
            subject = new Subject();
            subject.getPrincipals().add(principal);
        }
        if (session != null) {
            session.setAttribute(Globals.SUBJECT_ATTR, subject);
        }
    }

    this.userPrincipal = principal;
}

From source file:com.google.ratel.util.RatelUtils.java

/**
 * Returns true if Click resources (JavaScript, CSS, images etc) packaged in jars can be deployed to the root directory of the webapp,
 * false otherwise.//from  w ww  . j a  va 2s.c  o m
 * <p/>
 * This method will return false in restricted environments where write access to the underlying file system is disallowed. Examples
 * where write access is not allowed include the WebLogic JEE server (this can be changed though) and Google App Engine.
 *
 * @param servletContext the application servlet context
 * @return true if writes are allowed, false otherwise
 */
public static boolean isResourcesDeployable(ServletContext servletContext) {
    try {
        boolean canWrite = (servletContext.getRealPath("/") != null);
        if (!canWrite) {
            return false;
        }

        // Since Google App Engine returns a value for getRealPath, check
        // SecurityManager if writes are allowed
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite("/");
        }
        return true;
    } catch (Throwable e) {
        return false;
    }
}

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv2) throws BeansException {
    net.yasion.common.core.bean.wrapper.PropertyValue pv = new net.yasion.common.core.bean.wrapper.PropertyValue(
            "", null);
    AfxBeanUtils.copySamePropertyValue(pv2, pv);
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;/*ww w . j a va  2s  .co  m*/
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // #TO#DO#: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // 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);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.getResolvedDescriptor();
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().setResolvedDescriptor(pd);
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.getConversionNecessary())) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        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);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().setConversionNecessary(valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}