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.directwebremoting.jaxer.servlet.JaxerInterfaceHandler.java

@Override
protected String generateTemplate(String contextPath, String servletPath, String pathInfo) throws IOException {
    String fullCreatorName = pathInfo;

    if (!fullCreatorName.endsWith(PathConstants.EXTENSION_JS)) {
        return null;
    }/*from ww w  .  j a va 2 s . c om*/

    fullCreatorName = fullCreatorName.replaceFirst("/", "");
    fullCreatorName = fullCreatorName.replace(PathConstants.EXTENSION_JS, "");

    // Lookup the module using long creatorName
    Module module = moduleManager.getModule(fullCreatorName, false);
    if (module == null) {
        log.warn("Failed to find creator using: " + fullCreatorName);
        throw new SecurityException("Failed to find creator");
    }

    // Internally use short scriptName
    String scriptName = module.getName();

    return generateInterfaceScript(contextPath, servletPath, scriptName);
}

From source file:io.romain.passport.logic.observables.LastKnownLocationObservable.java

@Override
public void call(Subscriber<? super Location> subscriber) {
    if (ContextCompat.checkSelfPermission(mClient.getContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(mClient.getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

        Location location = LocationServices.FusedLocationApi.getLastLocation(mClient);
        if (location != null) {
            subscriber.onNext(location);
        }//from   ww w . j a v  a  2 s.  com
        subscriber.onCompleted();
    } else {
        subscriber.onError(new SecurityException("You don't have the permission..."));
    }
}

From source file:com.dgq.utils.EncodeUtils.java

/**
 * URL ?, EncodeUTF-8.//from   w w w .j  av  a  2 s  .  c  o  m
 */
public static String urlEncode(String part) {
    try {
        return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new SecurityException("URL?!");
    }
}

From source file:ma.glasnost.orika.test.converter.CloneableConverterNoSetAccessibleTestCase.java

@Test
public void cloneableConverterWithoutSetAccessible() throws DatatypeConfigurationException {

    final SecurityManager initialSm = System.getSecurityManager();
    try {/*w w  w. j  a  v  a  2s .  com*/
        System.setSecurityManager(new SecurityManager() {
            public void checkPermission(java.security.Permission perm) {
                if ("suppressAccessChecks".equals(perm.getName())) {
                    for (StackTraceElement ste : new Throwable().getStackTrace()) {
                        if (ste.getClassName().equals(CloneableConverter.class.getCanonicalName())) {
                            throw new SecurityException("not permitted");
                        }
                    }
                }
            }
        });

        CloneableConverter cc = new CloneableConverter(SampleCloneable.class);

        MapperFactory factory = MappingUtil.getMapperFactory();
        factory.getConverterFactory().registerConverter(cc);

        GregorianCalendar cal = new GregorianCalendar();
        cal.add(Calendar.YEAR, 10);
        XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar((GregorianCalendar) cal);
        cal.add(Calendar.MONTH, 3);

        ClonableHolder source = new ClonableHolder();
        source.value = new SampleCloneable();
        source.value.id = 5L;
        source.date = new Date(System.currentTimeMillis() + 100000);
        source.timestamp = new Timestamp(System.currentTimeMillis() + 50000);
        source.calendar = cal;
        source.xmlCalendar = xmlCal;

        ClonableHolder dest = factory.getMapperFacade().map(source, ClonableHolder.class);
        Assert.assertEquals(source.value, dest.value);
        Assert.assertNotSame(source.value, dest.value);
        Assert.assertEquals(source.date, dest.date);
        Assert.assertNotSame(source.date, dest.date);
        Assert.assertEquals(source.timestamp, dest.timestamp);
        Assert.assertNotSame(source.timestamp, dest.timestamp);
        Assert.assertEquals(source.calendar, dest.calendar);
        Assert.assertNotSame(source.calendar, dest.calendar);
        Assert.assertEquals(source.xmlCalendar, dest.xmlCalendar);
        Assert.assertNotSame(source.xmlCalendar, dest.xmlCalendar);
    } finally {
        System.setSecurityManager(initialSm);
    }
}

From source file:com.auditbucket.helper.SecurityHelper.java

public String getUserName(boolean exceptionOnNull, boolean isSysUser) {
    Authentication a = SecurityContextHolder.getContext().getAuthentication();
    if (a == null)
        if (exceptionOnNull)
            throw new SecurityException("User is not authenticated");
        else/*from  w w  w  .ja v a 2s . c o  m*/
            return null;

    if (isSysUser) {
        SystemUser su = getSysUser(a.getName());
        if (su == null)
            throw new IllegalArgumentException("Not authorised");
    }
    return a.getName();
}

From source file:io.mapzone.controller.catalog.csw.TransactionResponse.java

@Override
protected void doExecute() throws Exception {
    try (UnitOfWork uow = CatalogPlugin.instance().catalog().unitOfWork();) {
        // XXX check origin for authorisation
        // when fixed then also change the catalog server URL the controller
        // sends to clients via ArenaConfig
        log.info("Remote:" + request().httpRequest().getRemoteHost());
        if (!request().httpRequest().getRemoteHost().equals("127.0.0.1")) {
            throw new SecurityException("Authorisation missing.");
        }//  w ww. ja  v a 2 s  . co  m

        TransactionType tx = request().<TransactionType>parsedBody().get();

        for (Object op : tx.getInsertOrUpdateOrDelete()) {
            if (op instanceof InsertType) {
                handleInsert((InsertType) op, uow);
            } else if (op instanceof UpdateType) {
                handleUpdate((UpdateType) op, uow);
            } else if (op instanceof DeleteType) {
                handleDelete((DeleteType) op, uow);
            } else {
                throw new RuntimeException("Unhandled op type: " + op);
            }
        }
        uow.commit();
    }
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Verifies the certificate authenticity using the configured TrustStore and the signature of
 * the speechlet request./*from  w  w  w.  j  a  va 2s  . co  m*/
 *
 * @param serializedSpeechletRequest
 *            speechlet request serialized as a string of JSON
 * @param baseEncoded64Signature
 *            the signature for provided in the request header
 * @param signingCertificateChainUrl
 *            the certificate chain URL provided in the request header
 */
public static void checkRequestSignature(final byte[] serializedSpeechletRequest,
        final String baseEncoded64Signature, final String signingCertificateChainUrl) {
    if ((baseEncoded64Signature == null) || (signingCertificateChainUrl == null)) {
        throw new SecurityException("Missing signature/certificate for the provided speechlet request");
    }

    try {
        X509Certificate signingCertificate;
        if (CERTIFICATE_CACHE.containsKey(signingCertificateChainUrl)) {
            signingCertificate = CERTIFICATE_CACHE.get(signingCertificateChainUrl);
            /*
             * check the before/after dates on the certificate are still valid for the present
             * time
             */
            signingCertificate.checkValidity();
        } else {
            signingCertificate = retrieveAndVerifyCertificateChain(signingCertificateChainUrl);

            // if certificate is valid, then add it to the cache
            CERTIFICATE_CACHE.put(signingCertificateChainUrl, signingCertificate);
        }

        // verify that the request was signed by the provided certificate
        Signature signature = Signature.getInstance(Sdk.SIGNATURE_ALGORITHM);
        signature.initVerify(signingCertificate.getPublicKey());
        signature.update(serializedSpeechletRequest);
        if (!signature.verify(Base64.decodeBase64(baseEncoded64Signature.getBytes(Sdk.CHARACTER_ENCODING)))) {
            throw new SecurityException(
                    "Failed to verify the signature/certificate for the provided speechlet request");
        }
    } catch (CertificateException | SignatureException | NoSuchAlgorithmException | InvalidKeyException
            | IOException ex) {
        throw new SecurityException(
                "Failed to verify the signature/certificate for the provided speechlet request", ex);
    }
}

From source file:org.directwebremoting.servlet.DtoHandler.java

@Override
protected String generateTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!generateDtoClasses.matches(".*\\bdto\\b.*")) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return "";
    }//  www  . j av a 2s .com

    String jsClassName = request.getPathInfo();

    if (!jsClassName.startsWith(dtoHandlerUrl) || !jsClassName.endsWith(PathConstants.EXTENSION_JS)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return "";
    }

    jsClassName = jsClassName.substring(dtoHandlerUrl.length());
    jsClassName = jsClassName.substring(0, jsClassName.length() - PathConstants.EXTENSION_JS.length());

    if (!LocalUtil.isJavaIdentifierWithPackage(jsClassName)) {
        log.debug("Throwing at request for class with name: '" + jsClassName + "'");
        throw new SecurityException("Class names must comply with Java package and class identifiers");
    }

    return remoter.generateDtoScript(jsClassName);
}

From source file:eu.forgestore.ws.util.ShiroUTValidator.java

public String validate(UsernameToken usernameToken) throws LoginException {

    if (usernameToken == null) {
        throw new SecurityException("noCredential");
    }/*from   w  ww  .ja v a2 s  . com*/
    // Validate the UsernameToken

    String pwType = usernameToken.getPasswordType();
    logger.info("UsernameToken user " + usernameToken.getName());
    logger.info("UsernameToken password " + usernameToken.getPassword());
    logger.info("UsernameToken password type " + pwType);

    //      if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
    //         if (log.isDebugEnabled()) {
    //            logger.debug("Authentication failed - digest passwords are not accepted");
    //         }
    //         throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    //      }

    if (usernameToken.getPassword() == null) {

        logger.debug("Authentication failed - no password was provided");

        throw new FailedLoginException("Sorry! No login for you.");
    }

    // Validate it via Shiro
    Subject currentUser = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(usernameToken.getName(),
            usernameToken.getPassword());
    token.setRememberMe(true);
    try {
        currentUser.login(token);
        currentUser.getSession().setAttribute("aKey", UUID.randomUUID().toString());
    } catch (AuthenticationException ex) {
        logger.info(ex.getMessage(), ex);
        throw new FailedLoginException("Sorry! No login for you.");
    }
    // Perform authorization check
    if (!requiredRoles.isEmpty() && !currentUser.hasAllRoles(requiredRoles)) {
        logger.info("Authorization failed for authenticated user");
        throw new FailedLoginException("Sorry! No login for you.");
    }

    return (String) currentUser.getPrincipal();
}

From source file:org.callistasoftware.netcare.web.controller.HomeController.java

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String goHome() {

    log.info("User {} is being redirected to home");
    final UserBaseView user = this.getLoggedInUser();
    if (user == null) {
        throw new SecurityException("User is not logged in");
    }/*from w  w  w  . ja  v a 2s  . c  om*/

    if (user.isCareActor()) {
        log.debug("Redirecting to admin home");
        return "redirect:admin/home";
    }

    log.debug("Redirecting to user home");
    return "redirect:user/home";
}