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.intalio.tempo.portlet.SecuredController.java

protected User authenticate(String token, String[] grantedRoles) throws SecurityException {
    try {//from ww w. java2  s .c o m
        Property[] props = _tokenService.getTokenProperties(token);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Token properties: " + PropertyUtils.toMap(props));
        }

        String name = extractUser(props);
        String[] roles = extractRoles(props);
        User user = new User(name, roles, token);
        if (grantedRoles.length > 0 && !user.hasOneRoleOf(grantedRoles)) {
            throw new SecurityException("User does not have one of the following role: "
                    + StringArrayUtils.toCommaDelimited(grantedRoles));
        }
        LOG.debug("User: " + user);
        return user;
    } catch (AuthenticationException ex) {
        throw new SecurityException(ex);
    } catch (RemoteException ex) {
        throw new SecurityException(ex);
    }
}

From source file:io.lavagna.service.CalendarService.java

public Calendar getUserCalendar(String userToken) throws URISyntaxException, ParseException {
    UserWithPermission user;//from   w  ww  .  ja va  2s  . c  om

    try {
        user = findUserFromCalendarToken(userToken);
    } catch (EmptyResultDataAccessException ex) {
        throw new SecurityException("Invalid token");
    }

    if (userRepository.isCalendarFeedDisabled(user)) {
        throw new SecurityException("Calendar feed disabled");
    }

    final Calendar calendar = new Calendar();
    calendar.getProperties().add(new ProdId("-//Lavagna//iCal4j 1.0//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    calendar.getProperties().add(CalScale.GREGORIAN);
    calendar.getProperties().add(Method.PUBLISH);

    final String applicationUrl = StringUtils
            .appendIfMissing(configurationRepository.getValue(Key.BASE_APPLICATION_URL), "/");

    final List<VEvent> events = new ArrayList<>();

    final SimpleDateFormat releaseDateFormatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");

    // Milestones
    List<Project> projects = projectService.findAllProjects(user);
    for (Project project : projects) {
        CardLabel milestoneLabel = cardLabelRepository.findLabelByName(project.getId(), "MILESTONE",
                CardLabel.LabelDomain.SYSTEM);

        Url mUrl = new Url(new URI(String.format("%s%s/milestones/", applicationUrl, project.getShortName())));

        for (LabelListValueWithMetadata m : cardLabelRepository
                .findListValuesByLabelId(milestoneLabel.getId())) {
            if (m.getMetadata().containsKey("releaseDate")) {

                java.util.Date date = releaseDateFormatter.parse(m.getMetadata().get("releaseDate") + " 12:00");

                SearchFilter filter = filter(SearchFilter.FilterType.MILESTONE, SearchFilter.ValueType.STRING,
                        m.getValue());
                SearchFilter notTrashFilter = filter(SearchFilter.FilterType.NOTLOCATION,
                        SearchFilter.ValueType.STRING, BoardColumn.BoardColumnLocation.TRASH.toString());
                SearchResults cards = searchService.find(Arrays.asList(filter, notTrashFilter), project.getId(),
                        null, user);

                double closed = 0;
                double total = 0;
                StringBuilder descBuilder = new StringBuilder();
                for (CardFullWithCounts card : cards.getFound()) {
                    if (card.getColumnDefinition() == ColumnDefinition.CLOSED) {
                        closed++;
                    }
                    total++;
                    descBuilder.append(getEventName(card));
                    descBuilder.append("\n");
                }

                final String name = String.format("%s - %s (%.0f%%)", project.getShortName(), m.getValue(),
                        total > 0 ? 100 * closed / total : 100);

                final VEvent event = new VEvent(new Date(date.getTime()), name);
                event.getProperties().getProperty(Property.DTSTART).getParameters().add(Value.DATE);

                event.getProperties().add(new Description(descBuilder.toString()));

                final UUID id = new UUID(getLong(m.getCardLabelId(), m.getId()), getLong(m.getOrder(), 0));
                event.getProperties().add(new Uid(id.toString()));

                // Reminder on milestone's date
                if (!m.getMetadata().containsKey("status") || m.getMetadata().get("status").equals("CLOSED")) {
                    final VAlarm reminder = new VAlarm(new Dur(0, 0, 0, 0));
                    reminder.getProperties().add(Action.DISPLAY);
                    reminder.getProperties().add(new Description(name));
                    event.getAlarms().add(reminder);
                }

                // Url
                event.getProperties().add(mUrl);

                events.add(event);
            }
        }
    }

    // Cards
    Map<Integer, UserDescription> usersCache = new HashMap<>();
    Map<Integer, CardFullWithCounts> map = new LinkedHashMap<>();

    SearchFilter locationFilter = filter(SearchFilter.FilterType.LOCATION, SearchFilter.ValueType.STRING,
            BoardColumn.BoardColumnLocation.BOARD.toString());

    SearchFilter aFilter = filter(SearchFilter.FilterType.ASSIGNED, SearchFilter.ValueType.CURRENT_USER, "me");
    for (CardFullWithCounts card : searchService.find(Arrays.asList(locationFilter, aFilter), null, null, user)
            .getFound()) {
        map.put(card.getId(), card);
    }

    SearchFilter wFilter = filter(SearchFilter.FilterType.WATCHED_BY, SearchFilter.ValueType.CURRENT_USER,
            "me");
    for (CardFullWithCounts card : searchService.find(Arrays.asList(locationFilter, wFilter), null, null, user)
            .getFound()) {
        map.put(card.getId(), card);
    }

    for (CardFullWithCounts card : map.values()) {

        Url cardUrl = new Url(new URI(String.format("%s%s/%s-%s", applicationUrl, card.getProjectShortName(),
                card.getBoardShortName(), card.getSequence())));

        CardDataHistory cardDesc = cardDataService.findLatestDescriptionByCardId(card.getId());

        for (LabelAndValue lav : card.getLabelsWithType(LabelType.TIMESTAMP)) {
            String name = getEventName(card);

            final VEvent event = new VEvent(new Date(lav.getLabelValueTimestamp()), name);
            event.getProperties().getProperty(Property.DTSTART).getParameters().add(Value.DATE);

            event.getProperties().add(new Created(new DateTime(card.getCreationDate())));
            event.getProperties().add(new LastModified(new DateTime(card.getLastUpdateTime())));

            final UUID id = new UUID(getLong(card.getColumnId(), card.getId()),
                    getLong(lav.getLabelId(), lav.getLabelValueId()));
            event.getProperties().add(new Uid(id.toString()));

            // Reminder on label's date
            if (card.getColumnDefinition() != ColumnDefinition.CLOSED) {
                final VAlarm reminder = new VAlarm(new Dur(0, 0, 0, 0));
                reminder.getProperties().add(Action.DISPLAY);
                reminder.getProperties().add(new Description(name));
                event.getAlarms().add(reminder);
            }

            // Organizer
            UserDescription ud = getUserDescription(card.getCreationUser(), usersCache);
            Organizer organizer = new Organizer(URI.create(ud.getEmail()));
            organizer.getParameters().add(new Cn(ud.getName()));
            event.getProperties().add(organizer);

            // Url
            event.getProperties().add(cardUrl);

            // Description
            if (cardDesc != null) {
                event.getProperties().add(new Description(cardDesc.getContent()));
            }

            events.add(event);
        }
    }

    calendar.getComponents().addAll(events);

    return calendar;
}

From source file:net.lightbody.bmp.proxy.jetty.util.URLResource.java

/**
 * Deletes the given resource//  www . java2 s . com
 */
public boolean delete() throws SecurityException {
    throw new SecurityException("Delete not supported");
}

From source file:org.fao.geonet.api.records.attachments.FilesystemStore.java

@Override
public Path getResource(ServiceContext context, String metadataUuid, String resourceId) throws Exception {
    // Those characters should not be allowed by URL structure
    if (resourceId.contains("..") || resourceId.startsWith("/") || resourceId.startsWith("file:/")) {
        throw new SecurityException(String.format("Invalid resource identifier '%s'.", resourceId));
    }//from   w  w w  .  ja  v a2  s  .  c om
    ApplicationContext _appContext = ApplicationContextHolder.get();
    AccessManager accessManager = _appContext.getBean(AccessManager.class);
    GeonetworkDataDirectory dataDirectory = _appContext.getBean(GeonetworkDataDirectory.class);
    String metadataId = getAndCheckMetadataId(metadataUuid);
    Path metadataDir = Lib.resource.getMetadataDir(dataDirectory, metadataId);

    Path resourceFile = null;

    boolean canDownload = accessManager.canDownload(context, metadataId);
    for (MetadataResourceVisibility r : MetadataResourceVisibility.values()) {
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(metadataDir.resolve(r.toString()),
                resourceId)) {
            for (Path path : directoryStream) {
                if (Files.isRegularFile(path)) {
                    resourceFile = path;
                }
            }
        } catch (IOException ignored) {
        }
    }

    if (resourceFile != null && Files.exists(resourceFile)) {
        if (resourceFile.getParent().getFileName().toString()
                .equals(MetadataResourceVisibility.PRIVATE.toString()) && !canDownload) {
            throw new SecurityException(String.format(
                    "Current user can't download resources for metadata '%s' and as such can't access the requested resource '%s'.",
                    metadataUuid, resourceId));
        }
        return resourceFile;
    } else {
        throw new ResourceNotFoundException(
                String.format("Metadata resource '%s' not found for metadata '%s'", resourceId, metadataUuid));
    }
}

From source file:org.jpublish.repository.filesystem.ExtendedFileSystemRepository.java

/**
 * Get an OutputStream for writing content to the given path.
 *
 * @param path The path to the content/*w  w w . ja  v  a2 s.  com*/
 * @return The OutputStream
 * @throws Exception
 */

public OutputStream getOutputStream(String path) throws Exception {
    if (!isWriteAllowed()) {
        throw new SecurityException("Writing not allowed");
    }

    return new FileOutputStream(pathToFile(path));
}

From source file:be.e_contract.eid.applet.service.impl.handler.SignatureDataMessageHandler.java

@Override
public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    byte[] signatureValue = message.signatureValue;
    List<X509Certificate> certificateChain = message.certificateChain;
    if (certificateChain.isEmpty()) {
        throw new ServletException("certificate chain is empty");
    }//from w ww  .j a  v  a 2  s . c  om
    X509Certificate signingCertificate = certificateChain.get(0);
    if (null == signingCertificate) {
        throw new ServletException("non-repudiation certificate missing");
    }
    LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal());
    PublicKey signingPublicKey = signingCertificate.getPublicKey();

    BeIDContextQualifier contextQualifier = new BeIDContextQualifier(request);

    /*
     * Verify the signature.
     */
    String digestAlgo = this.signatureState.getDigestAlgo();
    byte[] expectedDigestValue = this.signatureState.getDigestValue();
    if (digestAlgo.endsWith("-PSS")) {
        LOG.debug("verifying RSA/PSS signature");
        try {
            Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME);
            if ("SHA-256-PSS".equals(digestAlgo)) {
                LOG.debug("RSA/PSS SHA256");
                signature.setParameter(
                        new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
            }
            signature.initVerify(signingPublicKey);
            signature.update(expectedDigestValue);
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                        signingCertificate, signatureValue);
                this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage(), e);
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                    signingCertificate, signatureValue);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    } else {
        try {
            Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME);
            signature.initVerify(signingPublicKey);
            ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
            if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) {
                digestInfo.write(SHA1_DIGEST_INFO_PREFIX);
            } else if ("SHA-224".equals(digestAlgo)) {
                digestInfo.write(SHA224_DIGEST_INFO_PREFIX);
            } else if ("SHA-256".equals(digestAlgo)) {
                digestInfo.write(SHA256_DIGEST_INFO_PREFIX);
            } else if ("SHA-384".equals(digestAlgo)) {
                digestInfo.write(SHA384_DIGEST_INFO_PREFIX);
            } else if ("SHA-512".equals(digestAlgo)) {
                digestInfo.write(SHA512_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD160".equals(digestAlgo)) {
                digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD128".equals(digestAlgo)) {
                digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD256".equals(digestAlgo)) {
                digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX);
            }
            digestInfo.write(expectedDigestValue);
            signature.update(digestInfo.toByteArray());
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                        signingCertificate, signatureValue);
                this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage());
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                    signingCertificate, signatureValue);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    }

    SignatureEvent signatureEvent = new SignatureEvent(signatureValue, certificateChain);
    try {
        this.signatureEvent.select(contextQualifier).fire(signatureEvent);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    }

    if (null != signatureEvent.getError()) {
        SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.TRUST, signingCertificate);
        this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
        return new FinishedMessage(signatureEvent.getError());
    }
    return new FinishedMessage();
}

From source file:org.jboss.dashboard.users.UserStatus.java

/**
 * Determine if current user has given permission.
 *
 * @param perm permission to check// w ww  .ja  v  a 2  s. c om
 * @throws SecurityException if permission is denied
 */
public void checkPermission(Permission perm) throws SecurityException {
    if (!hasPermission(perm))
        throw new SecurityException("Permission denied.\r\n" + "permission=" + perm.toString() + "\r\n");
}

From source file:at.tfr.securefs.ui.ValidationBean.java

private void assureNonRevokedShares(List<String> revokedKeys) {
    if (revokedKeys != null && !revokedKeys.isEmpty()) {
        for (UiShare share : validationData.getUiShares()) {
            if (revokedKeys.stream().anyMatch(k -> share.equalsReal(k))) {
                throw new SecurityException("Invalid Use of RevokedKey: " + share);
            }/*from www .j  a  v a2 s  .  co  m*/
        }
    }
}

From source file:ch.rasc.wampspring.broker.SimpleBrokerMessageHandler.java

private void checkAuthentication(WampMessage wampMessage) {
    WampSession wampSession = wampMessage.getWampSession();
    if (wampSession != null && !wampSession.isAuthenticated() && this.authenticationRequiredGlobal) {
        throw new SecurityException("Not authenticated");
    }/*w  w w. j  ava  2 s.c  o m*/
}

From source file:dk.dma.msinm.user.UserService.java

/**
 * When creating a new user, check the roles assigned to the user.
 * <p>/*from w ww .  ja  va 2 s  .c o  m*/
 * A new user can always get the "user" role, e.g.via self-registration
 * on the website.
 * <p>
 * When an editor or administrator updates a user, they can only assign
 * roles they hold themselves.
 *
 * @param roles the roles to check
 */
private void validateRoleAssignment(String... roles) {

    // The "user" role can always be assigned
    if (roles.length == 1 && roles[0].equals("user")) {
        return;
    }

    // All other role assignments require a calling user with compatible roles
    User caller = findByPrincipal(ctx.getCallerPrincipal());
    if (caller == null) {
        throw new SecurityException("Invalid caller " + ctx.getCallerPrincipal());
    }
    Set<String> callerRoles = caller.getRoles().stream().map(Role::getName).collect(Collectors.toSet());
    for (String role : roles) {
        if (!callerRoles.contains(role)) {
            throw new SecurityException(
                    "Calling user " + ctx.getCallerPrincipal() + " cannot assign role " + role);
        }
    }
}