Java Code Examples for java.security.AccessControlException

The following are top voted examples for showing how to use java.security.AccessControlException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: NonPublicProxyClass.java   View source code 7 votes vote down vote up
public void run() throws Exception {
    boolean hasAccess = loader != null || hasAccess();
    try {
        proxyClass = Proxy.getProxyClass(loader, interfaces);
        if (!hasAccess) {
            throw new RuntimeException("should have no permission to create proxy class");
        }
    } catch (AccessControlException e) {
        if (hasAccess) {
            throw e;
        }
        if (e.getPermission().getClass() != RuntimePermission.class ||
                !e.getPermission().getName().equals("getClassLoader")) {
            throw e;
        }
        return;
    }

    if (Modifier.isPublic(proxyClass.getModifiers())) {
        throw new RuntimeException(proxyClass + " must be non-public");
    }
    newProxyInstance();
    newInstanceFromConstructor(proxyClass);
}
 
Example 2
Project: lams   File: StdSchedulerFactory.java   View source code 6 votes vote down vote up
/**
 * Add all System properties to the given <code>props</code>.  Will override
 * any properties that already exist in the given <code>props</code>.
 */
private Properties overrideWithSysProps(Properties props) {
    Properties sysProps = null;
    try {
        sysProps = System.getProperties();
    } catch (AccessControlException e) {
        getLog().warn(
            "Skipping overriding quartz properties with System properties " +
            "during initialization because of an AccessControlException.  " +
            "This is likely due to not having read/write access for " +
            "java.util.PropertyPermission as required by java.lang.System.getProperties().  " +
            "To resolve this warning, either add this permission to your policy file or " +
            "use a non-default version of initialize().",
            e);
    }

    if (sysProps != null) {
        props.putAll(sysProps);
    }

    return props;
}
 
Example 3
Project: gdx-cclibs   File: JsonFieldUpdater.java   View source code 6 votes vote down vote up
private OrderedMap<String, Field> getStaticFields(Class type) {
    if (staticFields.containsKey(type))
        return staticFields.get(type);
    Field[] fields = ClassReflection.getDeclaredFields(type);
    OrderedMap<String, Field> nameToField = new OrderedMap(fields.length);
    for (Field field : fields) {
        if (!field.isStatic())
            continue;
        if (!field.isAccessible()) {
            try {
                field.setAccessible(true);
            } catch (AccessControlException ex) {
                continue;
            }
        }

        nameToField.put(field.getName(), field);
    }
    staticFields.put(type, nameToField);
    return nameToField;
}
 
Example 4
Project: OpenJSharp   File: MarshalInputStream.java   View source code 6 votes vote down vote up
/**
 * Fix for 4179055: Need to assist resolving sun stubs; resolve
 * class locally if it is a "permitted" sun class
 */
private Class<?> checkSunClass(String className, AccessControlException e)
    throws AccessControlException
{
    // ensure that we are giving out a stub for the correct reason
    Permission perm = e.getPermission();
    String name = null;
    if (perm != null) {
        name = perm.getName();
    }

    Class<?> resolvedClass = permittedSunClasses.get(className);

    // if class not permitted, throw the SecurityException
    if ((name == null) ||
        (resolvedClass == null) ||
        ((!name.equals("accessClassInPackage.sun.rmi.server")) &&
        (!name.equals("accessClassInPackage.sun.rmi.registry"))))
    {
        throw e;
    }

    return resolvedClass;
}
 
Example 5
Project: openjdk-jdk10   File: PrivilegedCallables.java   View source code 6 votes vote down vote up
void test(String[] args) {
    testPrivileged();

    final Policy policy = new Policy();
    Policy.setPolicy(policy);
    policy.setPermissions(new RuntimePermission("getClassLoader"),
                          new RuntimePermission("setContextClassLoader"),
                          new RuntimePermission("stopThread"));
    System.setSecurityManager(new SecurityManager());

    testPrivileged();

    policy.setPermissions(/* Nothing */);

    THROWS(AccessControlException.class,
           new F() {void f(){ privilegedCallableUsingCurrentClassLoader(realCaller); }},
           new F() {void f(){ privilegedThreadFactory(); }});

    policy.setPermissions(new RuntimePermission("setSecurityManager"));
    System.setSecurityManager(null);
}
 
Example 6
Project: openjdk-jdk10   File: bug6484091.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    File dir = FileSystemView.getFileSystemView().getDefaultDirectory();

    printDirContent(dir);

    System.setSecurityManager(new SecurityManager());

    // The next test cases use 'dir' obtained without SecurityManager

    try {
        printDirContent(dir);

        throw new RuntimeException("Dir content was derived bypass SecurityManager");
    } catch (AccessControlException e) {
        // It's a successful situation
    }
}
 
Example 7
Project: hadoop   File: ClientRMService.java   View source code 6 votes vote down vote up
private String checkReservationACLs(String queueName, String auditConstant)
    throws YarnException {
  UserGroupInformation callerUGI;
  try {
    callerUGI = UserGroupInformation.getCurrentUser();
  } catch (IOException ie) {
    RMAuditLogger.logFailure("UNKNOWN", auditConstant, queueName,
        "ClientRMService", "Error getting UGI");
    throw RPCUtil.getRemoteException(ie);
  }
  // Check if user has access on the managed queue
  if (!queueACLsManager.checkAccess(callerUGI, QueueACL.SUBMIT_APPLICATIONS,
      queueName)) {
    RMAuditLogger.logFailure(
        callerUGI.getShortUserName(),
        auditConstant,
        "User doesn't have permissions to "
            + QueueACL.SUBMIT_APPLICATIONS.toString(), "ClientRMService",
        AuditConstants.UNAUTHORIZED_USER);
    throw RPCUtil.getRemoteException(new AccessControlException("User "
        + callerUGI.getShortUserName() + " cannot perform operation "
        + QueueACL.SUBMIT_APPLICATIONS.name() + " on queue" + queueName));
  }
  return callerUGI.getShortUserName();
}
 
Example 8
Project: hadoop   File: TestMoveApplication.java   View source code 6 votes vote down vote up
@Test
public void testMoveRejectedByPermissions() throws Exception {
  failMove = true;
  
  // Submit application
  final Application application = new Application("user1", resourceManager);
  application.submit();

  final ClientRMService clientRMService = resourceManager.getClientRMService();
  try {
    UserGroupInformation.createRemoteUser("otheruser").doAs(
        new PrivilegedExceptionAction<MoveApplicationAcrossQueuesResponse>() {
          @Override
          public MoveApplicationAcrossQueuesResponse run() throws Exception {
            return clientRMService.moveApplicationAcrossQueues(
                MoveApplicationAcrossQueuesRequest.newInstance(
                    application.getApplicationId(), "newqueue"));
          }
          
        });
    fail("Should have hit exception");
  } catch (Exception ex) {
    assertEquals(AccessControlException.class, ex.getCause().getCause().getClass());
  }
}
 
Example 9
Project: jdk8u-jdk   File: SignedJarTest.java   View source code 6 votes vote down vote up
public static void test(Permission perm, boolean expectException) {
    boolean getException = (Boolean) AccessController.doPrivileged((PrivilegedAction) () -> {
        try {
            AccessController.checkPermission(perm);
            return (Boolean) false;
        } catch (AccessControlException ex) {
            return (Boolean) true;
        }
    });

    if (expectException ^ getException) {
        String message = "Check Permission :" + perm + "\n ExpectException = "
                + expectException + "\n getException = " + getException;
        throw new RuntimeException(message);
    }

}
 
Example 10
Project: jdk8u-jdk   File: LimitedDoPrivilegedWithThread.java   View source code 6 votes vote down vote up
public void runTest(AccessControlContext acc, Permission perm,
        boolean expectACE, int id) {

    AccessController.doPrivileged(
            (PrivilegedAction) () -> {
                try {
                    AccessController.getContext().checkPermission(P1);
                } catch (AccessControlException ace) {
                    catchACE = true;
                }
                if (catchACE ^ expectACE) {
                    throw new RuntimeException("test" + id + " failed");
                }
                return null;
            }, acc, perm);
}
 
Example 11
Project: openjdk-jdk10   File: NestedActions.java   View source code 6 votes vote down vote up
@Override
public java.lang.Object run() {
    System.out.println("Try to read 'java.class.path' property");

    AccessControlContext acc = AccessController.getContext();
    Subject s = Subject.getSubject(acc);
    System.out.println("principals = " + s.getPrincipals());

    try {
        System.out.println("java.class.path = "
                + System.getProperty("java.class.path"));
        throw new RuntimeException(
                "Test failed: no AccessControlException thrown");
    } catch (AccessControlException ace) {
        System.out.println(
                "AccessControlException thrown as expected: "
                + ace.getMessage());
    }

    return null;
}
 
Example 12
Project: jdk8u-jdk   File: NonPublicProxyClass.java   View source code 6 votes vote down vote up
private void newProxyInstance() {
    // expect newProxyInstance to succeed if it's in the same runtime package
    int i = proxyClass.getName().lastIndexOf('.');
    String pkg = (i != -1) ? proxyClass.getName().substring(0, i) : "";
    boolean hasAccess = pkg.isEmpty() || hasAccess();
    try {
        Proxy.newProxyInstance(loader, interfaces, handler);
        if (!hasAccess) {
            throw new RuntimeException("ERROR: Proxy.newProxyInstance should fail " + proxyClass);
        }
    } catch (AccessControlException e) {
        if (hasAccess) {
            throw e;
        }
        if (e.getPermission().getClass() != ReflectPermission.class ||
                !e.getPermission().getName().equals(NEW_PROXY_IN_PKG + pkg)) {
            throw e;
        }
    }
}
 
Example 13
Project: jdk8u-jdk   File: FilterWithSecurityManagerTest.java   View source code 6 votes vote down vote up
/**
 * Test that setting process-wide filter is checked by security manager.
 */
@Test
public void testGlobalFilter() throws Exception {
    if (ObjectInputFilter.Config.getSerialFilter() == null) {
        return;
    }
    try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais)) {
        ObjectInputFilter.Config.setSerialFilter(filter);
        assertFalse(setSecurityManager,
                "When SecurityManager exists, without "
                + "java.security.SerializablePermission(serialFilter) Exception should be thrown");
        Object o = ois.readObject();
    } catch (AccessControlException ex) {
        assertTrue(setSecurityManager);
        assertTrue(ex.getMessage().contains("java.io.SerializablePermission"));
        assertTrue(ex.getMessage().contains("serialFilter"));
    }
}
 
Example 14
Project: openjdk-jdk10   File: FilterWithSecurityManagerTest.java   View source code 6 votes vote down vote up
/**
 * Test that setting process-wide filter is checked by security manager.
 */
@Test
public void testGlobalFilter() throws Exception {
    ObjectInputFilter global = ObjectInputFilter.Config.getSerialFilter();

    try  {
        ObjectInputFilter.Config.setSerialFilter(filter);
        assertFalse(setSecurityManager,
                "When SecurityManager exists, without "
                + "java.io.SerializablePermission(serialFilter) "
                + "IllegalStateException should be thrown");
    } catch (AccessControlException ex) {
        assertTrue(setSecurityManager);
        assertTrue(ex.getMessage().contains("java.io.SerializablePermission"));
        assertTrue(ex.getMessage().contains("serialFilter"));
    } catch (IllegalStateException ise) {
        // ISE should occur only if global filter already set
        Assert.assertNotNull(global, "Global filter should be non-null");
    }
}
 
Example 15
Project: openjdk-jdk10   File: NestedActions.java   View source code 6 votes vote down vote up
@Override
public java.lang.Object run() throws Exception {
    System.out.println("Try to read 'java.class.path' property");

    AccessControlContext acc = AccessController.getContext();
    Subject s = Subject.getSubject(acc);
    System.out.println("principals = " + s.getPrincipals());

    try {
        System.out.println("java.class.path = "
                + System.getProperty("java.class.path"));
        throw new RuntimeException(
                "Test failed: no AccessControlException thrown");
    } catch (AccessControlException ace) {
        System.out.println(
                "AccessControlException thrown as expected: "
                + ace.getMessage());
        throw new ReadPropertyException(ace);
    }
}
 
Example 16
Project: athena   File: SecurityModeManager.java   View source code 6 votes vote down vote up
@Override
public void logged(LogEntry entry) {
    if (entry.getException() != null &&
            entry.getException() instanceof AccessControlException) {
        String location = entry.getBundle().getLocation();
        Permission javaPerm =
                ((AccessControlException) entry.getException()).getPermission();
        org.onosproject.security.Permission permission = DefaultPolicyBuilder.getOnosPermission(javaPerm);
        if (permission == null) {
            log.warn("Unsupported permission requested.");
            return;
        }
        store.getApplicationIds(location).stream().filter(
                appId -> store.isSecured(appId) &&
                        appAdminService.getState(appId) == ApplicationState.ACTIVE).forEach(appId -> {
            store.requestPermission(appId, permission);
            print("[POLICY VIOLATION] APP: %s / Bundle: %s / Permission: %s ",
                    appId.name(), location, permission.toString());
        });
    }
}
 
Example 17
Project: jaffa-framework   File: SecurityManager.java   View source code 6 votes vote down vote up
/** Run the guarded business function, only if the current thread has access.
 * This guarded function may throw a PrivilegedActionException which will contain
 * the real exception
 * @return Returns back the object that the guarded code returned
 * @param functionName Name of the business function being guarded
 * @param action An action object which will be executed, this should contain the guarded code
 * @throws PrivilegedActionException This is the wrapped exception the the guarded code threw
 * @throws AccessControlException This is thrown if the user doesn't have authorization for this function
 */
public static Object runFunction(String functionName, PrivilegedExceptionAction action)
throws PrivilegedActionException, AccessControlException {
    
    if(hasAccess(functionName)) {
        try {
            return action.run();
        } catch (Exception e) {
            throw new PrivilegedActionException(e);
        }
    } else {
        // Access Defined
        log.info("Access Denied To Business Function: " + functionName);
        throw new AccessControlException("Business Function:" + functionName);
    }
}
 
Example 18
Project: jaffa-framework   File: AttachmentHandler.java   View source code 6 votes vote down vote up
private void checkFunctionAccess(Attachment attachment, boolean forMaintenance) throws ApplicationExceptions, FrameworkException, AccessControlException {
    if (attachment != null && attachment.getSerializedKey() != null) {
        // Retrieve the domain object to which the attachment belongs
        IPersistent attachTo = null;
        try {
            attachTo = PersistentHelper.loadFromSerializedKey(attachment.getUOW(), attachment.getSerializedKey());
        } catch (Exception e) {
            log.error("Exception thrown while retrieving the domain object to which the attachment belongs", e);
            throw ExceptionHelper.throwAFR(e);
        }

        if(attachTo!=null) {
            // Ensure that the user has access to the domain object's attachments
            String function = "Attachment." + attachTo.getClass().getSimpleName() + (forMaintenance ? ".Maintenance" : ".Inquiry");
            if (!SecurityManager.checkFunctionAccess(function)) {
                String str = "Access to business-function '" + function + "' is required to be able to " + (forMaintenance ? "manage" : "view") + " attachments for the domain class " + attachTo.getClass().getName();
                log.error(str);
                throw new AccessControlException(str);
            }
        }
    }
}
 
Example 19
Project: jaffa-framework   File: CxfFunctionGuardInterceptor.java   View source code 6 votes vote down vote up
/**
 * Checks if a caller has access to a method being invoked
 *
 * @param method Method being invoked
 * @throws AccessControlException Thrown when the caller doesn't have access
 */
private void checkAccess(Method method) throws AccessControlException, ApplicationExceptions, FrameworkException {
    String targetClassName = method.getDeclaringClass().getName();

    // Get the rule map
    Map<String, List<RuleMetaData>> ruleMap = getPropertyRuleMap(targetClassName, "function-guard");
    if (ruleMap == null) {
        return;
    }

    // Get the rules
    List<RuleMetaData> rules = ruleMap.get(null);
    if (rules == null) {
        return;
    }

    // Check access for any rules that match
    for (RuleMetaData rule : rules) {
        if (match(method, rule)) {
            checkAccess(method, targetClassName, rule);
        }
    }
}
 
Example 20
Project: openjdk-jdk10   File: MarshalInputStream.java   View source code 6 votes vote down vote up
/**
 * Fix for 4179055: Need to assist resolving sun stubs; resolve
 * class locally if it is a "permitted" sun class
 */
private Class<?> checkSunClass(String className, AccessControlException e)
    throws AccessControlException
{
    // ensure that we are giving out a stub for the correct reason
    Permission perm = e.getPermission();
    String name = null;
    if (perm != null) {
        name = perm.getName();
    }

    Class<?> resolvedClass = permittedSunClasses.get(className);

    // if class not permitted, throw the SecurityException
    if ((name == null) ||
        (resolvedClass == null) ||
        ((!name.equals("accessClassInPackage.sun.rmi.server")) &&
        (!name.equals("accessClassInPackage.sun.rmi.registry"))))
    {
        throw e;
    }

    return resolvedClass;
}
 
Example 21
Project: openjdk-jdk10   File: SignedJarTest.java   View source code 6 votes vote down vote up
public static void test(Permission perm, boolean expectException) {
    boolean getException = (Boolean) AccessController.doPrivileged((PrivilegedAction) () -> {
        try {
            AccessController.checkPermission(perm);
            return (Boolean) false;
        } catch (AccessControlException ex) {
            return (Boolean) true;
        }
    });

    if (expectException ^ getException) {
        String message = "Check Permission :" + perm + "\n ExpectException = "
                + expectException + "\n getException = " + getException;
        throw new RuntimeException(message);
    }

}
 
Example 22
Project: openjdk-jdk10   File: LimitedDoPrivilegedWithThread.java   View source code 6 votes vote down vote up
public void runTest(AccessControlContext acc, Permission perm,
        boolean expectACE, int id) {

    AccessController.doPrivileged(
            (PrivilegedAction) () -> {
                try {
                    AccessController.getContext().checkPermission(P1);
                } catch (AccessControlException ace) {
                    catchACE = true;
                }
                if (catchACE ^ expectACE) {
                    throw new RuntimeException("test" + id + " failed");
                }
                return null;
            }, acc, perm);
}
 
Example 23
Project: openjdk-jdk10   File: NoAccess.java   View source code 6 votes vote down vote up
static Class<?> findClass(Module module, String cn, Permission perm) {
    try {
        Class<?> c = Class.forName(module, cn);
        if (c == null) {
            throw new RuntimeException(cn + " not found in " + module);
        }
        if (c.getModule() != module) {
            throw new RuntimeException(c.getModule() + " != " + module);
        }
        return c;
    } catch (AccessControlException e) {
        if (e.getPermission().equals(perm))
            return null;
        throw e;
    }
}
 
Example 24
Project: openjdk-jdk10   File: NoGetClassLoaderAccess.java   View source code 6 votes vote down vote up
static Class<?> findClass(Module module, String cn) {
    try {
        Class<?> c = Class.forName(module, cn);
        if (c == null) {
            throw new RuntimeException(cn + " not found in " + module);
        }
        if (c.getModule() != module) {
            throw new RuntimeException(c.getModule() + " != " + module);
        }
        return c;
    } catch (AccessControlException e) {
        if (module != m3) {
            if (e.getPermission().equals(GET_CLASSLOADER_PERMISSION))
                return null;
        }
        throw e;
    }
}
 
Example 25
Project: openjdk-jdk10   File: NestedActions.java   View source code 6 votes vote down vote up
@Override
public Object run() {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    System.out.println("principals = " + subject.getPrincipals());

    try {
        Utils.writeFile(filename);
        new File(filename).delete();
        throw new RuntimeException(
                "Test failed: no AccessControlException thrown");
    } catch (AccessControlException ace) {
        System.out.println(
                "AccessControlException thrown as expected: "
                + ace.getMessage());
    }

    ReadFromFileNegativeAction readFromFile
            = new ReadFromFileNegativeAction(filename);
    return Subject.doAs(subject, readFromFile);
}
 
Example 26
Project: openjdk-jdk10   File: NonPublicProxyClass.java   View source code 6 votes vote down vote up
public void run() throws Exception {
    boolean hasAccess = loader != null || hasAccess();
    try {
        proxyClass = Proxy.getProxyClass(loader, interfaces);
        if (!hasAccess) {
            throw new RuntimeException("should have no permission to create proxy class");
        }
    } catch (AccessControlException e) {
        if (hasAccess) {
            throw e;
        }
        if (e.getPermission().getClass() != RuntimePermission.class ||
                !e.getPermission().getName().equals("getClassLoader")) {
            throw e;
        }
        return;
    }

    if (Modifier.isPublic(proxyClass.getModifiers())) {
        throw new RuntimeException(proxyClass + " must be non-public");
    }
    newProxyInstance();
    newInstanceFromConstructor(proxyClass);
}
 
Example 27
Project: openjdk-jdk10   File: Version.java   View source code 6 votes vote down vote up
private void checkPermission(Permission perm, boolean expectException) {
    boolean getException = (Boolean) AccessController
            .doPrivileged((PrivilegedAction) () -> {
        try {
            AccessController.checkPermission(perm);
            return (Boolean) false;
        } catch (AccessControlException ex) {
            return (Boolean) true;
        }
    });

    if (expectException ^ getException) {
        String message = "Check Permission :" + perm + "\n ExpectException = "
                + expectException + "\n getException = " + getException;
        throw new RuntimeException(message);
    }
}
 
Example 28
Project: openjdk-jdk10   File: TestSetResourceBundle.java   View source code 6 votes vote down vote up
/**
 * Test the LoggingPermission("control") is required.
 * @param loggerName The logger to use.
 */
public static void testPermission(String loggerName) {
    if (System.getSecurityManager() != null) {
        throw new Error("Security manager is already set");
    }
    Policy.setPolicy(new SimplePolicy(TestCase.PERMISSION));
    System.setSecurityManager(new SecurityManager());
    final ResourceBundle bundle = ResourceBundle.getBundle(LIST_BUNDLE_NAME);
    Logger foobar = Logger.getLogger(loggerName);
    try {
        foobar.setResourceBundle(bundle);
        throw new RuntimeException("Permission not checked!");
    } catch (AccessControlException x) {
        if (x.getPermission() instanceof LoggingPermission) {
            if ("control".equals(x.getPermission().getName())) {
                System.out.println("Got expected exception: " + x);
                return;
            }
        }
        throw new RuntimeException("Unexpected exception: "+x, x);
    }

}
 
Example 29
Project: firebase-admin-java   File: RevivingScheduledExecutor.java   View source code 5 votes vote down vote up
@VisibleForTesting
RevivingScheduledExecutor(
    final ThreadFactory threadFactory,
    final String threadName,
    final long initialDelayMs,
    final long timeoutMs) {
  super(0);
  checkNotNull(threadFactory, "threadFactory must not be null");
  INSTANCE_COUNTER.incrementAndGet();
  this.initialDelayMs = initialDelayMs;
  this.timeoutMs = timeoutMs;
  setRemoveOnCancelPolicy(true);
  setThreadFactory(
      new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
          logger.debug("Creating new thread for: {}", threadName);
          Thread thread = threadFactory.newThread(r);
          try {
            thread.setName(threadName);
            thread.setDaemon(true);
          } catch (AccessControlException ignore) {
            // Unsupported on App Engine.
          }
          if (requestedRestart.getAndSet(false)) {
            afterRestart();
          }
          return thread;
        }
      });
}
 
Example 30
Project: GitHub   File: TypeUtils.java   View source code 5 votes vote down vote up
static void setAccessible(AccessibleObject obj){
    if(!setAccessibleEnable){
        return;
    }
    if(obj.isAccessible()){
        return;
    }
    try{
        obj.setAccessible(true);
    } catch(AccessControlException error){
        setAccessibleEnable = false;
    }
}
 
Example 31
Project: incubator-netbeans   File: DirectoryChooserUI.java   View source code 5 votes vote down vote up
private static boolean canWrite(File f) {
    boolean writeable = false;
    if (f != null) {
        try {
            writeable = f.canWrite();
        } catch (AccessControlException ex) {
            writeable = false;
        }
    }
    return writeable;
}
 
Example 32
Project: tomcat7   File: WebappClassLoaderBase.java   View source code 5 votes vote down vote up
/**
 * Refresh the system policy file, to pick up eventual changes.
 */
protected void refreshPolicy() {

    try {
        // The policy file may have been modified to adjust
        // permissions, so we're reloading it when loading or
        // reloading a Context
        Policy policy = Policy.getPolicy();
        policy.refresh();
    } catch (AccessControlException e) {
        // Some policy files may restrict this, even for the core,
        // so this exception is ignored
    }

}
 
Example 33
Project: fitnotifications   File: ULocale.java   View source code 5 votes vote down vote up
public static String getSystemProperty(String key) {
    String val = null;
    final String fkey = key;
    if (System.getSecurityManager() != null) {
        try {
            val = AccessController.doPrivileged(new PrivilegedAction<String>() {
                @Override
                public String run() {
                    return System.getProperty(fkey);
                }
            });
        } catch (AccessControlException e) {
            // ignore
        }
    } else {
        val = System.getProperty(fkey);
    }
    return val;
}
 
Example 34
Project: fitnotifications   File: ICUConfig.java   View source code 5 votes vote down vote up
/**
 * Get ICU configuration property value for the given name.
 * @param name The configuration property name
 * @param def The default value
 * @return The configuration property value.  If the property does not
 * exist, <code>def</code> is returned.
 */
public static String get(String name, String def) {
    String val = null;
    final String fname = name;
    if (System.getSecurityManager() != null) {
        try {
            val = AccessController.doPrivileged(new PrivilegedAction<String>() {
                @Override
                public String run() {
                    return System.getProperty(fname);
                }
            });
        } catch (AccessControlException e) {
            // ignore
            // TODO log this message
        }
    } else {
        val = System.getProperty(name);
    }

    if (val == null) {
        val = CONFIG_PROPS.getProperty(name, def);
    }
    return val;
}
 
Example 35
Project: powertext   File: Configuration.java   View source code 5 votes vote down vote up
/**
 * gets a new default Configuration
 * @return Configuration
 */
public static final Configuration getConfiguration() {
	try {
		String config = System.getProperty("jazzy.config"); // added by bd
		if (config != null && config.length() > 0)
			return getConfiguration(config);
	} catch (AccessControlException e) {
		e.printStackTrace();
	} 
  return getConfiguration(null);
}
 
Example 36
Project: gdx-cclibs   File: Disposal.java   View source code 5 votes vote down vote up
private static void makeAccessible (Field field){
    if (!field.isAccessible()) {
        try {
            field.setAccessible(true);
        } catch (AccessControlException ex) {
            throw new GdxRuntimeException(String.format("Field %s cannot be made accessible", field.getName()));
        }
    }
}
 
Example 37
Project: gdx-cclibs   File: AssignmentAssetManager.java   View source code 5 votes vote down vote up
private void makeAccessible (Field field) {
    if (!field.isAccessible()) {
        try {
            field.setAccessible(true);
        } catch (AccessControlException ex) {
            throw new GdxRuntimeException(String.format("Field %s cannot be made accessible", field.getName()));
        }
    }
}
 
Example 38
Project: jiracli   File: HttpClient.java   View source code 5 votes vote down vote up
private static void checkAccountLocked(HttpResponse response) {
    Header header = response.getLastHeader("X-Authentication-Denied-Reason");
    if (header != null) {
        String info = Objects.toString(header.getValue(), "").trim();
        throw new AccessControlException("Your account seems to be locked" + (info.isEmpty() ? "" : ": " + info));
    }
}
 
Example 39
Project: openjdk-jdk10   File: BadPolicyFile.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    URI uri = new File(System.getProperty("test.src", "."),
                       "BadPolicyFile.policy").toURI();
    Policy.setPolicy(Policy.getInstance("JavaPolicy", new URIParameter(uri)));
    System.setSecurityManager(new SecurityManager());
    try {
        String javahome = System.getProperty("java.home");
        throw new Exception("Expected AccessControlException");
    } catch (AccessControlException ace) {
        System.out.println("Test PASSED");
    }
}
 
Example 40
Project: sql-utils   File: MySqlOutputVisitor.java   View source code 5 votes vote down vote up
public MySqlOutputVisitor(Appendable appender, boolean parameterized) {
    super(appender, parameterized);

    try {
        configFromProperty(System.getProperties());
    } catch (AccessControlException e) {
        // skip
    }
}