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:be.e_contract.dssp.client.DigitalSignatureServiceClient.java

private DocumentType addDocument(String mimetype, byte[] data, boolean useAttachments,
        InputDocuments inputDocuments) {
    DocumentType document = this.objectFactory.createDocumentType();
    String documentId = "document-" + UUID.randomUUID().toString();
    document.setID(documentId);//from  ww  w  .j  a va  2s.c om
    inputDocuments.getDocumentOrTransformedDataOrDocumentHash().add(document);
    if (useAttachments) {
        AttachmentReferenceType attachmentReference = this.objectFactory.createAttachmentReferenceType();
        document.setAttachmentReference(attachmentReference);
        attachmentReference.setMimeType(mimetype);
        DigestMethodType digestMethod = this.dsObjectFactory.createDigestMethodType();
        digestMethod.setAlgorithm(DigitalSignatureServiceConstants.SHA1_DIGEST_METHOD_TYPE);
        attachmentReference.setDigestMethod(digestMethod);
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-1 algo error: " + e.getMessage(), e);
        }
        byte[] digest = messageDigest.digest(data);
        attachmentReference.setDigestValue(digest);

        String contentId = addAttachment(mimetype, data);
        String attachmentUri = "cid:" + contentId;
        attachmentReference.setAttRefURI(attachmentUri);
    } else {
        if ("application/xml".equals(mimetype)) {
            document.setBase64XML(data);
        } else {
            Base64Data base64Data = this.objectFactory.createBase64Data();
            base64Data.setMimeType(mimetype);
            base64Data.setValue(data);
            document.setBase64Data(base64Data);
        }
    }
    return document;
}

From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java

/**
 * TLS provides encryption and optionally authentication for a session
 * by opening a channel with this profile.  The default action is to
 * set up for a channel with encryption only, no authentication.  To
 * mandate authentication, set the configuration via <code>init</code>.<p>
 * @see org.beepcore.beep.profile.Profile
 */// w w  w. ja v a2s .  c o m
public TLSProfileJSSE() {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");

        ctx.init(null, null, null);

        socketFactory = (SSLSocketFactory) ctx.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage());
    } catch (KeyManagementException e) {
        log.error(e.getMessage());
    }

    if (handshakeListeners == null) {
        handshakeListeners = Collections.synchronizedList(new LinkedList());
    }
}

From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java

private boolean disableSSL() {
    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }//  w ww.  ja  v  a 2 s  .  c o m
    };

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    // install all-trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        return true;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        return false;
    } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarSetSystemPasswordHtml.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///w w  w . ja  v a  2  s .  c  o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String S_ProcName = "doPost";

    ICFAstSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
        sess = request.getSession(true);
        schemaObj = new CFAstSchemaObj();
        sess.setAttribute("SchemaObj", schemaObj);
    } else {
        schemaObj = (ICFAstSchemaObj) sess.getAttribute("SchemaObj");
        if (schemaObj == null) {
            response.sendRedirect("CFAstSMWarLoginHtml");
            return;
        }
    }

    ICFAstSchema dbSchema = null;
    try {
        CFAstAuthorization auth = schemaObj.getAuthorization();
        if (auth != null) {
            response.sendRedirect("CFAstSMWarSecurityMainHtml");
        } else {
            dbSchema = CFAstSchemaPool.getSchemaPool().getInstance();
            schemaObj.setBackingStore(dbSchema);
            schemaObj.beginTransaction();
            ICFAstSecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
            String passwordHash = systemUser.getRequiredPasswordHash();
            if ((passwordHash != null) && (passwordHash.length() > 0) && (!passwordHash.equals("bootstrap"))) {
                response.sendRedirect("CFAstSMWarLoginHtml");
            } else {
                ICFAstClusterObj resolvedCluster;
                String resolvedClusterDomainName;
                String resolvedClusterDescription;
                ICFAstSysClusterObj sysCluster = schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1,
                        false);
                if (sysCluster == null) {
                    resolvedCluster = null;
                    resolvedClusterDomainName = (String) request.getParameter("ClusterDomainName");
                    resolvedClusterDescription = (String) request.getParameter("ClusterDescription");
                } else {
                    resolvedCluster = sysCluster.getRequiredContainerCluster();
                    if (resolvedCluster == null) {
                        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(),
                                S_ProcName, "resolvedCluster");
                    }
                    resolvedClusterDomainName = resolvedCluster.getRequiredFullDomainName();
                    resolvedClusterDescription = resolvedCluster.getRequiredDescription();
                }

                String password = (String) request.getParameter("Password");
                if (password == null) {
                    password = "";
                }
                String confirmPassword = (String) request.getParameter("ConfirmPassword");
                if (confirmPassword == null) {
                    confirmPassword = "";
                }
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                if (password.length() <= 0) {
                    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
                    out.println("<HTML>");
                    out.println("<BODY>");
                    out.println("<form method=\"post\" formaction=\"CFAstSMWarSetSystemPasswordHtml\">");
                    out.println("<H1 style=\"text-align:center\">"
                            + ((resolvedClusterDescription == null) ? "" : resolvedClusterDescription)
                            + " Security Manager</H1>");
                    out.println(
                            "<H2 style=\"text-align:center\">Please initialize the \"system\" password and cluster details.</H2>");
                    out.println("<p>");
                    out.println("<center>");
                    out.println("<table style=\"width:60%\">");
                    out.println(
                            "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
                    out.println(
                            "<tr><th style=\"text-align:left\">Confirm Password:</th><td><input type=\"password\" name=\"ConfirmPassword\"/></td></tr>");
                    out.println(
                            "<tr><th style=\"text-align:left\">Cluster Domain Name:</th><td><input name=\"ClusterDomainName\"/></td></tr>");
                    out.println(
                            "<tr><th style=\"text-align:left\">Cluster Description:</th><td><input name=\"ClusterDescription\"/></td></tr>");
                    out.println(
                            "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
                    out.println("</table>");
                    out.println("</center>");
                    out.println("</form>");
                    out.println("</BODY>");
                    out.println("</HTML>");
                } else if (!password.equals(confirmPassword)) {
                    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
                    out.println("<HTML>");
                    out.println("<BODY>");
                    out.println("<form method=\"post\" formaction=\"CFAstSMWarSetSystemPasswordHtml\">");
                    out.println("<H1 style=\"text-align:center\">"
                            + ((resolvedClusterDescription == null) ? "" : resolvedClusterDescription)
                            + " Security Manager</H1>");
                    out.println(
                            "<H2 style=\"text-align:center\">Please initialize the \"system\" password and cluster details.</H2>");
                    out.println("<p>");
                    out.println("<center>");
                    out.println("<table style=\"width:60%\">");
                    out.println(
                            "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
                    out.println(
                            "<tr><th style=\"text-align:left\">Confirm Password:</th><td><input type=\"password\" name=\"ConfirmPassword\"/></td></tr>");
                    out.println(
                            "<tr><th style=\"text-align:left\">Cluster Domain Name:</th><td><input name=\"ClusterDomainName\"/></td></tr>");
                    out.println(
                            "<tr><th style=\"text-align:left\">Cluster Description:</th><td><input name=\"ClusterDescription\"/></td></tr>");
                    out.println(
                            "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
                    out.println("</table>");
                    out.println("</center>");
                    out.println("</form>");
                    out.println("</BODY>");
                    out.println("</HTML>");
                } else {
                    MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
                    msgDigest.update(password.getBytes("UTF-8"));
                    byte[] hash = msgDigest.digest();
                    byte[] encodedHash = Base64.encodeBase64(hash);
                    msgDigest.update(encodedHash);
                    hash = msgDigest.digest();
                    encodedHash = Base64.encodeBase64(hash);
                    String hashedAndEncodedPassword = new String(encodedHash);

                    // Need to temporarily "log in" as system.system to set the password
                    ICFAstClusterObj systemCluster = schemaObj.getClusterTableObj()
                            .readClusterByUDomainNameIdx("system");
                    ICFAstTenantObj systemTenant = schemaObj.getTenantTableObj()
                            .readTenantByUNameIdx(systemCluster.getRequiredId(), "system");
                    ICFAstSecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
                    ICFAstSecSessionEditObj editSystemSession = (ICFAstSecSessionEditObj) systemSession
                            .beginEdit();
                    editSystemSession.setRequiredContainerSecUser(systemUser);
                    editSystemSession.setRequiredStart(Calendar.getInstance());
                    systemSession = editSystemSession.create();
                    editSystemSession.endEdit();

                    auth = new CFAstAuthorization();
                    auth.setSecCluster(systemCluster);
                    auth.setSecTenant(systemTenant);
                    auth.setSecSession(systemSession);
                    schemaObj.setAuthorization(auth);

                    if (resolvedCluster == null) {
                        ICFAstClusterObj cluster = schemaObj.getClusterTableObj().newInstance();
                        ICFAstClusterEditObj editCluster = cluster.beginEdit();
                        editCluster.setRequiredFullDomainName(resolvedClusterDomainName);
                        editCluster.setRequiredDescription(resolvedClusterDescription);
                        cluster = editCluster.create();
                        editCluster.endEdit();

                        resolvedCluster = cluster;

                        ICFAstTenantObj tenant = schemaObj.getTenantTableObj().newInstance();
                        ICFAstTenantEditObj editTenant = tenant.beginEdit();
                        editTenant.setRequiredContainerCluster(cluster);
                        editTenant.setRequiredTenantName("system");
                        tenant = editTenant.create();
                        editTenant.endEdit();

                        sysCluster = schemaObj.getSysClusterTableObj().newInstance();
                        ICFAstSysClusterEditObj editSysCluster = sysCluster.beginEdit();
                        editSysCluster.setRequiredContainerCluster(resolvedCluster);
                        editSysCluster.setRequiredSingletonId(1);
                        sysCluster = editSysCluster.create();
                        editSysCluster.endEdit();
                    }

                    ICFAstSecUserEditObj editSystemUser = (ICFAstSecUserEditObj) systemUser.beginEdit();
                    editSystemUser.setRequiredPasswordHash(hashedAndEncodedPassword);
                    editSystemUser.update();
                    editSystemUser.endEdit();

                    editSystemSession = (ICFAstSecSessionEditObj) systemSession.beginEdit();
                    editSystemSession.setOptionalFinish(Calendar.getInstance());
                    editSystemSession.update();
                    editSystemSession.endEdit();

                    schemaObj.commit();

                    schemaObj.setAuthorization(null);

                    out.println("<H1 style=\"text-align:center\">"
                            + ((resolvedClusterDescription == null) ? "" : resolvedClusterDescription)
                            + " Security Manager</H1>");
                    out.println("<H2 style=\"text-align:center\">Password set.</H2>");
                    out.println("<p style=\"text-align:center\">");
                    out.println(
                            "You may now <A HRef=\"CFAstSMWarLoginHtml\">log in to the security manager.</A>");
                }
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException -- " + e.getMessage(), e);
    } catch (RuntimeException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
        if (dbSchema != null) {
            try {
                if (schemaObj.isTransactionOpen()) {
                    schemaObj.rollback();
                }
            } catch (RuntimeException e) {
            }
            schemaObj.setBackingStore(null);
            CFAstSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

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

/**
 *
 * @param dn may not be null/* ww  w.ja  v a2 s . c  o  m*/
 * @param rights may not be null
 * @param bindings may not be null, can be zerolen array
 * @param elapsedMins may not be null or negative
 * @param reservedMins may not be null or negative
 * @param numWorkspaces number of OTHER, current workspaces
 * @param chargeRatio ratio to compute the real minutes charge, typically <= 1.0 and > 0
 * @return Decision Integer
 * @throws AuthorizationException processing problem
 * @throws ResourceRequestDeniedException error w/ explanation to client
 */
public Integer decide(String dn, GroupRights rights, VirtualMachine[] bindings, Long elapsedMins,
        Long reservedMins, int numWorkspaces, double chargeRatio)

        throws AuthorizationException, ResourceRequestDeniedException {

    if (!HashUtil.isInitialized()) {
        throw new AuthorizationException(
                "Cannot give an authorization " + "decision without a properly initialized hashing system");
    }

    if (dn == null) {
        throw new IllegalArgumentException("dn is null");
    }

    if (rights == null) {
        throw new IllegalArgumentException("rights is null");
    }

    if (bindings == null) {
        throw new IllegalArgumentException("bindings is null");
    }

    if (elapsedMins == null) {
        throw new IllegalArgumentException("elapsedMins is null");
    } else if (elapsedMins.longValue() < 0) {
        throw new IllegalArgumentException("elapsedMins is negative");
    }

    if (reservedMins == null) {
        throw new IllegalArgumentException("reservedMins is null");
    } else if (reservedMins.longValue() < 0) {
        throw new IllegalArgumentException("reservedMins is negative");
    }

    if (chargeRatio <= 0) {
        throw new IllegalArgumentException("expecting charge ratio to be positive");
    }

    final StringBuffer buf = new StringBuffer("\n\nConsidering caller: '");
    buf.append(dn).append("'.\nCurrent elapsed minutes: ").append(elapsedMins)
            .append(".\nCurrent reserved minutes: ").append(reservedMins)
            .append(".\nNumber of VMs in request: ").append(bindings.length)
            .append(".\nCharge ratio for request: ").append(chargeRatio)
            .append(".\nNumber of VMs caller is already currently running: ").append(numWorkspaces)
            .append(".\nRights:\n").append(rights).append("\n\n");

    final int maxCurrentPolicy = (int) rights.getMaxWorkspaceNumber();
    if (maxCurrentPolicy > 0) {

        if (numWorkspaces + bindings.length > maxCurrentPolicy) {

            final StringBuffer newbuf = new StringBuffer("\nDenied: Request for ");
            newbuf.append(bindings.length).append(" workspaces");

            if (numWorkspaces != 0) {
                newbuf.append(", together with number of currently " + "running workspaces (")
                        .append(numWorkspaces).append("),");
            }

            newbuf.append(" exceeds the maximum, which is ").append(maxCurrentPolicy)
                    .append(" concurrently running workspaces.");

            final String msg = newbuf.toString();
            buf.append(msg);
            logger.warn(buf.toString());
            throw new ResourceRequestDeniedException(msg);
        }
    }

    long requestDur = 0;
    for (int i = 0; i < bindings.length; i++) {

        final VirtualMachineDeployment dep = bindings[i].getDeployment();
        if (dep == null) {
            final String msg = "ERROR: No deployment information in " + "binding, can't make decision.";
            buf.append(msg);
            logger.error(buf.toString());
            throw new AuthorizationException(msg);
        }

        final long seconds = dep.getMinDuration();
        requestDur += seconds / 60;
    }

    final Double doubleRequestDur = requestDur * chargeRatio;
    requestDur = doubleRequestDur.longValue();

    if (bindings.length > 1) {
        buf.append("Duration total of all requests in group: ");
    } else {
        buf.append("Duration request: ");
    }

    buf.append(requestDur).append("\n");

    // zero or below means no check should be made
    if (rights.getMaxCPUs() > 0) {
        final long maxCPUs = rights.getMaxCPUs();
        for (int i = 0; i < bindings.length; i++) {

            final VirtualMachineDeployment dep = bindings[i].getDeployment();
            if (dep == null) {
                final String msg = "ERROR: No deployment information in " + "binding, can't make decision.";
                buf.append(msg);
                logger.error(buf.toString());
                throw new AuthorizationException(msg);
            }
            final long currentCPUs = dep.getIndividualCPUCount();
            if (currentCPUs > maxCPUs) {

                buf.append("\nDenied: Requested CPU count (").append(currentCPUs)
                        .append(") + is greater or equal to maximum CPU count (").append(maxCPUs)
                        .append(").\n");

                logger.warn(buf.toString());

                throw new ResourceRequestDeniedException("You requested too many CPUs (" + currentCPUs
                        + "), the " + "maximum is " + maxCPUs + " CPUs.");
            }
        }
    }

    // zero or below means no check should be made
    if (rights.getMaxReservedMinutes() > 0) {
        final long max = rights.getMaxReservedMinutes();
        final long current = reservedMins.longValue();
        if (requestDur + current > max) {

            buf.append("\nDenied: Request duration (").append(requestDur).append(") + current reserved tally (")
                    .append(current).append(") + is greater or equal to maximum reserved (").append(max)
                    .append(").\n");

            logger.warn(buf.toString());

            throw new ResourceRequestDeniedException("Your request is for too much time (" + requestDur
                    + "), the " + "maximum reserved at once is " + max + " minutes.  You currently have "
                    + current + " other reserved minutes.");
        }
    }

    // zero or below means no check should be made
    if (rights.getMaxElapsedReservedMinutes() > 0) {
        final long max = rights.getMaxElapsedReservedMinutes();
        final long currentElapsed = elapsedMins.longValue();
        final long currentReserved = reservedMins.longValue();
        final long tally = currentElapsed + currentReserved;
        if (requestDur + tally > max) {

            buf.append("\nDenied: Request duration (").append(requestDur)
                    .append(") + current reserved+elapsed tally (").append(tally)
                    .append(") + is greater or equal to maximum reserved+elapsed (").append(max).append(").\n");

            logger.warn(buf.toString());

            throw new ResourceRequestDeniedException("Your request is for too much time (" + requestDur
                    + "), this would exceed the " + "maximum you can have both used in the "
                    + "past and have reserved currently. " + "This maximum is " + max
                    + " minutes.  You currently have " + currentElapsed + " elapsed minutes " + "and "
                    + currentReserved + " reserved minutes and the request for " + requestDur
                    + " minutes would exceed this.");
        }
    }

    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();
            buf.append(msg);
            logger.error(buf.toString());
            throw new AuthorizationException(msg);
        }
    } else {
        dnhash = null;
    }

    for (int i = 0; i < bindings.length; i++) {

        final VirtualMachinePartition[] parts = bindings[i].getPartitions();

        if (parts == null) {
            final String msg = "ERROR: No partition information in " + "binding, can't make decision.";
            buf.append(msg);
            logger.error(buf.toString());
            throw new AuthorizationException(msg);
        }

        checkImages(parts, rights, buf, dn, dnhash);
    }

    buf.append("\n");
    logger.info(buf.toString());
    return Decision.PERMIT;
}

From source file:rapture.kernel.AdminApiImpl.java

private String generateSecureToken() {
    try {//from   w  w  w  .  ja  va 2  s .  c om
        // get secure random
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte bytes[] = new byte[128];
        random.nextBytes(bytes);
        // get its digest
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] result = sha.digest(bytes);
        // encode to hex
        return (new Hex()).encodeHexString(result);
    } catch (NoSuchAlgorithmException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, e.getMessage());
    }
}

From source file:net.peterkuterna.android.apps.devoxxfrsched.util.ImageDownloader.java

Bitmap downloadBitmap(String url) {
    final int IO_BUFFER_SIZE = 4 * 1024;

    File cacheFile = null;/*from   ww  w.  j  a  v a  2s  . c  o  m*/
    try {
        MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
        mDigest.update(url.getBytes());
        final String cacheKey = bytesToHexString(mDigest.digest());
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                    + File.separator + "data" + File.separator + mContext.getPackageName() + File.separator
                    + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp");
        }
    } catch (NoSuchAlgorithmException e) {
        // Oh well, SHA-1 not available (weird), don't cache bitmaps.
    }

    HttpGet getRequest = null;
    try {
        getRequest = new HttpGet(url);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "Error while constructing get request: " + e.getMessage());
        return null;
    }

    try {
        HttpResponse response = mClient.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            final byte[] respBytes = EntityUtils.toByteArray(entity);

            if (cacheFile != null) {
                try {
                    cacheFile.getParentFile().mkdirs();
                    cacheFile.createNewFile();
                    FileOutputStream fos = new FileOutputStream(cacheFile);
                    fos.write(respBytes);
                    fos.close();
                } catch (FileNotFoundException e) {
                    Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                } catch (IOException e) {
                    Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e);
                }
            }

            return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length);
        }
    } catch (IOException e) {
        getRequest.abort();
        Log.w(TAG, "I/O error while retrieving bitmap from " + url, e);
    } catch (IllegalStateException e) {
        getRequest.abort();
        Log.w(TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
        getRequest.abort();
        Log.w(TAG, "Error while retrieving bitmap from " + url, e);
    }
    return null;
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Get the Certificate Authority private key
 * /* ww  w. ja v  a 2 s. c  o m*/
 * @return
 */
private PrivateKey getCaKey(KeyStore trustedKs) {
    PrivateKey caKey = null;
    String keyAlias = config.getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_KEY_ALIAS);
    String keyPassword = config.getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_KEY_PASSWORD);

    try {
        caKey = (PrivateKey) trustedKs.getKey(keyAlias, keyPassword.toCharArray());
    } catch (KeyStoreException kse) {
        throw new AlfrescoRuntimeException(kse.getMessage());
    } catch (UnrecoverableKeyException uke) {
        throw new AlfrescoRuntimeException(uke.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        throw new AlfrescoRuntimeException(nsae.getMessage());
    }

    return caKey;
}

From source file:com.flexvdi.androidlauncher.LoginActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    mContext = this;

    try {/* w ww  .ja va2 s .co m*/
        GStreamer.init(mContext);
    } catch (Exception e) {
        Log.e(TAG, "Can't initialize GStreamer" + e.getMessage());
        finish();
    }

    settings = getSharedPreferences("flexVDI", MODE_PRIVATE);
    settingsEditor = settings.edit();
    /* Uncomment this for clearing preferences (useful when debugging) */
    //settingsEditor.clear();
    //settingsEditor.apply();
    //settingsEditor.commit();

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.activity_login);

    textUser = (EditText) findViewById(R.id.textUser);
    textServer = (EditText) findViewById(R.id.textServer);
    textPassword = (EditText) findViewById(R.id.textPassword);

    goButton = (Button) findViewById(R.id.buttonGO);
    goButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ConnectivityManager cm = (ConnectivityManager) mContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

            if (!isConnected) {
                Toast.makeText(view.getContext(), getResources().getString(R.string.no_network),
                        Toast.LENGTH_LONG).show();
                return;
            }

            if (checkBoxGenericSpice.isChecked()) {
                String userField = textUser.getText().toString();
                if (userField.length() == 0 || !userField.contains(":")) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.invalid_spice_server),
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String spiceAddress = userField.substring(0, userField.indexOf(":"));
                String spicePort = userField.substring(userField.indexOf(":") + 1);

                if (spiceAddress.length() == 0 || spicePort.length() == 0) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.invalid_spice_server),
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String spicePassword = textPassword.getText().toString();

                settingsEditor.putBoolean("enableSound", checkBoxEnableSound.isChecked());
                settingsEditor.putBoolean("staticResolution", checkBoxStaticResolution.isChecked());
                settingsEditor.putBoolean("genericSpice", checkBoxGenericSpice.isChecked());
                settingsEditor.putString("flexServerName", textServer.getText().toString());

                settingsEditor.putString("spice_address", spiceAddress);
                settingsEditor.putString("spice_port", spicePort);
                settingsEditor.putString("spice_password", spicePassword);
                settingsEditor.putBoolean("use_ws", false);

                settingsEditor.apply();
                settingsEditor.commit();

                startMainActivity();
            } else {
                if (textServer.getText().length() == 0) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.empty_flexvdi_server),
                            Toast.LENGTH_LONG).show();
                } else {
                    if (textUser.getText().length() != 0 && textPassword.getText().length() != 0) {
                        new RequestTask().execute("authmode", textServer.getText().toString(),
                                textUser.getText().toString(), textPassword.getText().toString(), "");
                    } else
                        Toast.makeText(view.getContext(), getResources().getString(R.string.empty_credentials),
                                Toast.LENGTH_LONG).show();
                }
            }
        }
    });

    // The advanced settings button.
    checkBoxAdvancedOptions = (CheckBox) findViewById(R.id.checkBoxAdvancedSettings);
    layoutAdvancedOptions = (LinearLayout) findViewById(R.id.layoutAdvancedOptions2);
    checkBoxAdvancedOptions.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            if (checked)
                layoutAdvancedOptions.setVisibility(View.VISIBLE);
            else
                layoutAdvancedOptions.setVisibility(View.GONE);
        }
    });

    textServer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View field, boolean hasFocus) {
            if (!hasFocus && checkBoxGenericSpice.isChecked()) {
                if (textUser.getText().toString().length() == 0) {
                    textUser.setText(textServer.getText());
                }
            }
        }
    });

    checkBoxEnableSound = (CheckBox) findViewById(R.id.checkBoxEnableSound);
    if (settings.getBoolean("enableSound", true)) {
        checkBoxEnableSound.setChecked(true);
    } else {
        checkBoxEnableSound.setChecked(false);
    }

    if (!settings.contains("staticResolution")) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        if ((size.x + size.y) > 2340) {
            /* 2340 = 1440+900 */
            settingsEditor.putBoolean("staticResolution", true);
        } else {
            settingsEditor.putBoolean("staticResolution", false);
        }
        settingsEditor.apply();
        settingsEditor.commit();
    }

    checkBoxStaticResolution = (CheckBox) findViewById(R.id.checkBoxStaticResolution);
    if (settings.getBoolean("staticResolution", true)) {
        checkBoxStaticResolution.setChecked(true);
    } else {
        checkBoxStaticResolution.setChecked(false);
    }

    checkBoxGenericSpice = (CheckBox) findViewById(R.id.checkBoxGenericSpice);
    if (settings.getBoolean("genericSpice", false)) {
        checkBoxGenericSpice.setChecked(true);
        checkBoxAdvancedOptions.setChecked(true);
        layoutAdvancedOptions.setVisibility(View.VISIBLE);

        if (settings.contains("flexServerName")) {
            textServer.setText(settings.getString("flexServerName", ""));
            textUser.setText(settings.getString("flexServerName", ""));
            textServer.setHint(getResources().getString(R.string.spice_server));
            textUser.setHint(getResources().getString(R.string.spice_server_port));
        }
    } else {
        checkBoxGenericSpice.setChecked(false);
        if (settings.contains("flexServerName")) {
            textServer.setText(settings.getString("flexServerName", ""));
            layoutAdvancedOptions.setVisibility(View.GONE);
        } else {
            textServer.setText("manager.flexvdi.com");
            checkBoxAdvancedOptions.setChecked(true);
        }
    }

    checkBoxGenericSpice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            if (checked) {
                textServer.setHint(getResources().getString(R.string.spice_server));
                textUser.setHint(getResources().getString(R.string.spice_server_port));
                String server = textServer.getText().toString();
                if (server.length() != 0) {
                    if (server.contains(":")) {
                        textUser.setText(server);
                    } else {
                        textUser.setText(server + ":5900");
                        textServer.setText(server + ":5900");
                    }
                }
            } else {
                textServer.setHint(getResources().getString(R.string.flexvdi_server));
                String server = textServer.getText().toString();
                if (server.length() != 0 && server.contains(":")) {
                    textServer.setText(server.substring(0, server.indexOf(":")));
                }
                textUser.setText("");
                textUser.setHint(getResources().getString(R.string.user));
            }
        }
    });

    deviceID = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);

    textViewDeviceID = (TextView) findViewById(R.id.textViewDeviceID);
    textViewDeviceID.setText("ID: " + deviceID + " (" + BuildConfig.VERSION_NAME + ")");

    try {
        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new NullX509TrustManager() }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    } catch (NoSuchAlgorithmException nsae) {
        Log.e(TAG, nsae.getMessage());
    } catch (KeyManagementException kme) {
        Log.e(TAG, kme.getMessage());
    }
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Get the trusted keystore as configured in the extension properties.
 * //  ww w.jav  a  2  s. com
 * @return
 */
private KeyStore getTrustedKeyStore() {
    try {
        String keystorePassword = config
                .getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_KEYSTORE_PASSWORD);
        String keystorePath = config
                .getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_KEYSTORE_PATH);
        KeyStore keystore = KeyStore.getInstance("pkcs12");
        FileInputStream keyStream = new FileInputStream(keystorePath);
        keystore.load(keyStream, keystorePassword.toCharArray());

        // return the keystore
        return keystore;
    } catch (KeyStoreException kse) {
        throw new AlfrescoRuntimeException(kse.getMessage());
    } catch (java.security.cert.CertificateException ce) {
        throw new AlfrescoRuntimeException(ce.getMessage());
    } catch (NoSuchAlgorithmException nsaex) {
        throw new AlfrescoRuntimeException(nsaex.getMessage());
    } catch (IOException ioex) {
        throw new AlfrescoRuntimeException(ioex.getMessage());
    }
}