Hi
I am loading a property file to establish DB connection,
ex:
DB1="JDBc................", username , password
above line is as in property file, but when i call getConnection method I need to send url, username and pw.
How can I parse it.
You can put your key/value pairs in a properties file like this:
dbUrl = yourURL
username = yourusername
password = yourpassword
Then you can load them into your app from the properties file:
private void loadProps() {
try {
InputStream is = getClass().getResourceAsStream("database_props.properties");
props = new Properties();
props.load(is);
is.close();
dbConnStr = props.getProperty("dbUrl");
username = props.getProperty("username");
password = props.getProperty("password");
}
catch(IOException ioe) {
log.error("IOException in loadProps");
for(StackTraceElement ste : ioe.getStackTrace())
log.error(ste.toString());
}
}
And then you can use those values to create your connection.
You can split the entry:
String dbProperty = prop.getProperty("DB1");
String[] dbDetails = dbProperty.split(",", 3);
dbDetails[0] will hold your JDBC..., [1] your username and [2] your password
Better still, you might want to hold them in different properties (As lweller said)
db.username = scott
db.password = tiger
db.url = ....
This way you get better clarity and control.
It is better to define separately
dburl =....
username =....
password = ...
Still if you want to parse it, you can use the split method of string to split by comma
Related
When I try to change the password of a user via LDAP, in whose AD account the setting is set that the password must be changed at the next login, I get the following error:
cause: javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C090447, comment: AcceptSecurityContext error, data 773, v3839
Subcode 773 indicates that the user must reset the password, which is exactly what I intend to do right now.
With the following code I can successfully change the password if the above flag is not set:
public void updateUserPassword(String user, String oldPassword,
String newPassword) throws NamingException, LoginException {
try {
InitialDirContext ctx = this.getContext();
String filter = "(&(objectClass=user)(sAMAccountName=" + user + "))";
String baseDn = (String) this.getActiveDirectoryProps().get("baseDN_User");
// Search for user entry
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctls.setReturningObjFlag(true);
String[] returnAttrs = new String[3];
returnAttrs[0] = "cn"; // Common Name
returnAttrs[1] = "displayName";
returnAttrs[2] = "description";
NamingEnumeration<SearchResult> enumSearchResult = ctx.search(baseDn, filter, returnAttrs, ctls);
if (enumSearchResult.hasMore()) {
SearchResult result = enumSearchResult.next();
DirContext userCtx = (DirContext) result.getObject();
// Change the BindUser
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userCtx.getNameInNamespace());
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword);
// Update password
Attribute oldattr = new BasicAttribute("unicodePwd", toUnicodeBytes(oldPassword));
Attribute newattr = new BasicAttribute("unicodePwd", toUnicodeBytes(newPassword));
ModificationItem olditem = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, oldattr);
ModificationItem newitem = new ModificationItem(DirContext.ADD_ATTRIBUTE, newattr);
String dn = userCtx.getNameInNamespace();
ctx.modifyAttributes(dn, new ModificationItem[]{olditem, newitem});
}
ctx.close();
} catch (final NamingException nE) {
//
} catch (Exception E) {
//
} finally {
//
}
}
So, do you have any idea what needs to be changed? Or what the reason is that it does not work?
My guess is that you just need to remove these lines:
// Change the BindUser
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userCtx.getNameInNamespace());
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword);
You can't authenticate with the old password since it's no longer valid. But you also don't need to bind with the user's own credentials when changing the password, since you have to provide the old password in the request.
These lines may give you trouble too:
Attribute oldattr = new BasicAttribute("unicodePwd", toUnicodeBytes(oldPassword));
Attribute newattr = new BasicAttribute("unicodePwd", toUnicodeBytes(newPassword));
The passwords do have to converted to unicode bytes, but they also have to be enclosed in double quotes too ("). So you'll probably have to add double quotes before passing it to toUnicodeBytes().
You can manage it in two steps:
In case "user must change password" it set, you should change the password of the user to an initial password as admin (bind).
Attribute oldattr = new BasicAttribute("unicodePwd", toUnicodeBytes(oldPassword));
Attribute newattr = new BasicAttribute("unicodePwd", toUnicodeBytes(initialPassword));
Then, after a bind with the user with the (initial) password the user (himself) should change his password.
Attribute oldattr = new BasicAttribute("unicodePwd", toUnicodeBytes(initialPassword)));
Attribute newattr = new BasicAttribute("unicodePwd", toUnicodeBytes(newPassword));
(with double quotes, if you like)
This can work also in case if the user's password is expired.
I have this URL:
String template = "https://{subdomain}.apache.com/t/information/{information_service}";
I would like to know how can I replace the values {subdomain} and {information_service} to build a new URL. Something like this
String subdomain = "newHouse";
String information_service = "rooms";
Note: I will get different values for each iteration and session, this is just an example
Output
String URL = "https://newHouse.apache.com/t/information/rooms";
I tried with this example
URIBuilder builder = new URIBuilder()
.setScheme("http")
.setHost("apache.org")
.setPath("/shindig")
.addParameter("helloWorld", "foo&bar")
.setFragment("foo");
builder.toString();
But I wonder if there are something more directly to replace the value of placeholders
I have a credential store that I created with Elytron's tool giving a clear text password: "mypassword". In my Java program I can connect to the store with the following code;
Password storePassword = ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR,"mypassword");
CredentialStore.ProtectionParameter protectionParameter = new CredentialStore.CredentialSourceProtectionParameter(
IdentityCredentials.NONE.withCredential(new PasswordCredential(storePassword)));
Provider provider = new WildFlyElytronPasswordProvider();
Security.addProvider(provider);
CredentialStore credentialStore = CredentialStore.getInstance(KeyStoreCredentialStore.KEY_STORE_CREDENTIAL_STORE);
// Configure and Initialise the CredentialStore
String configPath = System.getProperty("jboss.server.data.dir");
Map<String, String> configuration = new HashMap<>();
String path = configPath + File.separator + "credentials" + File.separator + "csstore.jceks";
configuration.put("keyStoreType", "JCEKS");
configuration.put("location", path);
configuration.put("modifiable", "false");
//Initialize credentialStore
credentialStore.initialize(configuration, protectionParameter);
However, I now want to connect to the credential store with an encrypted password instead of a clear text. For this purpose, I again used Elytron's tool to create a Masked Passowrd of "mypassword" with the following command;
elytron-tool.sh mask --salt 12345678 --iteration 123 --secret mypassword;
Here the values for salt and iteration are just random, could be anything. The above command gives me the masked password which is;
MASK-38PaKyS.9hHaRq7pAaE5tB;12345678;123
I now need a way to connect to credential store with this masked password within my Java program. I found that there is also a class called "MaskedPassword" which I might use but I couldn't find out how.
Any suggestions?
When you use elytron tool to generate masked password then you get string with prefix MASK- and suffix with salt and iteration
in your case - MASK-38PaKyS.9hHaRq7pAaE5tB;12345678;123
you can use below piece of code to decrypt the masked password,
private char[] getUnmaskedPass(String maskedPassword) throws GeneralSecurityException {
int maskLength = enter code here"MASK-".length();
if (maskedPassword == null || maskedPassword.length() <= maskLength) {
throw new GeneralSecurityException();
}
String[] parsed = maskedPassword.substring(maskLength).split(";");
if (parsed.length != 3) {
throw new GeneralSecurityException();
}
String encoded = parsed[0];
String salt = parsed[1];
int iteration = Integer.parseInt(parsed[2]);
PasswordBasedEncryptionUtil encryptUtil = new PasswordBasedEncryptionUtil.Builder().picketBoxCompatibility().salt(salt).iteration(iteration)
.decryptMode().build();
return encryptUtil.decodeAndDecrypt(encoded);
}
Now you can use this in your piece of code as a clearPassword. I hope that helped.
Source - https://github.com/wildfly-security/wildfly-elytron-tool/blob/master/src/main/java/org/wildfly/security/tool/MaskCommand.java static char[] decryptMasked(String maskedPassword)
We can create it using the below code...
Password storePassword = MaskedPassword.createRaw(MaskedPassword.ALGORITHM_MASKED_MD5_DES, <CREDENTIAL_STORE_ENTRY_PREFIX>.toCharArray(), 120,"12345678".getBytes(StandardCharsets.UTF_8),"MASK-38PaKyS.9hHaRq7pAaE5tB".getBytes(StandardCharsets.UTF_8));
....
....
If we have an url e.g www.google.de how can I get ONLY the "google"
In Java new URL (url).getHost(); does work but it gives me google.de
and this is not what I want to have.
Thank you
EDIT: If we have something like www.google.co.uk then I also want to have only "google" as result.
I dont want "google.de" or "www.google" I ONLY want "google"
Splitting on a period and selecting the first or second element (whichever is not "www") would work:
URL url = new URL("http://www.host.ext.ext");
String host = url.getHost(); // host = "www.host.ext.ext"
String splitHost = host.split("\\.") // splitHost = { "www", "host", "ext", "ext" }
host = splitHost[0].equals("www") ? splitHost[1] : splitHost[0]; // host = "host"
If there is anything more than http://www. before it, and the extension is potentially more than two "extensions" (.co.uk for instance), then there is no easy way to get just the part you want. As far as I know, you would have to try iterating over a list of extensions and return the part immediately before the longest matching extension.
The most basic solution would be using
System.out.println(url.split("\\.")[1]);
Or you could try this https://stackoverflow.com/a/23079402/2555419
public String getHostName(String url) {
URI uri = new URI(url);
String hostname = uri.getHost();
// to provide faultproof result, check if not null then return only hostname, without www.
if (hostname != null) {
return hostname.startsWith("www.") ? hostname.substring(4) : hostname;
}
return hostname;
}
I have an URL address like: http://myfile.com/File1/beauty.png
I have to remove http://site address/ from main string
That mean result should be File1/beauty.png
Note: site address might be anything(e.g some.com, some.org)
See here: http://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html
Just create a URL object out of your string and use URL.getPath() like this:
String s = new URL("http://myfile.com/File1/beauty.png").getPath();
If you don't need the slash at the beginning, you can remove it via s.substring(1, s.length());
Edit, according to comment:
If you are not allowed to use URL, this would be your best bet: Extract main domain name from a given url
See the accepted answer. Basically you have to get a TLD list, find the domain and substract everything till the domain names' end.
If, as you say, you only want to use the standard String methods then this should do it.
public static String getPath(String url){
if(url.contains("://")){
url = url.substring(url.indexOf("://")+3);
url = url.substring(url.indexOf("/") + 1);
} else {
url = url.substring(url.indexOf("/")+1);
}
return url;
}
If the url contains :// then we know that the string you are looking for will come after the third /. Otherwise, it should come after the first. If we do the following;
System.out.println(getPath("http://myfile.com/File1/beauty.png"));
System.out.println(getPath("https://myfile.com/File1/beauty.png"));
System.out.println(getPath("www1.myfile.com/File1/beauty.png"));
System.out.println(getPath("myfile.co.uk/File1/beauty.png"));;
The output is;
File1/beauty.png
File1/beauty.png
File1/beauty.png
File1/beauty.png
You can use the below approach to fetch the required data.
String url = "http://myfile.org/File1/beauty.png";
URL u = new URL(url);
String[] arr = url.split(u.getAuthority());
System.out.println(arr[1]);
Output - /File1/beauty.png
String s = "http://www.freegreatpicture.com/files/146/26189-abstract-color-background.jpg";
s = s.substring(s.indexOf("/", str.indexOf("/") + 1));