How to get simply email address after MimeUtility.decodeText()? - java

How can I simply get the email address after use MimeUtility.decodeText() from javax.mail.internet ?
After that operation I have following String:
Foo Bar <foo.bar#abc.en>
I can do that by methods from String class but I'm interested in existed predefinied method for this ?

It's very easy to define your method. To get the String you only need one line of code:
String email = stringToDecode.split("<")[1].substring(0, stringToDecode.split("<")[1].length() - 1);

Just call new InternetAddress(addr).getAddress(). In fact, you don't even need to call MimeUtility.decodeText() first.

Related

Asserting UUID in junit

I have a method which builds an object and returns it.
The object as UUID as one of its fields. While building the object, random UUID is generated. Here is the code:
public MetaData getMetaData(String id) {
return MetaData.newBuilder().setId(id)
.setCorrelationId(UUID.randomUUID().toString())
.setCreatedAt(now(UTC).format(ISO_ZONED_DATE_TIME))
.build();
}
Here is my test:
#Test
public void shouldVerifyIfTheMetaDataIsBuild() {
MetaData metaData = handler.getMetaData("1234");
assertThat(metaData.getId(), is("1234"));
assertThat(metaData.getCorrelationId(), isNotNull());
}
I'm just verifying if the correlationId is not null or not. Is there a better way to verify the UUID?
The only way to verify the current production code is to, yes, check that CorrelationId is not null. You could also check that the layout of the expected string matches a valid UUID string.
Of course, when you want to a bit of better checking, then you simply have to replace UUID.randomUUID().toString() with something that you can control.
For example you could create a UUIDGenerator interface, with a default method that creates a random UUID, as shown in your code. But in your test setup, you instead provide an implementation of that interface that returns a specific UUID.
Then your test code could know which UUID should be used, and assertThat(actualUuid, is(expectedUuid)).
I would change this line:
assertThat(metaData.getCorrelationId().toString(), isNotNull());
to the following:
assertThat(metaData.getCorrelationId(), isNotNull());
otherwise you would get a NullPointerException if metaData.getCorrelationId() returns null instead of an assertion failure.
Additionally, you could test if metaData.getCorrelationId() returns a string that represents a valid UUID, by trying to parse it:
try {
UUID.fromString(metaData.getCorrelationID());
} catch (IllegalArgumentException e) {
fail("Correlation ID is not a valid UUID: " + metaData.getCorrelationId());
}
When using a UUID, I check the String pattern using a regex.
assertTrue(id.matches(Pattern("([a-f0-9]{8}(-[a-f0-9]{4}){4}[a-f0-9]{8})")))
This way I check if it is present and if the String is indeed a UUID as I had it happen that an unintended change put a space there which would pass in the assertNotNull solutions.
One more thing you can validate about UUID is it's length (as it is always 36 java.util.UUID.randomUUID().toString() length).
There will be a chance for detecting changes in implementation in future.
I added a UUID validator to Apache Commons Validator. It's not yet been merged, but you can vote for it here: https://github.com/apache/commons-validator/pull/68
As rightly said by #GhostCat, since we don't have control over UUID.randomUUID(), the only way would be to check if the UUID generated is not null. For that, you may use the code below:
assertNotNull(metaData.getCorrelationId());

How can I get value after hashtag from URL in Java

I have a URL and I want to print in my graphical user interface the ID value after the hashtag.
For example, we have www.site.com/index.php#hello and I want to print hello value on a label in my GUI.
How can I do this using Java in Netbeans?
Simple solution is getRef() in URL class:
URL url = new URL("http://www.anyhost.com/index.php#hello");
jLabel.setText(url.getRef());
EDIT: According to #Henry comment:
I would recommend to use the java.net.URI as it also deals with encoding. The Javadocs say: "Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL()."
and this comment:
Why not just doing uri.getFragment()
URI uri = new URI("http://www.anyhost.com/index.php#hello");
jLabel.setText(uri.getFragment());
Use the String.split() Method.
public static String getId(string url) {
return url.split("#")[1];
}
String.split() returns an array of Strings that are delimited, or "Split," by the value you pass to it, or in this case #.
Because you want only the string after the #, you can just use the second item in the array that it returns by adding [1] to the end of it.
For more on String.split() go to Tutorials Point.
By the way, the part of the URL you are referencing is the Element ID. It is used to jump to an Element on a webpage.

Calling JavaScript function in Java

I'm trying to send an email using a javascript code in a Java project. Database connection works fine, I already tested it. I got the error:
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: missing ) after formal parameters (#1) in at line number 1
The only information of relevance is not readily reported: the final JavaScript string executed. Make sure to look at relevant data when debugging. After inspecting the final string it will be apparent why it is incorrect and trivial to "fix".
Hint: it will look something like function sendMail(userblah, foo#bar.qux) { .., which is indeed invalid JavaScript.
The problem and solution should be self-evident from that - use fixed parameters (variable names) in the function declaration and supply arguments (values) via the invokeFunction call.
Solution:
// The following parameter names are JAVASCRIPT variable names.
String script = "function sendMail(username, email, body) { ..";
// And pass correct arguments (values), in order. The variables used
// here are JAVA variables, and align by-position with the JS parameters.
inv.invokeFunction("sendMail", username, email, "EMAIL SENT!!!!");
In addition, the getElementById (invalid ID) is wrong, the body parameter is never used, and encodeURIComponent should be used (instead of escape).
Not sure if this is a typo or not:
result = request.executeQuery("SELECT user.login, user.email "
+ "FROM user " + );
It looks like you are missing the end of your statement.
Hmmmm, your function definition:
function sendMail("username","email") {...}
doesn't look like valid JavaScript to me, apart of that, you never call the function.
Pseudocode, how to do it:
function sendMail(username, email) {
var link = "jadajada" + email; // .... etc
}
sendMail("+username+","+email+");

How to get value from HSSFComments in apache POI

I want to read/extract the value from HSSFComment.
I can access the HSSFComment by the following code:
HSSFComment comment = workSheet.getCellComment(1, 0);
But, how can I get the text/value from that "comment" instance?
there are tow methods in HSSFComment:
getTextObjectRecord()
getNoteRecord()
But both are protected methods...that's why I can't access those from my class. in other word, these methods are not visible from my class. Following line of code doesn't compile.
TextObjectRecord txo = comment.getTextObjectRecord();
Any comments?
Use getString() inherited from HSSFTextBox. This returns an HSSFRichTextString, which itself has a getString() method to get the plain text. In otherwords
String comment = cell.getComment().getString().getString();
Which you can't do like that due to the possibility of null returns, but that's the idea.

getting only name of the class Class.getName()

How can i get the name of the class
String.class.getName() returns java.lang.String
I am only interested in getting last part ie only String
Any Api can do that?
Class.getSimpleName()
The below both ways works fine.
System.out.println("The Class Name is: " + this.getClass().getName());
System.out.println("The simple Class Name is: " + this.getClass().getSimpleName());
Output as below:
The Class Name is: package.Student
The simple Class Name is: Student
or programmaticaly
String s = String.class.getName();
s = s.substring(s.lastIndexOf('.') + 1);
You can use following simple technique for print log with class name.
private String TAG = MainActivity.class.getSimpleName();
Suppose we have to check coming variable value in method then we can use log like bellow :
private void printVariable(){
Log.e(TAG, "printVariable: ");
}
Importance of this line is that, we can check method name along with class name. To write this type of log.
write :- loge and Enter.
will print on console
E/MainActivity: printVariable:
Social.class.getSimpleName()
getSimpleName() :
Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.
The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".
Here is the Groovy way of accessing object properties:
this.class.simpleName # returns the simple name of the current class
Get simple name instead of path.
String onlyClassName = this.getLocalClassName();
call above method in onCreate

Categories

Resources