Example usage for java.security NoSuchAlgorithmException getMessage

List of usage examples for java.security NoSuchAlgorithmException getMessage

Introduction

In this page you can find the example usage for java.security NoSuchAlgorithmException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.globus.workspace.groupauthz.DecisionLogic.java

public Integer checkNewAltTargetURI(GroupRights rights, URI altTargetURI, String dn)
        throws AuthorizationException {

    if (altTargetURI == null) {
        throw new IllegalArgumentException("altTargetURI may not be null");
    }//from   w w w  .j  a v a2s .  c o  m

    if (rights == null) {
        throw new IllegalArgumentException("rights may not be null");
    }

    if (dn == null) {
        throw new IllegalArgumentException("DN may not be null");
    }

    final String dnhash;
    if (rights.isDirHashMode()) {
        try {
            dnhash = HashUtil.hashDN(dn);
        } catch (NoSuchAlgorithmException e) {
            final String msg = "ERROR: DN hash required but it " + "is not available: " + e.getMessage();
            throw new AuthorizationException(msg);
        }
    } else {
        dnhash = null;
    }

    final String hostname = rights.getImageNodeHostname();
    if (hostname != null) {
        if (!hostname.equalsIgnoreCase(altTargetURI.getHost())) {
            throw new AuthorizationException("You may only use images from host '" + hostname + "'");
        }
    }

    final String basedir = rights.getImageBaseDirectory();
    if (basedir == null) {
        return Decision.PERMIT; // *** EARLY RETURN ***
    }

    final String comparisonDir;

    try {
        comparisonDir = normalize(basedir, null);
    } catch (ResourceRequestDeniedException e) {
        throw new AuthorizationException(e.getMessage(), e);
    }

    if (!basedir.equals(comparisonDir)) {
        logger.debug("Configured base directory policy normalized from '" + basedir + "' into '" + comparisonDir
                + "'");
    }

    String subdir = null;
    if (dnhash != null) {
        subdir = comparisonDir + "/" + dnhash;
    }

    if (!altTargetURI.getPath().startsWith(comparisonDir)) {

        throw new AuthorizationException("You may only save images to alternate "
                + "locations starting with base directory '" + comparisonDir + "'");
    }

    if (subdir != null && !altTargetURI.getPath().startsWith(subdir)) {

        throw new AuthorizationException("You may only save images to alternate "
                + "locations starting with base directory '" + subdir + "'");
    }

    return Decision.PERMIT;
}

From source file:eionet.meta.imp.VocabularyRDFImportHandler.java

/**
 * Constructor for RDFHandler to import rdf into vocabulary.
 *
 * @param folderContextRoot//from ww  w.  ja v a2  s  . c  o  m
 *            base uri for vocabulary.
 * @param concepts
 *            concepts of vocabulary
 * @param boundElements
 *            bound elements to vocabulary.
 * @param boundElementsToIds
 *            bound elements ids.
 * @param boundURIs
 *            rdf namespaces for bound elements
 * @param workingLanguage
 *            working language, only first two letters are used
 * @param createNewDataElementsForPredicates
 *            create new data elements for seen predicates
 * @param ddNamespace
 *            dd instance namespace
 * @throws ServiceException
 *             when digest algorithm cannot be found
 */
public VocabularyRDFImportHandler(String folderContextRoot, List<VocabularyConcept> concepts,
        Map<String, Integer> boundElementsToIds, Map<String, List<String>> boundElements,
        Map<String, String> boundURIs, boolean createNewDataElementsForPredicates, String workingLanguage,
        String ddNamespace) throws ServiceException {
    super(folderContextRoot, concepts, boundElementsToIds);
    this.boundElements = boundElements;
    this.createNewDataElementsForPredicates = createNewDataElementsForPredicates;
    this.boundURIs = boundURIs;
    this.attributePositions = new HashMap<String, Map<String, Integer>>();
    this.predicateUpdatesAtConcepts = new HashMap<String, Set<Integer>>();
    this.notBoundPredicates = new HashSet<String>();
    this.identifierOfPredicate = new HashMap<String, String>();
    this.conceptsUpdatedForAttributes = new HashMap<String, Set<Integer>>();
    this.conceptsUpdatedForAttributes.put(SKOS_CONCEPT_ATTRIBUTE_NS + ":" + PREF_LABEL, new HashSet<Integer>());
    this.conceptsUpdatedForAttributes.put(SKOS_CONCEPT_ATTRIBUTE_NS + ":" + DEFINITION, new HashSet<Integer>());
    this.conceptsUpdatedForAttributes.put(SKOS_CONCEPT_ATTRIBUTE_NS + ":" + NOTATION, new HashSet<Integer>());
    this.lastCandidateForConceptAttribute = new HashMap<String, Literal>();
    // get first two letters of working language since, it can be like en-US
    this.workingLanguage = StringUtils.substring(workingLanguage, 0, 2);
    this.ddNamespace = ddNamespace;
    this.seenStatementsHashCodes = new HashSet<BigInteger>();
    try {
        this.messageDigestInstance = MessageDigest.getInstance(HASHING_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new ServiceException(e.getMessage());
    }
}

From source file:com.qut.middleware.spep.authn.bindings.impl.ArtifactProcessorImpl.java

public void afterPropertiesSet() {
    if (this.entityIdentifier == null || this.sourceID == null) {
        throw new IllegalArgumentException("ESOE identifier has not been specified correctly.");
    }// w ww .ja v a 2  s  .c o  m

    if (this.identifierGenerator == null) {
        throw new IllegalArgumentException("Identifier generator has not been specified correctly.");
    }

    if (this.nodeIndex == -1) {
        throw new IllegalArgumentException("Node index has not been specified correctly.");
    }

    try {
        this.random = SecureRandom.getInstance(this.RNG);
        this.random.setSeed(System.currentTimeMillis());

        String packages = ArtifactResolve.class.getPackage().getName();
        String[] schema = new String[] { SchemaConstants.samlProtocol };
        this.artifactResponseMarshaller = new MarshallerImpl<ArtifactResponse>(packages, schema,
                this.keystoreResolver);
        this.artifactResponseUnmarshaller = new UnmarshallerImpl<ArtifactResponse>(packages, schema,
                this.metadataProcessor);
        this.artifactResolveMarshaller = new MarshallerImpl<ArtifactResolve>(packages, schema,
                this.keystoreResolver);
        this.artifactResolveUnmarshaller = new UnmarshallerImpl<ArtifactResolve>(packages, schema,
                this.metadataProcessor);

        this.artifactMap = new ConcurrentHashMap<String, Artifact>();
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(
                "No such algorithm exists for the PRNG. Unable to continue. Error: " + e.getMessage(), e);
    } catch (MarshallerException e) {
        throw new IllegalArgumentException(
                "Error initializing marshaller. Unable to continue. Error: " + e.getMessage(), e);
    } catch (UnmarshallerException e) {
        throw new IllegalArgumentException(
                "Error intitializing unmarshaller. Unable to continue. Error: " + e.getMessage(), e);
    }
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public String getMediaIds(File[] pics, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    String ids = "";

    for (int i = 0; i < pics.length; i++) {
        File file = pics[i];/*from   w w  w. j a v a 2  s .  c  o  m*/
        try {
            AccessToken token = twitter.getOAuthAccessToken();
            String oauth_token = token.getToken();
            String oauth_token_secret = token.getTokenSecret();

            // generate authorization header
            String get_or_post = "POST";
            String oauth_signature_method = "HMAC-SHA1";

            String uuid_string = UUID.randomUUID().toString();
            uuid_string = uuid_string.replaceAll("-", "");
            String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

            // get the timestamp
            Calendar tempcal = Calendar.getInstance();
            long ts = tempcal.getTimeInMillis();// get current time in milliseconds
            String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

            // the parameter string must be in alphabetical order, "text" parameter added at end
            String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                    + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                    + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
            System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

            String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json";
            String twitter_endpoint_host = "upload.twitter.com";
            String twitter_endpoint_path = "/1.1/media/upload.json";
            String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                    + encode(parameter_string);
            String oauth_signature = computeSignature(signature_base_string,
                    AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

            String authorization_header_string = "OAuth oauth_consumer_key=\""
                    + AppSettings.TWITTER_CONSUMER_KEY
                    + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                    + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                    + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
            HttpProtocolParams.setUseExpectContinue(params, false);
            HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                    // Required protocol interceptors
                    new RequestContent(), new RequestTargetHost(),
                    // Recommended protocol interceptors
                    new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

            HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
            HttpContext context = new BasicHttpContext(null);
            HttpHost host = new HttpHost(twitter_endpoint_host, 443);
            DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

            try {
                try {
                    SSLContext sslcontext = SSLContext.getInstance("TLS");
                    sslcontext.init(null, null, null);
                    SSLSocketFactory ssf = sslcontext.getSocketFactory();
                    Socket socket = ssf.createSocket();
                    socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                    conn.bind(socket, params);

                    BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST",
                            twitter_endpoint_path);

                    // need to add status parameter to this POST
                    MultipartEntity reqEntity = new MultipartEntity();

                    FileBody sb_image = new FileBody(file);
                    reqEntity.addPart("media", sb_image);

                    request2.setEntity(reqEntity);
                    request2.setParams(params);

                    request2.addHeader("Authorization", authorization_header_string);
                    System.out.println(
                            "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing...");
                    httpexecutor.preProcess(request2, httpproc, context);
                    HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                    System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing...");
                    response2.setParams(params);
                    httpexecutor.postProcess(response2, httpproc, context);
                    String responseBody = EntityUtils.toString(response2.getEntity());
                    System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody);
                    // error checking here. Otherwise, status should be updated.
                    jsonresponse = new JSONObject(responseBody);
                    if (jsonresponse.has("errors")) {
                        JSONObject temp_jo = new JSONObject();
                        temp_jo.put("response_status", "error");
                        temp_jo.put("message",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message"));
                        temp_jo.put("twitter_code",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code"));
                        jsonresponse = temp_jo;
                    }

                    // add it to the media_ids string
                    ids += jsonresponse.getString("media_id_string");
                    if (i != pics.length - 1) {
                        ids += ",";
                    }

                    conn.close();
                } catch (HttpException he) {
                    System.out.println(he.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia HttpException message=" + he.getMessage());
                    return null;
                } catch (NoSuchAlgorithmException nsae) {
                    System.out.println(nsae.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage());
                    return null;
                } catch (KeyManagementException kme) {
                    System.out.println(kme.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia KeyManagementException message=" + kme.getMessage());
                    return null;
                } finally {
                    conn.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage());
                return null;
            }
        } catch (Exception e) {
            return null;
        }

    }
    return ids;
}

From source file:org.atricore.idbus.kernel.main.authn.scheme.UsernamePasswordAuthScheme.java

/**
 * Only invoke this if algorithm is set.
 *
 * @throws SSOAuthenticationException//w ww  .j  av  a 2  s.c  o m
 */
protected MessageDigest getDigest() throws SSOAuthenticationException {

    MessageDigest _digest = null;
    if (_hashAlgorithm != null) {

        try {
            _digest = MessageDigest.getInstance(_hashAlgorithm);
            logger.debug("Using hash algorithm/encoding : " + _hashAlgorithm + "/" + _hashEncoding);
        } catch (NoSuchAlgorithmException e) {
            logger.error("Algorithm not supported : " + _hashAlgorithm, e);
            throw new SSOAuthenticationException(e.getMessage(), e);
        }
    }

    return _digest;

}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceImpl.java

/**
 * Encode the user ID in a secure cookie.
 *
 * @param userId//from   w w  w. jav a 2s  . co m
 * @return
 */
String encodeCookie(String userId, String tokenType) {
    if (userId == null) {
        return null;
    }
    if (clusterCookieServer != null) {
        return clusterCookieServer.encodeCookie(userId);
    } else {
        long expires = System.currentTimeMillis() + ttl;
        SecureCookie secretKeyHolder = tokenStore.getActiveToken();

        try {
            return secretKeyHolder.encode(expires, userId, tokenType);
        } catch (NoSuchAlgorithmException e) {
            LOG.error(e.getMessage(), e);
        } catch (InvalidKeyException e) {
            LOG.error(e.getMessage(), e);
        } catch (IllegalStateException e) {
            LOG.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            LOG.error(e.getMessage(), e);
        } catch (SecureCookieException e) {
            if (e.isError()) {
                LOG.error(e.getMessage(), e);
            } else {
                LOG.info(e.getMessage(), e);
            }
        }
        return null;
    }
}

From source file:org.sakaiproject.nakamura.lite.accesscontrol.AccessControlManagerImpl.java

public void setAcl(String objectType, String objectPath, AclModification[] aclModifications)
        throws StorageClientException, AccessDeniedException {
    checkOpen();//from  w w  w  .j  a v  a  2  s . co m
    check(objectType, objectPath, Permissions.CAN_WRITE_ACL);
    check(objectType, objectPath, Permissions.CAN_READ_ACL);
    String key = this.getAclKey(objectType, objectPath);
    Map<String, Object> currentAcl = getCached(keySpace, aclColumnFamily, key);
    // every ACL gets a secret key, which avoids doing it later with a special call
    Map<String, Object> modifications = Maps.newLinkedHashMap();
    if (!currentAcl.containsKey(_SECRET_KEY)) {
        byte[] secretKeySeed = new byte[20];
        secureRandom.nextBytes(secretKeySeed);
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA1");
            modifications.put(_SECRET_KEY, Base64.encodeBase64URLSafeString(md.digest(secretKeySeed)));
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    if (!currentAcl.containsKey(_KEY)) {
        modifications.put(_KEY, key);
        modifications.put(_OBJECT_TYPE, objectType); // this is here to make data migration possible in the future 
        modifications.put(_PATH, objectPath); // same
    }
    for (AclModification m : aclModifications) {
        String name = m.getAceKey();
        if (READ_ONLY_PROPERTIES.contains(name)) {
            continue;
        }
        if (m.isRemove()) {
            modifications.put(name, null);
        } else {

            int originalbitmap = getBitMap(name, modifications, currentAcl);
            int modifiedbitmap = m.modify(originalbitmap);
            LOGGER.debug("Adding Modification {} {} ", name, modifiedbitmap);
            modifications.put(name, modifiedbitmap);

            // KERN-1515
            // We need to modify the opposite key to apply the
            // reverse of the change we just made. Otherwise,
            // you can end up with ACLs with contradictions, like:
            // anonymous@g=1, anonymous@d=1
            if (containsKey(inverseKeyOf(name), modifications, currentAcl)) {
                // XOR gives us a mask of only the bits that changed
                int difference = originalbitmap ^ modifiedbitmap;
                int otherbitmap = toInt(getBitMap(inverseKeyOf(name), modifications, currentAcl));

                // Zero out the bits that have been modified
                //
                // KERN-1887: This was originally toggling the modified bits
                // using: "otherbitmap ^ difference", but this would
                // incorrectly grant permissions in some cases (see JIRA
                // issue).  To avoid inconsistencies between grant and deny
                // lists, setting a bit in one list should unset the
                // corresponding bit in the other.
                int modifiedotherbitmap = otherbitmap & ~difference;

                if (otherbitmap != modifiedotherbitmap) {
                    // We made a change.  Record our modification.
                    modifications.put(inverseKeyOf(name), modifiedotherbitmap);
                }
            }
        }
    }
    LOGGER.debug("Updating ACL {} {} ", key, modifications);
    putCached(keySpace, aclColumnFamily, key, modifications, (currentAcl == null || currentAcl.size() == 0));
    storeListener.onUpdate(objectType, objectPath, getCurrentUserId(), false, null, "op:acl");
}

From source file:org.dataconservancy.packaging.tool.model.ipm.FileInfo.java

/**
 * Default constructor that should be used in most cases. Will read the file at the path location and load the necessary file attributes.
 * @param path The path to the file./*from  w w  w  . jav  a  2s. c  o m*/
 */
public FileInfo(Path path) {
    location = path.toUri();
    name = path.getFileName().toString();

    try {
        fileAttributes = new FileInfoAttributes(Files.readAttributes(path, BasicFileAttributes.class));
        if (fileAttributes.isRegularFile()) {
            checksums = new HashMap<>();
            formats = new ArrayList<>();

            MessageDigest md5 = null;
            MessageDigest sha1 = null;

            try {
                md5 = MessageDigest.getInstance("MD5");
                sha1 = MessageDigest.getInstance("SHA-1");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e.getMessage(), e);
            }

            try (ChecksumCalculatingInputStream in = new ChecksumCalculatingInputStream(
                    Files.newInputStream(path), Arrays.asList(md5, sha1))) {

                IOUtils.copy(in, new NullOutputStream());

                in.digests().forEach((md, digest) -> {
                    String encoded = Hex.encodeHexString(digest);
                    if (md.getAlgorithm().equals("MD5")) {
                        checksums.put(Algorithm.MD5, encoded);
                    }

                    if (md.getAlgorithm().equals("SHA-1")) {
                        checksums.put(Algorithm.SHA1, encoded);
                    }
                });
            }

            List<DetectedFormat> fileFormats = ContentDetectionService.getInstance()
                    .detectFormats(path.toFile());
            for (DetectedFormat format : fileFormats) {
                if (format.getId() != null && !format.getId().isEmpty()) {
                    formats.add(createFormatURIString(format));
                }

                if (format.getMimeType() != null && !format.getMimeType().isEmpty()) {
                    formats.add(format.getMimeType());
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.qut.middleware.esoe.sso.plugins.artifact.impl.ArtifactProcessorImpl.java

public void afterPropertiesSet() {
    if (this.entityIdentifier == null || this.sourceID == null) {
        throw new IllegalArgumentException("ESOE identifier has not been specified correctly.");
    }//  w ww.ja  v a  2s  .  c o m

    if (this.identifierGenerator == null) {
        throw new IllegalArgumentException("Identifier generator has not been specified correctly.");
    }

    if (this.nodeIndex == -1) {
        throw new IllegalArgumentException("Node index has not been specified correctly.");
    }

    try {
        this.random = SecureRandom.getInstance(this.RNG);
        this.random.setSeed(System.currentTimeMillis());

        String packages = ArtifactResolve.class.getPackage().getName();
        String[] schema = new String[] { SchemaConstants.samlProtocol };
        this.artifactResponseMarshaller = new MarshallerImpl<ArtifactResponse>(packages, schema,
                this.keystoreResolver);
        this.artifactResponseUnmarshaller = new UnmarshallerImpl<ArtifactResponse>(packages, schema,
                this.metadataProcessor);
        this.artifactResolveMarshaller = new MarshallerImpl<ArtifactResolve>(packages, schema,
                this.keystoreResolver);
        this.artifactResolveUnmarshaller = new UnmarshallerImpl<ArtifactResolve>(packages, schema,
                this.metadataProcessor);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(
                "No such algorithm exists for the PRNG. Unable to continue. Error: " + e.getMessage(), e);
    } catch (MarshallerException e) {
        throw new IllegalArgumentException(
                "Error initializing marshaller. Unable to continue. Error: " + e.getMessage(), e);
    } catch (UnmarshallerException e) {
        throw new IllegalArgumentException(
                "Error intitializing unmarshaller. Unable to continue. Error: " + e.getMessage(), e);
    }
}

From source file:com.telesign.util.TeleSignRequest.java

/**
 * Set the TLS protocol to TLSv1.2// ww  w .  j  ava 2s .  c  om
 */
private void setTLSProtocol() {
    SSLContext sslContext;
    try {
        // setting ssl instance to TLSv1.x
        sslContext = SSLContext.getInstance(httpsProtocol);

        // sslContext initialize
        sslContext.init(null, null, new SecureRandom());

        // typecasting ssl with HttpsUrlConnection and setting sslcontext
        ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (NoSuchAlgorithmException e1) {
        System.err.println("Received No Such Alogorithm Exception " + e1.getMessage());
    } catch (KeyManagementException e) {
        System.err.println("Key Management Exception received " + e.getMessage());
    }
}