Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

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

Prototype

public SecurityException(Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified cause and a detail message of (cause==null ?

Usage

From source file:org.ambraproject.service.user.UserRegistrationServiceImpl.java

/**
 * {@inheritDoc}//from w  w w  .j  a v a 2 s .  com
 */
@Override
@Transactional
public String sendEmailChangeMessage(final String oldEmail, final String newEmail, final String password)
        throws NoSuchUserException, DuplicateUserException {
    for (Map.Entry<String, String> argument : new HashMap<String, String>() {
        {
            put("old email", oldEmail);
            put("new email", newEmail);
            put("password", password);
        }
    }.entrySet()) {
        if (StringUtils.isEmpty(argument.getValue())) {
            throw new IllegalArgumentException("Must supply a(n) " + argument.getKey());
        }
    }

    UserProfile profile = (UserProfile) DataAccessUtils.uniqueResult(hibernateTemplate.findByCriteria(
            DetachedCriteria.forClass(UserProfile.class).add(Restrictions.eq("email", oldEmail))));

    if (profile == null) {
        throw new NoSuchUserException("No user with the email: " + oldEmail);
    }

    boolean validPassword = passwordDigestService.verifyPassword(password, profile.getPassword());
    if (!validPassword) {
        throw new SecurityException("Invalid password");
    }

    int existingUserCount = DataAccessUtils.intResult(hibernateTemplate.findByCriteria(
            DetachedCriteria.forClass(UserProfile.class).add(Restrictions.eq("email", newEmail).ignoreCase())
                    .setProjection(Projections.count("email"))));
    if (existingUserCount > 0) {
        throw new DuplicateUserException(DuplicateUserException.Field.EMAIL);
    }

    log.debug("sending email change verification to {}", newEmail);
    profile.setVerificationToken(TokenGenerator.getUniqueToken());
    hibernateTemplate.update(profile);
    ambraMailer.sendChangeEmailNotice(oldEmail, newEmail, profile.getVerificationToken());

    return profile.getVerificationToken();
}

From source file:org.gwtwidgets.server.spring.GWTRPCServiceExporter.java

/**
 * Handles an exception which is raised when a method access is attempted to
 * a method which is not part of the RPC interface. This method is invoked
 * by {@link #processCall(String)}. This implementation throws a
 * {@link SecurityException}. For details on arguments please consult
 * {@link #invokeMethodOnService(Object, Method, Object[], RPCRequest)}.
 * /* w ww  .  j  a  v  a 2s  .  c o m*/
 * @param e
 *            Exception thrown
 * @param service
 * @param targetMethod
 * @return RPC encoded response (such as an RPC client exception)
 */
protected String handleIllegalAccessException(IllegalAccessException e, Object service, Method targetMethod,
        RPCRequest rpcRequest) {
    SecurityException securityException = new SecurityException("Blocked attempt to access inaccessible method "
            + targetMethod + (service != null ? " on service " + service : ""));
    securityException.initCause(e);
    throw securityException;
}

From source file:edu.umich.flowfence.service.KVSSharedPrefs.java

@Override
public synchronized Editor edit() {
    checkClosed();//from w w  w. j a  v  a2 s.  co m
    if (!isWritable) {
        throw new SecurityException("This SharedPreferences cannot be modified");
    }
    return new Editor();
}

From source file:org.sakaiproject.poll.service.impl.PollListManagerImpl.java

public List<Option> getOptionsForPoll(Long pollId) {
    Poll poll;//from  w  ww .  j  a va  2 s.c  om
    try {
        poll = getPollById(pollId, false);
    } catch (SecurityException e) {
        throw new SecurityException(e);
    }
    if (poll == null) {
        throw new IllegalArgumentException(
                "Cannot get options for a poll (" + pollId + ") that does not exist");
    }
    Search search = new Search();
    search.addRestriction(new Restriction("pollId", pollId));
    search.addOrder(new Order("optionId"));
    List<Option> optionList = dao.findBySearch(Option.class, search);
    return optionList;
}

From source file:org.sakaiproject.iclicker.tool.ToolController.java

public void processInstructorSSO(PageContext pageContext, HttpServletRequest request) {
    // admin/instructor check
    if (!this.isAdmin() && !this.isInstructor()) {
        throw new SecurityException("Current user is not an instructor and cannot access the instructor view");
    }/*www.j  a va  2s .c  om*/
    // SSO handling
    boolean ssoEnabled = logic.isSingleSignOnEnabled();
    pageContext.setAttribute("ssoEnabled", ssoEnabled);
    if (ssoEnabled) {
        String userKey = null;
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            if ((request.getParameter("generateKey") != null)) {
                userKey = logic.makeUserKey(null, true);
                ToolController.addMessage(pageContext, ToolController.KEY_INFO, "inst.sso.generated.new.key",
                        (Object[]) null);
            }
        }
        if (userKey == null) {
            userKey = logic.makeUserKey(null, false);
        }
        pageContext.setAttribute("ssoUserKey", userKey);
    }
}

From source file:com.alertlogic.aws.kinesis.test1.kcl.CountingRecordProcessorTest.java

/**
 * A test helper to prevent calls to System.exit() from existing our JVM. We need to test failure behavior and want
 * to know if System.exit() was called./*from   ww  w .java  2  s .  c o m*/
 *
 * @param testBlock A code block that is expected to call System.exit().
 */
private void expectSystemExitWhenExecuting(Callable<Void> testBlock) throws Exception {
    final SecurityException expectedPreventionOfSystemExit = new SecurityException(
            "System.exit not allowed for this test.");
    // Disable System.exit() for this test
    final SecurityManager sm = new SecurityManager() {
        @Override
        public void checkExit(int status) {
            throw expectedPreventionOfSystemExit;
        }

        @Override
        public void checkPermission(Permission perm) {
            // Do nothing, allowing this security manager to be replaced
        }
    };
    SecurityManager oldSm = System.getSecurityManager();
    System.setSecurityManager(sm);
    boolean systemExitCalled = false;
    try {
        testBlock.call();
        fail("Expected System.exit to be called and throw a SecurityException by our test SecurityManager");
    } catch (SecurityException ex) {
        assertEquals("Expected SecurityException to be thrown when System.exit called",
                expectedPreventionOfSystemExit, ex);
        systemExitCalled = true;
    } finally {
        System.setSecurityManager(oldSm);
    }
    assertTrue("Expected test to call System.exit", systemExitCalled);
}

From source file:net.metanotion.multitenant.adminapp.Manager.java

/** This method generates the appropriate predicate to be used by a
{@link net.metanotion.web.concrete.ObjectPrefixDispatcher} to verify whether an HTTP request against a tenant
instance by the currently authenticated user is allowed based on the user's status as either a tenant admin or
tenant owner. This predicated does NOT verify specific ooperations permitted only to owners or verify that the user
has provided their password for operations that require a password to initiate.
   @param adminDS the data source for the administrative web application database.
   @return The predicate to use with the {@link net.metanotion.web.concrete.ObjectPrefixDispatcher}
*//*from   w w  w. j a  v  a 2s . c  om*/
public static Predicate<Map.Entry<Object, RequestObject>, Exception> tenantUserPermissionPredicate(
        final DataSource adminDS) {
    return new Predicate<Map.Entry<Object, RequestObject>, Exception>() {
        @Override
        public void eval(final Map.Entry<Object, RequestObject> requestInfo) throws Exception {
            logger.debug("auth check on tid {} for uid {}", requestInfo.getKey(), requestInfo.getValue());
            final long tid = Long.parseLong(requestInfo.getValue().get(Constants.TENANT_ID).toString());
            final UserToken user = ((Unknown) requestInfo.getKey()).lookupInterface(UserToken.class);
            try (final Connection conn = adminDS.getConnection()) {
                if (tenantQueries.checkAuth(conn, user.getID(), tid).size() == 0) {
                    throw new SecurityException("Invalid tenant for user.");
                }
            }
        }
    };
}

From source file:org.openanzo.activemq.internal.SecurityBroker.java

@Override
public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout)
        throws Exception {
    final ServerSecurityContext securityContext = (ServerSecurityContext) context.getSecurityContext();
    if (securityContext == null) {
        MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
        String errorMsg = Messages.formatString(ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED,
                context.getConnectionId().toString());
        log.error(LogUtils.SECURITY_MARKER, errorMsg);
        MDC.clear();//w  ww . j  ava  2  s.  co  m
        throw new SecurityException(errorMsg);
    }
    // You don't need to be an admin to remove temp destinations.
    if (!destination.isTemporary()) {
        if (destination.getPhysicalName().startsWith("services/")) {
            if (!securityContext.getAnzoPrincipal().isSysadmin()) {
                MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
                MDC.put(LogUtils.USER, securityContext.getAnzoPrincipal().getName());
                String errorMsg = Messages.formatString(
                        ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED,
                        securityContext.getUserName(), "remove", destination.toString());
                log.info(LogUtils.SECURITY_MARKER, errorMsg);
                MDC.clear();
                throw new SecurityException(errorMsg);
            }
        } else if (destination.getPhysicalName().startsWith(NAMESPACES.NAMEDGRAPH_TOPIC_PREFIX)) {

        } else if (destination.getPhysicalName().startsWith(NAMESPACES.STREAM_TOPIC_PREFIX)) {

        }
    } else {
        if (!((ActiveMQTempDestination) destination).getConnectionId()
                .equals(context.getConnectionId().getValue())) {
            MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
            MDC.put(LogUtils.USER, securityContext.getAnzoPrincipal().getName());
            String errorMsg = Messages.formatString(
                    ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED, securityContext.getUserName(),
                    "remove", destination.toString());
            log.info(LogUtils.SECURITY_MARKER, errorMsg);
            MDC.clear();
            throw new SecurityException(errorMsg);
        }
    }
    super.removeDestination(context, destination, timeout);
}

From source file:org.jolokia.http.HttpRequestHandler.java

/**
 * Check whether the given host and/or address is allowed to access this agent.
 *
 * @param pHost host to check/*ww  w.  j a  v a 2s. co  m*/
 * @param pAddress address to check
 * @param pOrigin (optional) origin header to check also.
 */
public void checkAccess(String pHost, String pAddress, String pOrigin) {
    if (!backendManager.isRemoteAccessAllowed(pHost, pAddress)) {
        throw new SecurityException("No access from client " + pAddress + " allowed");
    }
    if (pOrigin != null && !backendManager.isOriginAllowed(pOrigin, true)) {
        throw new SecurityException("Origin " + pOrigin + " is not allowed to call this agent");
    }
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * //  w  w w.  j  av  a  2  s . co  m
 * 
 * @param ctx
 *            
 * @param cipherContent
 *            
 * @param key
 *            
 * @return byte[] ?
 * 
 */
public static byte[] symmetryDecrypt(SecurityContext ctx, byte[] cipherContent, Key key) {
    try {
        byte[] tContent = null;
        Cipher cipher = Cipher.getInstance(ctx.getSymmetryAlgorithm(), ctx.getJceProvider());
        SecureRandom secureRandom = SecureRandom.getInstance(ctx.getSecureRandomAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, key, secureRandom);
        tContent = cipher.doFinal(cipherContent);
        return tContent;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}