how to display the decrypted and splited Strings in order? - java

i need some help and guidance in displaying the splitted Strings in order.
let say, i have username, password, nonceInString. i had successfully encrypted and decrypted those. then i split the decrypted data. it was done, too.
i want to display the decrypted data in order.
something like this.
userneme: sebastian
password: harrypotter
nonce value: sdgvay1saq3qsd5vc6dger9wqktue2tz*
i tried the following code, but it didn't display like i wish to.
pls help. thanks a lot in advance.
String codeWord = username + ";" + password + ";" + nonceInString;
String encryptedData = aesEncryptDecrypt.encrypt(codeWord);
String decryptedData = aesEncryptDecrypt.decrypt(encryptedData);
String[] splits = decryptedData.split(";");
String[] variables = {"username", "password", "nonce value"};
for (String data : variables){
for (String item : splits){
System.out.println( data + ": "+ item);
}
}

Your nested for-each logic is wrong; instead, you need to explicitly pair up the elements of the array by an index:
for (int i = 0; i < variables.length; i++) {
System.out.println(variables[i] + ":" + splits[i]);
}
Note that this assumes that both arrays have the same lengths, and will throw an ArrayIndexOutBoundsException if the splits array is shorter than the variables array.
As a side note, for key-value mapping data structure, you may want to look at java.util.Map.
import java.util.*;
//...
Map<String,String> map = new HashMap<String,String>();
map.put("username", "sebastian");
map.put("password", "harrypotter");
System.out.println(map); // prints "{username=sebastian, password=harrypotter}"
System.out.println(map.get("password")); // prints "harrypotter"

thats because your inner loop will loop through all the values in splits for each element in variables.
i assume you got something like
username ..
username ..
username ..
password ..
pa....

Related

jpa containing query with list

I have a table Called Media that has a column "tagList" of type List. I want to search media based on list of input tag.
I need a method like this.
List<Media> findByTagListContaining(<List> inputTagList);
This gives error but
List<Media> findByTagListContaining(String inputTag);
works fine. How to make first one works. I need partial matching as well for example if any row has tagList ["mentos","bollywood","comedy"]
and inputTagList is ["men","boll"] that row should come in result.
Hello, You can try this.
{
List<String> inputTagList = new ArrayList<String>();
inputTagList.add("men");
inputTagList.add("boll");
findByTagListContaining(inputTagList);
}
call your find By Tag List method
List<Media> findByTagListContaining(List<String> inputTagList){
String inputTagString = "[";
for(String strTemp : inputTagList){
//here create you own pattern matching code. Ex:
inputTagString+= "'" + strTemp + "%'" + ",";
}
inputTagString+="%]";
//And your inputTagString is ready to match you element ["mentos","bollywood","comedy"]
}

Parse a plain text into a Java Object

I´m parsing a plain text and trying to convert into an Object.
The text looks like(and i can´t change the format):
"N001";"2014-08-12-07.11.37.352000";" ";"some#email.com ";4847 ;"street";"NAME SURNAME ";26 ;"CALIFORNIA ";21
and The Object to convert:
String index;
String timestamp;
String mail;
Integer zipCode
...
I´ve tried with:
StringTokenizer st1 = new StringTokenizer(N001\";\"2014-08-12-07.11.37.352000\";\" \";\"some#email.com \";4847 ;\"street\";\"NAME SURNAME \";26 ;\"CALIFORNIA \";21);
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken(";").replaceAll("\"",""));
}
And the output is the correct one, i´ve thinking to have a counter and hardcoding with a case bucle and set the field deppending the counter, but the problem is that I have 40 fields...
Some idea?
Thanks a lot!
String line = "N001";"2014-08-12-07.11.37.352000";" ";"some#email.com ";4847 ;"street";"NAME SURNAME ";26 ;"CALIFORNIA ";21
StringTokenizer st1 = new StringTokenizer(line, ";");
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken().replaceAll("\"",""));
}
Or you can use split method and directly get a array of values using the delimiter ;
String []values = line.split(";");
then iterate through the array and get and cast the values they way you want
Regardless of the way you are parsing the file, you somehow need to define the mapping of column-to-field (and how to parse the text).
if this is a CVS file, you could use a library like super-csv. All you need to do is write a mapping definition.
I would first split your input String based on the semi-colon separator, then clean up the values.
For instance:
String input = "\"N001\";\"2014-08-12-07.11.37.352000\";\" " +
"\";\"some#email.com " +
"\";4847 ;\"street\";\"NAME " +
"SURNAME \";26 ;\"CALIFORNIA " +
"\";21 ";
// raw split
String[] split = input.split(";");
System.out.printf("Raw: %n%s%n", Arrays.toString(split));
// cleaning up whitespace and double quotes
ArrayList<String> cleanValues = new ArrayList<String>();
for (String s: split) {
String clean = s.replaceAll("[\\s\"]", "");
if (!clean.isEmpty()) {
cleanValues.add(clean);
}
}
System.out.printf("Clean: %n%s%n", cleanValues);
Output
Raw:
["N001", "2014-08-12-07.11.37.352000", " ", "some#email.com ", 4847 , "street", "NAME SURNAME ", 26 , "CALIFORNIA ", 21 ]
Clean:
[N001, 2014-08-12-07.11.37.352000, some#email.com, 4847, street, NAMESURNAME, 26, CALIFORNIA, 21]
Note
In order to map the values to your variables you will need to know their index in advance, and it will have to be consistent.
Then you can use the get(int i) method to retrieve them from your List - e.g. cleanValues.get(2) will get you the e-mail, etc.
Note (2)
If you do not know the indices in advance or they may vary, then you are in trouble.
You can of course try to get those indices by using regular expressions but I suspect you might end up complicating your life quite a bit.
you can use Java Reflection to automate your process.
Iterate over the fields
Field[] fields = dummyRow.getClass().getFields();
and set your values
SomeClass object = construct.newInstance();
field.set(object , value);

Regex: capture group in list like string

I've searched stacked overflow and the net and I found similar questions but none that gave me a concrete answer. I have a string that acts as a list with the following formatting
Key(Value)/Key(value)/Key(value,value)). I would like to match them by key name IF the key exists, so I don't really want the parenthesis included anywhere.. just the key and the value. I coded something out, but it's a real mess...
so my conditions are:
1)extract key value pairs without parenthesis
2)extract IF they are available...
3)If value portion of list contains two values delimited by a ",", extract individually
textToParse = "TdkRoot(0x0)/Tdk(0x2,0x0)/Tdk(0x0,0x1)/VAL(40A8F0B32240,2x4)/SN(0000:0000:0000:0000:0000:0000:0000:0000/IP(000.1.000.1)/Blue(2x4,2x4)"
String patternText = "^TdkRoot\(( [A-Za-z0-9]) Tdk\(( \\w}+) VAL\(( \\w) SN\(( \\w) IP\ (( \\w) Blue\(( \\w)"
Pattern pattern = Pattern.compile( patternText );
Matcher matcher = pattern.matcher(textToParse);
//Extract the groups from the regex (e.g. elements in braces)
String messageId = matcher.group( 1 );
String submitDate = matcher.group(4);
String statusText = matcher.group( 6 );
I think a cleaner/easier approach would be to extract the elements using patterns for each individual key/value. If so what pattern could I use to tell regex: for "key" grab "value" but leave the parenthesis... if value is delimited by a coma.. return array?? possibly?
Thanks Community!! Hope to hear from you!
PS I know (?<=\()(.*?)(?=\)) will capture anything in the parentheses "(This) value was captured), but how can I modify that to specify a key before the parentheses? "I want to capture whats in THIS(parentheses)" ... key THIS
possibly delimited by a coma
public static void main(String[] args) {
String textToParse = "TdkRoot(0x0)/Tdk(0x2,0x0)/Tdk(0x0,0x1)/VAL(40A8F0B32240,2x4)/SN(0000:0000:0000:0000:0000:0000:0000:0000)/IP(000.1.000.1)/Blue(2x4,2x4)";
Pattern p = Pattern.compile("(\\w+)\\((.*?)\\)");
Matcher m = p.matcher(textToParse);
while (m.find()) {
System.out.println("key :" + m.group(1));
if (m.group(2).contains(",")) {
String[] s = m.group(2).split(",");
System.out.println("values : " + Arrays.toString(s));
} else {
System.out.println("value :" + m.group(2));
}
}
}
o/p:
key :TdkRoot
value :0x0
key :Tdk
values : [0x2, 0x0]
key :Tdk
values : [0x0, 0x1]
key :VAL
values : [40A8F0B32240, 2x4]
key :SN
value :0000:0000:0000:0000:0000:0000:0000:0000
key :IP
value :000.1.000.1
key :Blue
values : [2x4, 2x4]
Not sure if this is what you are looking for (your sample code does not compile) but the following code parses the input text into a map :
String inputText = "TdkRoot(0x0)/Tdk(0x2,0x0)/Tdk(0x0,0x1)/VAL(40A8F0B32240,2x4)/SN(0000:0000:0000:0000:0000:0000:0000:0000)/IP(000.1.000.1)/Blue(2x4,2x4)";
Pattern outerPattern = Pattern.compile("([^/()]+)\\(([^()]+)\\)");
Pattern innerPattern = Pattern.compile("([^,]+)");
Map<String, Collection<String>> parsedData = new HashMap<String, Collection<String>>();
Matcher outerMatcher = outerPattern.matcher(inputText);
while (outerMatcher.find()) {
String key = outerMatcher.group(1);
String val = outerMatcher.group(2);
Collection<String> valueCollection = new ArrayList<String>();
Matcher innerMatcher = innerPattern.matcher(val);
while (innerMatcher.find()) {
valueCollection.add(innerMatcher.group(1));
}
parsedData.put(key, valueCollection);
}
System.out.println(parsedData);
The resulting map (printed on last line) is
{Blue=[2x4, 2x4], VAL=[40A8F0B32240, 2x4], IP=[000.1.000.1], TdkRoot=[0x0], SN=[0000:0000:0000:0000:0000:0000:0000:0000], Tdk=[0x0, 0x1]}

Retrieving a line of text splited in 2 or more Strings

I want to retrieve the info of a line of text from a textfile in 2 different strings...
This is the situation, getting the password line from pwd.txt :
String pwdRetrieved = retreivePwd.getPwd("pwd.txt");
However the password is crypted and it needs 2 valors, the password itself + a "key", like this:
4B5CB9348D5ADB733D43C2FB57A6A971-admin_pwd
admin_pwd is the "key" or "reference" to the encrypted password.
Now what I want to do is get 4B5CB9348D5ADB733D43C2FB57A6A971 into a string and admin_pwd into another string, is that possible?
More specific, i want to read from the .txt until the character "-" is found and store it into a String, then i want it to keep reading after "-" and store it into another string.
Read the whole string, split on the "-" and retrieve the two parts from the created array:
String pwdRetrieved = retreivePwd.getPwd("pwd.txt");
String[] splitPwdRetrieved = pwdRetrieved.split("-");
String password = splitPwdRetrieved[0];
String key = splitPwdRetrieved[1];
You can try this..
String[] pwd = pwdRetrieved.split("-");
After you can split this array value into individual strings.
Using String's split method will do the trick:
String[] split = pwdRetrieved.split("-");
Will return a string array with the two strings you are after
String[] split = pwdRetrieved.split("-");
String enc=split[0];
String pass=split[1];
you could split your String at the - after reading the whole line like this:
String pwdRetrieved = retreivePwd.getPwd("pwd.txt");
String[] split = pwdRetrieved .split("-");
System.out.println(split[0]);
System.out.println(split[1]);
You could do this:
String[] parts = pwdRetrieved.split("-");
String password = parts[0];
String key = parts[1];
Or do this:
int dashPosition = pwdRetrieved.indexOf("-");
String password = pwdRetrieved.substring(0, dashPosition);
String key = pwdRetrieved.substring(dashPosition + 1);

How to replace a word within a square bracket based a certain condition

I've a tricky condition which does not seem to work. For a given string, "Hi [HandleKey], you have [Action]", and a map which contains, map<"HandleKey","Peter"> I want to replace the square bracket and the word within if the key is found in the map. In this case, the map does not contain the key Action. The string should return "Hi Peter, you have [Action]".
Here is the code that I'm working on:
private String messageFormatter(String tMessage, Map<String, String> messageMap)
{
String formattedMsg = null;
Set<String> keyset = messageMap.keySet();
Iterator<String> keySetItr = keyset.iterator();
String msgkey = null;
boolean isFormatted = false;
while (keySetItr.hasNext())
{
msgkey = keySetItr.next();
if(t.contains(msgkey))
{
if(!isFormatted)
{
formattedMsg = tMessage.replaceAll("\\[", "").replaceAll("\\]", "");
formattedMsg = formattedMsg.replaceAll(msgkey, messageMap.get(msgkey));
isFormatted= true;
}else
{
formattedMsg = formattedMsg.replaceAll(msgkey, messageMap.get(msgkey));;
}
}else
{
formattedMsg=tMessage;
}
}
return formattedMsg;
}
The last else part is not right. Can anyone please help me with this. This code works fine for all the cases except when a matching key is not found in the map
is this idea ok for you?
instead of applying regex or extracting the stuff between [..], you could do some trick on your map side. e.g.
String s = "Hi [HandleKey], you have [Action]";
for(String k: yourMap.keySet()){
s=s.replaceAll("\\["+k+"\\]",yourMap.get(k));
}
You can do this with regex, here is a complete example code
public static void main(String[] args) {
String str = "Hi [HandleKey], you have [Action] ";
Hashtable<String, String> table = new Hashtable<String, String>();
table.put("HandleKey", "Peter");
Pattern pattern = Pattern.compile("\\[(\\w+)\\]");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
String key = matcher.group(1);
if (table.containsKey(key)) {
str = str.replaceFirst("\\[" + key + "\\]", table.get(key));
}
}
System.out.println(str);
}
Output:
Hi Peter, you have [Action]
Note that this is more efficient than looping over the Map if the map size is already large or growing.
To handle when key not in map with minimal changes to what you have above try
formattedMsg.replaceAll(msgkey,
(messageMap.containsKey(msgKey) ? messageMap.get(msgkey) : "[" + msgKey + "]"));
but looking again I can see that you're iterating the set of keys from the messageMap so the issue of a key not appearing in the map doesn't arise?
There's also a reference to if(t.contains(msgKey))... but not sure what t is
if you want the text to contain the formatted [msgKey] when its no found then replacing all "[" & "]" seems the wrong way to start if you want to put them back in in some cases.
I'd look at #iTech's suggestion and get regex doing more for you

Categories