Example usage for java.security NoSuchAlgorithmException toString

List of usage examples for java.security NoSuchAlgorithmException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.purl.sword.server.DepositServlet.java

/**
 * Process a post request./*from   w w  w.  j  av a 2  s.  co  m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Create the Deposit request
    Deposit d = new Deposit();
    Date date = new Date();
    log.debug("Starting deposit processing at " + date.toString() + " by " + request.getRemoteAddr());

    // Are there any authentication details?
    String usernamePassword = getUsernamePassword(request);
    if ((usernamePassword != null) && (!usernamePassword.equals(""))) {
        int p = usernamePassword.indexOf(':');
        if (p != -1) {
            d.setUsername(usernamePassword.substring(0, p));
            d.setPassword(usernamePassword.substring(p + 1));
        }
    } else if (authenticateWithBasic()) {
        String s = "Basic realm=\"SWORD\"";
        response.setHeader("WWW-Authenticate", s);
        response.setStatus(401);
        return;
    }

    // Set up some variables
    String filename = null;

    // Do the processing
    try {
        // Write the file to the temp directory
        filename = tempDirectory + "SWORD-" + request.getRemoteAddr() + "-" + counter.addAndGet(1);
        log.debug("Package temporarily stored as: " + filename);
        InputStream inputstream = request.getInputStream();
        OutputStream outputstream = new FileOutputStream(new File(filename));
        try {
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputstream.read(buf)) > 0) {
                outputstream.write(buf, 0, len);
            }
        } finally {
            inputstream.close();
            outputstream.close();
        }

        // Check the size is OK
        File file = new File(filename);
        long fLength = file.length() / 1024;
        if ((maxUploadSize != -1) && (fLength > maxUploadSize)) {
            this.makeErrorDocument(ErrorCodes.MAX_UPLOAD_SIZE_EXCEEDED,
                    HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                    "The uploaded file exceeded the maximum file size this server will accept (the file is "
                            + fLength + "kB but the server will only accept files as large as " + maxUploadSize
                            + "kB)",
                    request, response);
            return;
        }

        // Check the MD5 hash
        String receivedMD5 = ChecksumUtils.generateMD5(filename);
        log.debug("Received filechecksum: " + receivedMD5);
        d.setMd5(receivedMD5);
        String md5 = request.getHeader("Content-MD5");
        log.debug("Received file checksum header: " + md5);
        if ((md5 != null) && (!md5.equals(receivedMD5))) {
            // Return an error document
            this.makeErrorDocument(ErrorCodes.ERROR_CHECKSUM_MISMATCH,
                    HttpServletResponse.SC_PRECONDITION_FAILED,
                    "The received MD5 checksum for the deposited file did not match the checksum sent by the deposit client",
                    request, response);
            log.debug("Bad MD5 for file. Aborting with appropriate error message");
            return;
        } else {
            // Set the file to be deposited
            d.setFile(file);

            // Set the X-On-Behalf-Of header
            String onBehalfOf = request.getHeader(HttpHeaders.X_ON_BEHALF_OF.toString());
            if ((onBehalfOf != null) && (onBehalfOf.equals("reject"))) {
                // user name is "reject", so throw a not know error to allow the client to be tested
                throw new SWORDErrorException(ErrorCodes.TARGET_OWNER_UKNOWN, "unknown user \"reject\"");
            } else {
                d.setOnBehalfOf(onBehalfOf);
            }

            // Set the X-Packaging header
            d.setPackaging(request.getHeader(HttpHeaders.X_PACKAGING));

            // Set the X-No-Op header
            String noop = request.getHeader(HttpHeaders.X_NO_OP);
            log.error("X_NO_OP value is " + noop);
            if ((noop != null) && (noop.equals("true"))) {
                d.setNoOp(true);
            } else if ((noop != null) && (noop.equals("false"))) {
                d.setNoOp(false);
            } else if (noop == null) {
                d.setNoOp(false);
            } else {
                throw new SWORDErrorException(ErrorCodes.ERROR_BAD_REQUEST, "Bad no-op");
            }

            // Set the X-Verbose header
            String verbose = request.getHeader(HttpHeaders.X_VERBOSE);
            if ((verbose != null) && (verbose.equals("true"))) {
                d.setVerbose(true);
            } else if ((verbose != null) && (verbose.equals("false"))) {
                d.setVerbose(false);
            } else if (verbose == null) {
                d.setVerbose(false);
            } else {
                throw new SWORDErrorException(ErrorCodes.ERROR_BAD_REQUEST, "Bad verbose");
            }

            // Set the slug
            String slug = request.getHeader(HttpHeaders.SLUG);
            if (slug != null) {
                d.setSlug(slug);
            }

            // Set the content disposition
            d.setContentDisposition(request.getHeader(HttpHeaders.CONTENT_DISPOSITION));

            // Set the IP address
            d.setIPAddress(request.getRemoteAddr());

            // Set the deposit location
            d.setLocation(getUrl(request));

            // Set the content type
            d.setContentType(request.getContentType());

            // Set the content length
            String cl = request.getHeader(HttpHeaders.CONTENT_LENGTH);
            if ((cl != null) && (!cl.equals(""))) {
                d.setContentLength(Integer.parseInt(cl));
            }

            // Get the DepositResponse
            DepositResponse dr = myRepository.doDeposit(d);

            // Echo back the user agent
            if (request.getHeader(HttpHeaders.USER_AGENT.toString()) != null) {
                dr.getEntry().setUserAgent(request.getHeader(HttpHeaders.USER_AGENT.toString()));
            }

            // Echo back the packaging format
            if (request.getHeader(HttpHeaders.X_PACKAGING.toString()) != null) {
                dr.getEntry().setPackaging(request.getHeader(HttpHeaders.X_PACKAGING.toString()));
            }

            // Print out the Deposit Response
            response.setStatus(dr.getHttpResponse());
            if ((dr.getLocation() != null) && (!dr.getLocation().equals(""))) {
                response.setHeader("Location", dr.getLocation());
            }
            response.setContentType("application/atom+xml; charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(dr.marshall());
            out.flush();
        }
    } catch (SWORDAuthenticationException sae) {
        // Ask for credentials again
        if (authN.equals("Basic")) {
            String s = "Basic realm=\"SWORD\"";
            response.setHeader("WWW-Authenticate", s);
            response.setStatus(401);
        }
    } catch (SWORDErrorException see) {
        // Get the details and send the right SWORD error document
        log.error(see.toString());
        this.makeErrorDocument(see.getErrorURI(), see.getStatus(), see.getDescription(), request, response);
        return;
    } catch (SWORDException se) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.error(se.toString());
    } catch (NoSuchAlgorithmException nsae) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.error(nsae.toString());
    }

    finally {
        // Try deleting the temp file
        if (filename != null) {
            File f = new File(filename);
            if (f != null && !f.delete()) {
                log.error("Unable to delete file: " + filename);
            }
        }
    }
}

From source file:com.trigger_context.Main_Service.java

public String calculateMD5(File updateFile) {
    MessageDigest digest;//from   w ww.  j a v a2 s .  co m
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        noti("Exception while getting Digest", e.toString());
        return null;
    }

    InputStream is;
    try {
        is = new FileInputStream(updateFile);
    } catch (FileNotFoundException e) {
        noti("Exception while getting FileInputStream", e.toString());
        return null;
    }

    byte[] buffer = new byte[8192];
    int read;
    try {
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] md5sum = digest.digest();
        BigInteger bigInt = new BigInteger(1, md5sum);
        String output = bigInt.toString(16);
        // Fill to 32 chars
        output = String.format("%32s", output).replace(' ', '0');
        return output.toUpperCase();
    } catch (IOException e) {
        throw new RuntimeException("Unable to process file for MD5", e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            noti("Exception on closing MD5 input stream", e.toString());
        }
    }
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public KeyPair generateKeyPair() throws CryptoException {
    try {//from  w ww  . j av a2s . c om
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(this.keySize);

        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    } catch (NoSuchAlgorithmException e) {
        this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public KeyStore addKeyPair(KeyStore keyStore, String keyStorePassphrase, KeyPair keyPair, String keyPairName,
        String keyPairPassphrase, String keyPairSubjectDN) throws CryptoException {
    logger.debug("Adding key pair to existing key store");

    try {//from  ww  w  . j  a v a 2  s  .  c  om
        // Create the public key certificate for storage in the key store.
        X509Certificate cert = generateV3Certificate(keyPair, keyPairSubjectDN);
        X500PrivateCredential privateCredentials = new X500PrivateCredential(cert, keyPair.getPrivate(),
                keyPairName);

        Certificate[] certChain = new X509Certificate[1];
        certChain[0] = privateCredentials.getCertificate();

        // Load our generated key store up. They all have the same password, which we set.
        keyStore.load(null, keyStorePassphrase.toCharArray());

        /* Add certificate which contains the public key and set the private key as a key entry in the key store */
        keyStore.setCertificateEntry(privateCredentials.getAlias(), privateCredentials.getCertificate());
        keyStore.setKeyEntry(privateCredentials.getAlias(), keyPair.getPrivate(),
                keyPairPassphrase.toCharArray(), certChain);

        return keyStore;
    } catch (NoSuchAlgorithmException e) {
        this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (CertificateException e) {
        this.logger.error("CertificateException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (KeyStoreException e) {
        this.logger.error("KeyStoreException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (IOException e) {
        this.logger.error("IOException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }
}

From source file:com.newcell.calltext.wizards.impl.Basic.java

/**
 * Create an MD5 hash from a string/*from  ww w  .  j  av a2  s . com*/
 * @param str The original string
 * @return The MD5 hash of the string
 */
private String createMD5Hash(String str) {
    final String MD5 = "MD5";
    try {
        MessageDigest digest = java.security.MessageDigest.getInstance(MD5);
        digest.update(str.getBytes());
        byte messageDigest[] = digest.digest();
        // Create hex string
        StringBuilder hexString = new StringBuilder();
        for (byte aMessageDigest : messageDigest) {
            String h = Integer.toHexString(0xFF & aMessageDigest);
            while (h.length() < 2)
                h = "0" + h;
            hexString.append(h);
        }
        return hexString.toString();
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Error in createMD5Hash()");
        Log.e(TAG, e.toString());
    }
    return null;
}

From source file:uk.co.modularaudio.service.configuration.impl.ConfigurationServiceImpl.java

@Override
public void init() throws ComponentConfigurationException {

    if (configFilePath != null) {
        if (logWhereConfigComesFrom) {
            if (log.isInfoEnabled()) {
                log.info("ConfigurationServiceImpl beginning. Will use '" + configFilePath + "'"); // NOPMD by dan on 02/02/15 11:51
            }/*  w  w w  .ja v a  2s.co m*/
        }
        parseOneFilePath(configFilePath);

        if (additionalFilePaths != null && additionalFilePaths.length > 0) {
            for (final String additionalFilePath : additionalFilePaths) {
                parseOneFilePath(additionalFilePath);
            }
        }
    } else if (configResourcePath != null) {
        if (logWhereConfigComesFrom) {
            if (log.isInfoEnabled()) {
                log.info("ConfigurationServiceImpl beginning. Will use '" + configResourcePath + "'"); // NOPMD by dan on 02/02/15 11:51
            }
        }
        parseOneResourcePath(configResourcePath);

        if (additionalResourcePaths != null && additionalResourcePaths.length > 0) {
            for (final String additionalResourcePath : additionalResourcePaths) {
                parseOneResourcePath(additionalResourcePath);
            }
        }
    } else {
    }

    if (useEncryption && encryptionPepper != null) {
        try {
            // Initialise the secret key with our pepper (its not salt,
            // since salt should be added to taste i.e. random).
            final byte keyAsBytes[] = Base64.decodeBase64(encryptionPepper);

            keySpec = new SecretKeySpec(keyAsBytes, ALGO_TYPE);
            cipher = Cipher.getInstance(ALGO_TYPE);
        } catch (final NoSuchAlgorithmException nsae) {
            final String msg = "Unable to initialise config key decryption: " + nsae.toString();
            log.error(msg, nsae);
            throw new ComponentConfigurationException(msg, nsae);
        } catch (final NoSuchPaddingException nspe) {
            final String msg = "Unable to initialise config key decryption: " + nspe.toString();
            log.error(msg, nspe);
            throw new ComponentConfigurationException(msg, nspe);
        }
    } else if (useEncryption) {
        throw new ComponentConfigurationException("No encryption key specified yet component expected one");
    }
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}/*from  w  w w  .  j av  a 2  s .c  om*/
 */
@Override
public final byte[] sha256(byte[] data) throws McbpCryptoException {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        return md.digest(data);
    } catch (NoSuchAlgorithmException e) {
        throw new McbpCryptoException(e.toString());
    }
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}//w w  w .j ava 2s  .  co m
 */
@Override
public final byte[] sha1(byte[] data) throws McbpCryptoException {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(data);
        return md.digest();
    } catch (NoSuchAlgorithmException e) {
        throw new McbpCryptoException(e.toString());
    }
}

From source file:com.netspective.axiom.policy.AnsiDatabasePolicy.java

public Object handleGUIDPreDmlInsertExecute(ConnectionContext cc, GuidColumn column) throws SQLException {
    try {//from   w  w  w .j  a  v a 2  s.  c  om
        return GloballyUniqueIdentifier.getRandomGUID(false);
    } catch (NoSuchAlgorithmException e) {
        throw new SQLException(e.toString());
    } catch (UnknownHostException e) {
        throw new SQLException(e.toString());
    }
}