List of usage examples for java.security GeneralSecurityException getMessage
public String getMessage()
From source file:org.apache.manifoldcf.crawler.connectors.googledrive.GoogleDriveRepositoryConnector.java
private static void handleGeneralSecurityException(GeneralSecurityException e) throws ManifoldCFException, ServiceInterruption { // Permanent problem: can't initialize transport layer throw new ManifoldCFException("GoogleDrive exception: " + e.getMessage(), e); }
From source file:edu.internet2.middleware.changelogconsumer.googleapps.GoogleAppsFullSync.java
/** * Runs a fullSync.// w w w .j a v a2s. co m * @param dryRun indicates that this is dryRun */ public void process(boolean dryRun) { synchronized (fullSyncIsRunningLock) { fullSyncIsRunning.put(consumerName, Boolean.toString(true)); } connector = new GoogleGrouperConnector(); //Start with a clean cache GoogleCacheManager.googleGroups().clear(); GoogleCacheManager.googleGroups().clear(); properties = new GoogleAppsSyncProperties(consumerName); Pattern googleGroupFilter = Pattern.compile(properties.getGoogleGroupFilter()); try { connector.initialize(consumerName, properties); if (properties.getprefillGoogleCachesForFullSync()) { connector.populateGoogleCache(); } } catch (GeneralSecurityException e) { LOG.error("Google Apps Consume '{}' Full Sync - This consumer failed to initialize: {}", consumerName, e.getMessage()); } catch (IOException e) { LOG.error("Google Apps Consume '{}' Full Sync - This consumer failed to initialize: {}", consumerName, e.getMessage()); } GrouperSession grouperSession = null; try { grouperSession = GrouperSession.startRootSession(); connector.getGoogleSyncAttribute(); connector.cacheSyncedGroupsAndStems(true); // time context processing final StopWatch stopWatch = new StopWatch(); stopWatch.start(); //Populate a normalized list (google naming) of Grouper groups ArrayList<ComparableGroupItem> grouperGroups = new ArrayList<ComparableGroupItem>(); for (String groupKey : connector.getSyncedGroupsAndStems().keySet()) { if (connector.getSyncedGroupsAndStems().get(groupKey).equalsIgnoreCase("yes")) { edu.internet2.middleware.grouper.Group group = connector.fetchGrouperGroup(groupKey); if (group != null) { grouperGroups.add(new ComparableGroupItem( connector.getAddressFormatter().qualifyGroupAddress(group.getName()), group)); } } } //Populate a comparable list of Google groups ArrayList<ComparableGroupItem> googleGroups = new ArrayList<ComparableGroupItem>(); for (String groupName : GoogleCacheManager.googleGroups().getKeySet()) { if (googleGroupFilter.matcher(groupName.replace("@" + properties.getGoogleDomain(), "")).find()) { googleGroups.add(new ComparableGroupItem(groupName)); LOG.debug("Google Apps Consumer '{}' Full Sync - {} group matches group filter: included", consumerName, groupName); } else { LOG.debug("Google Apps Consumer '{}' Full Sync - {} group does not match group filter: ignored", consumerName, groupName); } } //Get our sets Collection<ComparableGroupItem> extraGroups = CollectionUtils.subtract(googleGroups, grouperGroups); processExtraGroups(dryRun, extraGroups); Collection<ComparableGroupItem> missingGroups = CollectionUtils.subtract(grouperGroups, googleGroups); processMissingGroups(dryRun, missingGroups); Collection<ComparableGroupItem> matchedGroups = CollectionUtils.intersection(grouperGroups, googleGroups); processMatchedGroups(dryRun, matchedGroups); // stop the timer and log stopWatch.stop(); LOG.debug("Google Apps Consumer '{}' Full Sync - Processed, Elapsed time {}", new Object[] { consumerName, stopWatch }); } finally { GrouperSession.stopQuietly(grouperSession); synchronized (fullSyncIsRunningLock) { fullSyncIsRunning.put(consumerName, Boolean.toString(true)); } } }
From source file:ch.swing.gridcertlib.SLCSRequestor.java
private void parseSLCSCertificateResponse(Source source) throws SLCSException, IOException { Element certificateElement = source.findNextElement(0, "Certificate"); if (certificateElement == null || certificateElement.isEmpty()) { final String message = "Certificate element not found in SLCS response"; LOG.error(message);//w ww . j a va2 s.c om throw new SLCSException(message); } String pemCertificate = certificateElement.getContent().toString(); LOG.info("Certificate element found"); LOG.debug("Certificate=" + pemCertificate); StringReader reader = new StringReader(pemCertificate); try { certificate_ = Certificate.readPEM(reader); } catch (GeneralSecurityException e) { final String message = "Failed to reconstitute the certificate: " + e.getMessage(); LOG.error(message, e); throw new SLCSException(message, e); } }
From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java
/** * Check if upload file has already been uploaded. Do nothing, if file is * missing./*from w ww. j ava 2 s . com*/ * * @throws UploadFailedException * If something went wrong sending/receiving the request to/from * the lookaside cache. * @throws FileAvailableInLookasideCacheException * If the upload candidate file is already present in the * lookaside cache. */ private void checkSourceAvailable() throws FileAvailableInLookasideCacheException, UploadFailedException { HttpClient client = getClient(); try { String uploadURI = null; uploadURI = this.projectRoot.getLookAsideCache().getUploadUrl().toString(); assert uploadURI != null; if (fedoraSslEnabled) { // user requested Fedora SSL enabled client try { client = fedoraSslEnable(client); } catch (GeneralSecurityException e) { throw new UploadFailedException(e.getMessage(), e); } } else if (trustAllSSLEnabled) { // use accept all SSL enabled client try { client = trustAllSslEnable(client); } catch (GeneralSecurityException e) { throw new UploadFailedException(e.getMessage(), e); } } HttpPost post = new HttpPost(uploadURI); // provide hint which URL is going to be used FedoraPackagerLogger logger = FedoraPackagerLogger.getInstance(); logger.logDebug(NLS.bind(FedoraPackagerText.UploadSourceCommand_usingUploadURLMsg, uploadURI)); // Construct the multipart POST request body. MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(FILENAME_PARAM_NAME, new StringBody(fileToUpload.getName())); reqEntity.addPart(PACKAGENAME_PARAM_NAME, new StringBody(projectRoot.getSpecfileModel().getName())); reqEntity.addPart(CHECKSUM_PARAM_NAME, new StringBody(SourcesFile.calculateChecksum(fileToUpload))); post.setEntity(reqEntity); HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); int returnCode = response.getStatusLine().getStatusCode(); if (returnCode != HttpURLConnection.HTTP_OK) { throw new UploadFailedException(response.getStatusLine().getReasonPhrase(), response); } else { String resString = ""; //$NON-NLS-1$ if (resEntity != null) { try { resString = parseResponse(resEntity); } catch (IOException e) { // ignore } EntityUtils.consume(resEntity); // clean up resources } // If this file has already been uploaded bail out if (resString.toLowerCase().equals(RESOURCE_AVAILABLE)) { throw new FileAvailableInLookasideCacheException(fileToUpload.getName()); } else if (resString.toLowerCase().equals(RESOURCE_MISSING)) { // check passed return; } else { // something is fishy throw new UploadFailedException(FedoraPackagerText.somethingUnexpectedHappenedError); } } } catch (IOException e) { throw new UploadFailedException(e.getMessage(), e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); } }
From source file:custom.application.login.java
public String oAuth2callback() throws ApplicationException { HttpServletRequest request = (HttpServletRequest) this.context.getAttribute("HTTP_REQUEST"); HttpServletResponse response = (HttpServletResponse) this.context.getAttribute("HTTP_RESPONSE"); Reforward reforward = new Reforward(request, response); TokenResponse oauth2_response;/* ww w. ja va 2 s. co m*/ try { if (this.getVariable("google_client_secrets") == null) { clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(login.class.getResourceAsStream("/clients_secrets.json"))); if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) { System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/ "); } this.setVariable(new ObjectVariable("google_client_secrets", clientSecrets)); } else clientSecrets = (GoogleClientSecrets) this.getVariable("google_client_secrets").getValue(); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES).build(); oauth2_response = flow.newTokenRequest(request.getParameter("code")) .setRedirectUri(this.getLink("oauth2callback")).execute(); System.out.println("Ok:" + oauth2_response.toPrettyString()); } catch (IOException e1) { // TODO Auto-generated catch block throw new ApplicationException(e1.getMessage(), e1); } catch (GeneralSecurityException e) { // TODO Auto-generated catch block throw new ApplicationException(e.getMessage(), e); } try { HttpClient httpClient = new DefaultHttpClient(); String url = "https://www.google.com/m8/feeds/contacts/default/full"; url = "https://www.googleapis.com/oauth2/v1/userinfo"; HttpGet httpget = new HttpGet(url + "?access_token=" + oauth2_response.getAccessToken()); httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8"); HttpResponse http_response = httpClient.execute(httpget); HeaderIterator iterator = http_response.headerIterator(); while (iterator.hasNext()) { Header next = iterator.nextHeader(); System.out.println(next.getName() + ":" + next.getValue()); } InputStream instream = http_response.getEntity().getContent(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len; while ((len = instream.read(bytes)) != -1) { out.write(bytes, 0, len); } instream.close(); out.close(); Struct struct = new Builder(); struct.parse(new String(out.toByteArray(), "utf-8")); this.usr = new User(); this.usr.setEmail(struct.toData().getFieldInfo("email").stringValue()); if (this.usr.findOneByKey("email", this.usr.getEmail()).size() == 0) { usr.setPassword(""); usr.setUsername(usr.getEmail()); usr.setLastloginIP(request.getRemoteAddr()); usr.setLastloginTime(new Date()); usr.setRegistrationTime(new Date()); usr.append(); } new passport(request, response, "waslogined").setLoginAsUser(this.usr.getId()); reforward.setDefault(URLDecoder.decode(this.getVariable("from").getValue().toString(), "utf8")); reforward.forward(); return new String(out.toByteArray(), "utf-8"); } catch (ClientProtocolException e) { throw new ApplicationException(e.getMessage(), e); } catch (IOException e) { throw new ApplicationException(e.getMessage(), e); } catch (ParseException e) { throw new ApplicationException(e.getMessage(), e); } }
From source file:edu.duke.cabig.c3pr.web.security.SecureWebServiceHandler.java
/** * @param samlAssertion/* w w w. jav a 2s. co m*/ * @throws SAMLException * @throws WSSecurityException */ private void verifyAssertion(SAMLAssertion samlAssertion) throws SAMLException, WSSecurityException { samlAssertion.verify(); Iterator<X509Certificate> it = samlAssertion.getX509Certificates(); if (!it.hasNext()) { throw new WSSecurityException("No X.509 certificates found in the SAML token."); } while (it.hasNext()) { X509Certificate cert = (X509Certificate) it.next(); Crypto crypto = getCrypto(); try { verifyCertificate(cert, crypto); } catch (GeneralSecurityException e) { log.error(ExceptionUtils.getFullStackTrace(e)); throw new WSSecurityException( "A certificate found in the SAML token did not pass a validity check: " + e.getMessage() + "\r\n" + cert, e); } } }
From source file:com.examples.abelanav2.datastore.DbClient.java
/** * Constructor.//from ww w . j a v a 2 s. c o m */ public DbClient() { try { // Setup the connection to Google Cloud Datastore and infer // credentials from the environment. datastore = DatastoreFactory.get() .create(DatastoreHelper.getOptionsFromEnv().dataset(BackendConstants.PROJECT_ID).build()); } catch (GeneralSecurityException e) { LOGGER.severe("Security error connecting to the datastore: " + e.getMessage()); } catch (IOException e) { LOGGER.severe("I/O error connecting to the datastore: " + e.getMessage()); } }
From source file:com.revo.deployr.client.core.impl.RClientImpl.java
public RClientImpl(String serverurl, int concurrentCallLimit, boolean allowSelfSignedSSLCert) throws RClientException, RSecurityException { log.debug("Creating client connection: serverurl=" + serverurl + ", concurrentCallLimit=" + concurrentCallLimit + ", allowSelfSignedSSLCert=" + allowSelfSignedSSLCert); this.serverurl = serverurl; // Create and initialize HTTP parameters HttpParams httpParams = new BasicHttpParams(); // Set Infinite Connection and Socket Timeouts. HttpConnectionParams.setConnectionTimeout(httpParams, 0); HttpConnectionParams.setSoTimeout(httpParams, 0); ConnManagerParams.setMaxTotalConnections(httpParams, concurrentCallLimit); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(concurrentCallLimit)); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); if (allowSelfSignedSSLCert) { /*/*from w w w .j av a2 s . c o m*/ * Register scheme for "https" that bypasses * SSL cert trusted-origin verification check * which makes it possible to connect to a * DeployR server using a self-signed certificate. * * Recommended for prototyping and testing only, * not recommended for production environments. */ TrustStrategy blindTrust = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] certificate, String authType) { return true; } }; try { sslSocketFactory = new SSLSocketFactory(blindTrust, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme("https", 8443, sslSocketFactory)); } catch (GeneralSecurityException gsex) { String exMsg = "Self-signed SSL cert config failed, " + gsex.getMessage(); log.debug(exMsg); throw new RSecurityException(exMsg, 0); } } // Create a HttpClient with the ThreadSafeClientConnManager. // This connection manager must be used if more than one thread will // be using the HttpClient. ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); httpClient = new DefaultHttpClient(cm, httpParams); // Enable cookie handling by setting cookie policy on HttpClient. httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); log.debug("Created client connection: httpClient=" + httpClient); eService = Executors.newCachedThreadPool(); }
From source file:org.gluu.oxtrust.action.ManageCertificateAction.java
@Restrict("#{s:hasPermission('configuration', 'access')}") public String generateCSR(String fileName) { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); }/*w ww. j av a 2 s.com*/ KeyPair pair = getKeyPair(fileName); boolean result = false; if (pair != null) { String url = applicationConfiguration.getIdpUrl().replaceFirst(".*//", ""); String csrPrincipal = String.format("CN=%s", url); X500Principal principal = new X500Principal(csrPrincipal); PKCS10CertificationRequest csr = null; try { csr = new PKCS10CertificationRequest("SHA1withRSA", principal, pair.getPublic(), null, pair.getPrivate()); } catch (GeneralSecurityException e) { log.error(e.getMessage(), e); return OxTrustConstants.RESULT_FAILURE; } // Form download responce StringBuilder response = new StringBuilder(); response.append(BEGIN_CERT_REQ + "\n"); response.append(WordUtils.wrap(new String(Base64.encode(csr.getDEREncoded())), 64, "\n", true) + "\n"); response.append(END_CERT_REQ + "\n"); result = ResponseHelper.downloadFile("csr.pem", OxTrustConstants.CONTENT_TYPE_TEXT_PLAIN, response.toString().getBytes(), facesContext); } return result ? OxTrustConstants.RESULT_SUCCESS : OxTrustConstants.RESULT_FAILURE; }
From source file:eu.eidas.auth.engine.core.impl.SignSW.java
private X509Certificate getSignatureCertificate(final Signature signature) throws SAMLEngineException { try {/*from ww w .j a v a 2s. c o m*/ final KeyInfo keyInfo = signature.getKeyInfo(); final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0) .getX509Certificates().get(0); final CertificateFactory certFact = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue())); final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis); return cert; } catch (GeneralSecurityException e) { LOG.debug("ERROR : GeneralSecurityException.", e); LOG.warn("ERROR : GeneralSecurityException.", e.getMessage()); throw new SAMLEngineException(e); } }