@Test public void testToThrift() throws DestroyFailedException { // verify thrift serialization Credentials creds = new Credentials("test", new PasswordToken("testing")); TCredentials tCreds = creds.toThrift(new MockInstance()); assertEquals("test", tCreds.getPrincipal()); assertEquals(PasswordToken.class.getName(), tCreds.getTokenClassName()); assertArrayEquals( AuthenticationTokenSerializer.serialize(new PasswordToken("testing")), tCreds.getToken()); // verify that we can't serialize if it's destroyed creds.getToken().destroy(); try { creds.toThrift(new MockInstance()); fail(); } catch (Exception e) { assertTrue(e instanceof RuntimeException); assertTrue(e.getCause() instanceof AccumuloSecurityException); assertTrue( AccumuloSecurityException.class .cast(e.getCause()) .getSecurityErrorCode() .equals(SecurityErrorCode.TOKEN_EXPIRED)); } }
public Credentials getOleFsMvnCredentials() { Credentials c = new Credentials(); c.setUsername("olefsmvn"); c.setPassword("olefsmvn"); c.setUrl("jdbc:mysql://localhost/olefsmvn"); return c; }
@Override protected void login(LoginController controller, Credentials credentials) throws IOException { try { client = new CloudFrontService( new AWSCredentials(credentials.getUsername(), credentials.getPassword())) { @Override protected HttpClient initHttpConnection() { return CloudFrontDistributionConfiguration.this.http(); } }; // Provoke authentication error for (String container : this.getContainers()) { for (Distribution.Method method : getMethods(container)) { // Cache first container this.cache(this.getOrigin(method, container), method); break; } break; } } catch (CloudFrontServiceException e) { log.warn(String.format("Invalid account: %s", e.getMessage())); this.message(Locale.localizedString("Login failed", "Credentials")); controller.fail(host.getProtocol(), credentials); this.login(); } }
public Credentials unmarshall(StaxUnmarshallerContext context) throws Exception { Credentials credentials = new Credentials(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 2; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return credentials; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("AccessKeyId", targetDepth)) { credentials.setAccessKeyId(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("SecretAccessKey", targetDepth)) { credentials.setSecretAccessKey(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("SessionToken", targetDepth)) { credentials.setSessionToken(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("Expiration", targetDepth)) { credentials.setExpiration(DateStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return credentials; } } } }
/** * Tests FileURL's getters and setters. * * @throws MalformedURLException should not happen */ @Test public void testAccessors() throws MalformedURLException { FileURL url = getRootURL(); String scheme = getScheme(); Credentials credentials = new Credentials("login", "password"); String host = "host"; int port = 10000; String path = getSchemePath("/path/to"); String query = "query"; url.setScheme(scheme); url.setCredentials(credentials); url.setHost(host); url.setPort(port); url.setPath(path); url.setQuery(query); url.setProperty("name", "value"); assert scheme.equals(url.getScheme()); assert credentials.equals(url.getCredentials(), true); assert host.equals(url.getHost()); assert port == url.getPort(); assert path.equals(url.getPath()); assert query.equals(url.getQuery()); assert "to".equals(url.getFilename()); assert "value".equals(url.getProperty("name")); // Test null values url.setCredentials(null); url.setHost(null); url.setPort(-1); url.setPath("/"); url.setQuery(null); url.setProperty("name", null); assert scheme.equals(url.getScheme()); assert url.getCredentials() == null; assert !url.containsCredentials(); assert url.getHost() == null; assert -1 == url.getPort(); assert "/".equals(url.getPath()); assert url.getQuery() == null; assert url.getFilename() == null; assert url.getProperty("name") == null; assert (scheme + "://").equals(url.toString(true, false)); // Path cannot be null, the path is supposed to be "/" if a null or empty value is specified url.setPath(null); assert "/".equals(url.getPath()); url.setPath(""); assert "/".equals(url.getPath()); // Path must always start with a leading '/', if the specified does not then a '/' is // automatically added url.setPath("path/to"); assert "/path/to".equals(url.getPath()); }
public Connection getConnection(Credentials c) { try { Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection(c.getUrl(), c.getUsername(), c.getPassword()); } catch (Throwable e) { throw new IllegalArgumentException(e); } }
private static String getUsername(FileURL url) { Credentials credentials = url.getCredentials(); String username; if (credentials == null || (username = credentials.getLogin()).equals("")) username = getDefaultUsername(); return username; }
protected ApplicationUser findApplicationUserByCredentials(final Credentials credentials) { return getEntityManager() .createQuery( "SELECT au FROM ApplicationUser au WHERE au.username = :username AND au.password = :password", ApplicationUser.class) .setParameter(USERNAME, credentials.getUsername()) .setParameter(PASSWORD, credentials.getPassword()) .getSingleResult(); }
public static Credentials getCredentials(Context context) { // TODO Auto-generated method stub Credentials credentials = new Credentials(); credentials.username = getSharedPreferences(context).getString("username", ""); credentials.password = getSharedPreferences(context).getString("password", ""); credentials.checkBoxStatus = getSharedPreferences(context).getBoolean("checkBoxStatus", false); return credentials; }
/** * Returns a <code>Credentials</code> object * * @return a <code>Credentials</code> object */ public Credentials build() { m_credentials = new Credentials(m_hostname); m_credentials.username = this.m_username; m_credentials.defaulRemotetPath = this.m_defaultRemotePath; m_credentials.password = this.m_password; m_credentials.protocol = this.m_protocol; m_credentials.port = this.m_port; return m_credentials; }
public static GitHubClient createGitHubClientFromCredentials(Credentials credentials) { GitHubClient gitHubClient = new GitHubClient(); String user = credentials.getUser(); String password = credentials.getPassword(); String oauthToken = credentials.getOauthToken(); if (oauthToken != null && !oauthToken.isEmpty()) { return gitHubClient.setOAuth2Token(oauthToken); } else if (user != null && !user.isEmpty() && password != null && !password.isEmpty()) { return gitHubClient.setCredentials(user, password); } else { throw new RuntimeException("Unable to initialize GitHubClient: missing credentials!"); } }
@Test public void testToString() { Credentials creds = new Credentials(null, null); assertEquals(Credentials.class.getName() + ":null:null:<hidden>", creds.toString()); creds = new Credentials("", new NullToken()); assertEquals( Credentials.class.getName() + "::" + NullToken.class.getName() + ":<hidden>", creds.toString()); creds = new Credentials("abc", null); assertEquals(Credentials.class.getName() + ":abc:null:<hidden>", creds.toString()); creds = new Credentials("abc", new PasswordToken("")); assertEquals( Credentials.class.getName() + ":abc:" + PasswordToken.class.getName() + ":<hidden>", creds.toString()); }
/** * Ensure that non URL-safe characters in login and password parts are properly handled, both when * parsing and representing URLs as string. * * @throws MalformedURLException should not happen */ @Test public void testCredentialsURLEncoding() throws MalformedURLException { FileURL url = getRootURL(); String urlDecodedString = ":@&=+$,/?t%#[]"; String urlEncodedString = "%3A%40%26%3D%2B%24%2C%2F%3Ft%25%23%5B%5D"; url.setCredentials(new Credentials(urlDecodedString, urlDecodedString)); String urlRep = url.getScheme() + "://" + urlEncodedString + ":" + urlEncodedString + "@"; assert urlRep.equals(url.toString(true, false)); url = FileURL.getFileURL(urlRep); Credentials credentials = url.getCredentials(); assert credentials.getLogin().equals(urlDecodedString); assert credentials.getPassword().equals(urlDecodedString); }
/** * Returns a string representation of the credentials. * * @param credMap The credentials. * @return The string representation. */ private static String getCredentialsStringRepresentation( final Map<AuthScope, Credentials> credMap) { StringBuffer sbResult = new StringBuffer(); Iterator<AuthScope> iter = credMap.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); Credentials cred = credMap.get(key); if (sbResult.length() > 0) { sbResult.append(", "); } sbResult.append(key); sbResult.append("#"); sbResult.append(cred.toString()); } return sbResult.toString(); }
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Request modifiedRequest = request .newBuilder() .addHeader( "Authorization", "Basic " + Base64.getEncoder() .encodeToString( (credentials.getUsername() + ":" + credentials.getPassword()) .getBytes())) .build(); return chain.proceed(modifiedRequest); }
/* */ public KrbApReq( Credentials paramCredentials, boolean paramBoolean1, boolean paramBoolean2, boolean paramBoolean3, Checksum paramChecksum) /* */ throws Asn1Exception, KrbCryptoException, KrbException, IOException /* */ { /* 104 */ APOptions localAPOptions = paramBoolean1 ? new APOptions(2) : new APOptions(); /* */ /* 107 */ if (DEBUG) { /* 108 */ System.out.println(">>> KrbApReq: APOptions are " + localAPOptions); /* */ } /* 110 */ EncryptionKey localEncryptionKey = paramBoolean2 ? new EncryptionKey(paramCredentials.getSessionKey()) : null; /* */ /* 114 */ LocalSeqNumber localLocalSeqNumber = new LocalSeqNumber(); /* */ /* 116 */ init( localAPOptions, paramCredentials, paramChecksum, localEncryptionKey, localLocalSeqNumber, null, 11); /* */ }
/** * Ensures that the values returned by {@link FileURL#getGuestCredentials()} and {@link * SchemeHandler#getGuestCredentials()} match the expected one returned by {@link * #getGuestCredentials()}. * * @throws MalformedURLException should not happen */ @Test public void testGuestCredentials() throws MalformedURLException { FileURL url = getRootURL(); Credentials expectedGuestCredentials = getGuestCredentials(); // Assert that the guest credentials values returned by the FileURL and its handler match the // expected one // and are consistent if (expectedGuestCredentials == null) { assert url.getGuestCredentials() == null; assert url.getHandler().getGuestCredentials() == null; } else { assert expectedGuestCredentials.equals(url.getGuestCredentials()); assert expectedGuestCredentials.equals(url.getHandler().getGuestCredentials()); } }
static Krb5InitCredential getInstance(Krb5NameElement name, Credentials delegatedCred) throws GSSException { EncryptionKey sessionKey = delegatedCred.getSessionKey(); /* * all of the following data is optional in a KRB-CRED * messages. This check for each field. */ PrincipalName cPrinc = delegatedCred.getClient(); PrincipalName sPrinc = delegatedCred.getServer(); KerberosPrincipal client = null; KerberosPrincipal server = null; Krb5NameElement credName = null; if (cPrinc != null) { String fullName = cPrinc.getName(); credName = Krb5NameElement.getInstance(fullName, Krb5MechFactory.NT_GSS_KRB5_PRINCIPAL); client = new KerberosPrincipal(fullName); } // XXX Compare name to credName if (sPrinc != null) { server = new KerberosPrincipal(sPrinc.getName(), KerberosPrincipal.KRB_NT_SRV_INST); } return new Krb5InitCredential( credName, delegatedCred, delegatedCred.getEncoded(), client, server, sessionKey.getBytes(), sessionKey.getEType(), delegatedCred.getFlags(), delegatedCred.getAuthTime(), delegatedCred.getStartTime(), delegatedCred.getEndTime(), delegatedCred.getRenewTill(), delegatedCred.getClientAddresses()); }
/** * Get the currently logged in user. * * @return the logged in user * @throws IOException if login fails */ public static synchronized UserGroupInformation getLoginUser() throws IOException { if (loginUser == null) { try { Subject subject = new Subject(); LoginContext login; if (isSecurityEnabled()) { login = new LoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, subject); } else if (useConfiguredFileAuth) { login = new LoginContext(HadoopConfiguration.FILE_CONFIG_NAME, subject); } else { login = new LoginContext(HadoopConfiguration.SIMPLE_CONFIG_NAME, subject); } login.login(); loginUser = new UserGroupInformation(subject); loginUser.setLogin(login); // loginUser.setAuthenticationMethod(isSecurityEnabled() ? // AuthenticationMethod.KERBEROS : // AuthenticationMethod.SIMPLE); AuthenticationMethod authMethod = AuthenticationMethod.SIMPLE; if (isSecurityEnabled()) { authMethod = AuthenticationMethod.KERBEROS; } else if (useConfiguredFileAuth) { authMethod = AuthenticationMethod.CONFIGFILE; } else { authMethod = AuthenticationMethod.SIMPLE; } loginUser.setAuthenticationMethod(authMethod); loginUser = new UserGroupInformation(login.getSubject()); String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION); if (fileLocation != null && isSecurityEnabled()) { // load the token storage file and put all of the tokens into the // user. Credentials cred = Credentials.readTokenStorageFiles(fileLocation, conf); for (Token<?> token : cred.getAllTokens()) { loginUser.addToken(token); } } loginUser.spawnAutoRenewalThreadForUserCreds(); } catch (LoginException le) { throw new IOException("failure to login", le); } } return loginUser; }
protected String authenticateUser(Credentials credentials) throws InvalidCredentialsException { try { final ApplicationUser applicationUser = findApplicationUserByCredentials(credentials); return credentials.generateJWToken(); } catch (final NoResultException nre) { throw new InvalidCredentialsException("Invalid username or password"); } catch (final Exception e) { throw new InvalidCredentialsException(e.getMessage()); } }
public void validate() throws org.apache.thrift.TException { // check for required fields if (!is_set_initial_status()) { throw new org.apache.thrift.protocol.TProtocolException( "Required field 'initial_status' is unset! Struct:" + toString()); } // check for sub-struct validity if (creds != null) { creds.validate(); } }
public Connection connection() { Connection conn; try { Class.forName(credentials.getDriver()).newInstance(); conn = DriverManager.getConnection( credentials.getUrl(), credentials.getUsername(), credentials.getPassword()); return conn; } catch (InstantiationException ex) { Logger.getLogger(GetSQLConnection.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (IllegalAccessException ex) { Logger.getLogger(GetSQLConnection.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (SQLException ex) { Logger.getLogger(GetSQLConnection.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (ClassNotFoundException ex) { Logger.getLogger(GetSQLConnection.class.getName()).log(Level.SEVERE, null, ex); return null; } }
@Test public void testSession() { String password = Credentials.getPassword(); assertFalse("Password can be an empty string", password.equals("")); for (int i = 0; i < 10; i++) { Session session = context.getSession(); assertTrue("Notes Session could not be retrieved at the iteration " + i, session.isOpen()); assertFalse( "There's a problem with the Session at the iteration " + i + ". I can't retrieve the current user name.", session.getUserName().equals("")); context.closeSession(); } }
public static Credentials getCredentials(Project project) { String user = null; String password = null; String oauth = null; Credentials credentials; // check userhome/.github Properties properties = GitHubUtil.getProperties(null); // check dir specified by property 'github.ant.filepath' if (properties == null && project != null) { // check dir/.github try { String filePath = project.getUserProperty("github.ant.filepath"); properties = GitHubUtil.getProperties(filePath); } catch (NullPointerException e) { // ignore: userproperty does not exist. } } if (properties != null) { user = properties.getProperty("github.ant.user"); password = properties.getProperty("github.ant.password"); oauth = properties.getProperty("github.ant.oauth"); } else { // try to resolve properties from commandline try { user = project.getProperty("github.ant.user"); password = project.getProperty("github.ant.password"); oauth = project.getProperty("github.ant.oauth"); } catch (NullPointerException e) { } } return Credentials.createNewCredentials(user, password, oauth); }
/** * Returns GP ServiceClient instance used for this for this maven session. * * <p>This implementation resolves service credentials in the following order: * * <ol> * <li>A json file specified by user defined property 'gp.credentials.json'. This is typically * specified by a command line argument, e.g.<br> * <code>-D gp.credentials.json=/home/yoshito/gpcreds.json</code> * <li>A json file specified by <credentialsJson> in pom.xml * <li>A set of fields specified by <credentials> in pom.xml * </ol> * * @return An instance of ServiceClient. * @throws MojoFailureException on a failure. */ protected ServiceClient getServiceClient() throws MojoFailureException { if (gpClient == null) { synchronized (this) { Credentials creds = credentials; if (credentialsJson != null) { getLog().info("Reading GP service credentials from " + credentialsJson.getAbsolutePath()); try (InputStreamReader reader = new InputStreamReader(new FileInputStream(credentialsJson), StandardCharsets.UTF_8)) { Gson gson = new Gson(); creds = gson.fromJson(reader, Credentials.class); } catch (IOException e) { throw new MojoFailureException( "Error while reading the specified JSON credential file.", e); } catch (JsonSyntaxException e) { throw new MojoFailureException("Bad JSON credential format.", e); } } if (creds == null) { throw new MojoFailureException( "Globalization Pipeline service credentials are not specified."); } if (!creds.isValid()) { throw new MojoFailureException("Bad credentials: " + creds); } getLog().debug("Using GP service credentials " + creds); gpClient = ServiceClient.getInstance( ServiceAccount.getInstance( creds.getUrl(), creds.getInstanceId(), creds.getUserId(), creds.getPassword())); } } return gpClient; }
/** * @param username User * @param password Secret */ public void setCredentials(final String username, final String password) { credentials.setUsername(username); credentials.setPassword(password); }
public void initializeResources() { if (_speechKit != null) { return; } _speechKit = SpeechKit.initialize( _context, Credentials.getSpeechKitAppId(), Credentials.getSpeechKitServer(), Credentials.getSpeechKitPort(), // the port number, e.g. 443, Credentials.getSpeechKitSsl(), // true if SSL should be used, Credentials .getSpeechKitCertSummary(), // the summary String (must match the Common Name (CN) // of the used certificate-data; as provided by Nuance) Credentials.getSpeechKitCertData(), // the certificate data, Credentials.getSpeechKitAppKey()); _speechKit.connect(); int beepResId = _context .getResources() .getIdentifier("rawbeep", "raw", _context.getApplicationInfo().packageName); // TODO: Keep an eye out for audio prompts not-working on the Android 2 or other 2.2 devices. this._defaultStartPrompt = _speechKit.defineAudioPrompt(beepResId); this._defaultStopPrompt = Prompt.vibration(100); _speechKit.setDefaultRecognizerPrompts( this._defaultStartPrompt, this._defaultStopPrompt, null, null); // Create Vocalizer listener Vocalizer.Listener vocalizerListener = new Vocalizer.Listener() { @Override public void onSpeakingBegin(Vocalizer vocalizer, String text, Object context) { Log.d(PLUGIN_TTS_NAME, String.format("start speaking: '%s'", text)); if (context instanceof Vocalizer.Listener) { ((Vocalizer.Listener) context).onSpeakingBegin(vocalizer, text, null); } } @Override public void onSpeakingDone( Vocalizer vocalizer, String text, SpeechError error, Object context) { // Use the context to determine if this was the final TTS phrase Log.d(PLUGIN_TTS_NAME, String.format("speaking done: '%s'", text)); if (context instanceof Vocalizer.Listener) { ((Vocalizer.Listener) context).onSpeakingDone(vocalizer, text, error, null); } } }; // Create a single Vocalizer here. _vocalizer = _speechKit.createVocalizerWithLanguage(_currentLanguage, vocalizerListener, new Handler()); _recognitionListener = createRecognitionListener(); _handler = new Handler(); }
protected NuanceEngine(Context ctx, CordovaPreferences prefs) { _context = ctx; Credentials.init(prefs); initializeResources(); }
/** @param serialized A valid bookmark dictionary */ public <T> Host(T serialized) { final Deserializer dict = DeserializerFactory.createDeserializer(serialized); Object uuidObj = dict.stringForKey("UUID"); if (uuidObj != null) { this.setUuid(uuidObj.toString()); } Object protocolObj = dict.stringForKey("Protocol"); if (protocolObj != null) { this.setProtocol(ProtocolFactory.forName(protocolObj.toString())); } Object providerObj = dict.stringForKey("Provider"); if (providerObj != null) { this.setProtocol(ProtocolFactory.forName(providerObj.toString())); } Object hostnameObj = dict.stringForKey("Hostname"); if (hostnameObj != null) { this.setHostname(hostnameObj.toString()); } Object usernameObj = dict.stringForKey("Username"); if (usernameObj != null) { credentials.setUsername(usernameObj.toString()); } Object passwordObj = dict.stringForKey("Password"); if (passwordObj != null) { credentials.setPassword(passwordObj.toString()); } Object cdnCredentialsObj = dict.stringForKey("CDN Credentials"); if (cdnCredentialsObj != null) { cdnCredentials.setUsername(cdnCredentialsObj.toString()); } Object keyObj = dict.stringForKey("Private Key File"); if (keyObj != null) { this.getCredentials().setIdentity(LocalFactory.createLocal(keyObj.toString())); } Object portObj = dict.stringForKey("Port"); if (portObj != null) { this.setPort(Integer.parseInt(portObj.toString())); } Object pathObj = dict.stringForKey("Path"); if (pathObj != null) { this.setDefaultPath(pathObj.toString()); } Object workdirObj = dict.stringForKey("Workdir"); if (workdirObj != null) { this.setWorkdir(workdirObj.toString()); } Object nicknameObj = dict.stringForKey("Nickname"); if (nicknameObj != null) { this.setNickname(nicknameObj.toString()); } Object encodingObj = dict.stringForKey("Encoding"); if (encodingObj != null) { this.setEncoding(encodingObj.toString()); } Object connectModeObj = dict.stringForKey("FTP Connect Mode"); if (connectModeObj != null) { if (connectModeObj.toString().equals(FTPConnectMode.PORT.toString())) { this.setFTPConnectMode(FTPConnectMode.PORT); } if (connectModeObj.toString().equals(FTPConnectMode.PASV.toString())) { this.setFTPConnectMode(FTPConnectMode.PASV); } } Object connObj = dict.stringForKey("Maximum Connections"); if (connObj != null) { this.setMaxConnections(Integer.valueOf(connObj.toString())); } Object downloadObj = dict.stringForKey("Download Folder"); if (downloadObj != null) { this.setDownloadFolder(LocalFactory.createLocal(downloadObj.toString())); } Object timezoneObj = dict.stringForKey("Timezone"); if (timezoneObj != null) { this.setTimezone(TimeZone.getTimeZone(timezoneObj.toString())); } Object commentObj = dict.stringForKey("Comment"); if (commentObj != null) { this.setComment(commentObj.toString()); } Object urlObj = dict.stringForKey("Web URL"); if (urlObj != null) { this.setWebURL(urlObj.toString()); } Object accessObj = dict.stringForKey("Access Timestamp"); if (accessObj != null) { this.setTimestamp(new Date(Long.parseLong(accessObj.toString()))); } }
/** * Return true if Credentials are UsernamePasswordCredentials, false otherwise. * * @return true, if the credentials are supported by this resolver */ public boolean supports(final Credentials credentials) { return credentials != null && UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass()); }