EmailAddress Validation in Java - apache-commons

I was researching best possible way to check if a String was a valid email Address. I am now fixated on two options, viz., using javax.mail.internet.InternetAddress; or using Apache Commons EmailValidator, which internally uses complicated regex parser.
I was wondering if there is any advantages on picking one over the other in terms of correctness, or is both just fine? I know for a fact that InternetAddress doesn't handle non-ascii characters efficiently in some cases.

You can use an EmailValidator from Apache Commons Validator library for that:
import org.apache.commons.validator.EmailValidator;
...
EmailValidator validator = EmailValidator.getInstance();
if (validator.isValid(email)) {
// is valid, do something
} else {
// is invalid, do something
}
isValid method checks if a field has a valid e-mail address.
This is the best Java email address validation method according to this question
What is the best Java email address validation method?

For something as well-established as email address format, the difference between two approaches is minuscule. Then again, fifty years ago, people never saw the need to use 4 digits for encoding years, so...
The only 'pitfall' with using the regex from Apache Commons, is that its functionality for validating an email address isn't "Java standard". To what extent that affects you as a developer? depends on how paranoid you are.
On the other hand, the standard Java implementation might be less efficient. You'd have to construct an InternetAddress and validate it. Looking at JavaMail's source code, I could see this:
/**
* Check that the address is a valid "mailbox" per RFC822.
* (We also allow simple names.)
*
* XXX - much more to check
* XXX - doesn't handle domain-literals properly (but no one uses them)
*/
(The XXX seems to be some sort of a note, or a "to do" item)

I've just tested it, and apparently the performance on InternetAddress is substantially better then using EmailValidator
package com.avaya.oss.server.errors;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.commons.validator.EmailValidator;
public class TestValidationTypes {
static String email = "test#testy.com";
static int maxItr = 10000;
public static void main(String[] args) throws AddressException {
long start = System.currentTimeMillis();
for (int i = 0; i < maxItr; i++) {
EmailValidator.getInstance().isValid(email);
}
System.out.println("EmailValidator duration: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < maxItr; i++) {
InternetAddress internetAddress = new InternetAddress(email);
internetAddress.validate();
}
System.out.println("InternetAdress duration: " + (System.currentTimeMillis() - start));
}
}
Output:
EmailValidator duration: 1195
InternetAdress duration: 67
The results are that EmailValidator took ~20 times longer:

Related

How to exploit this simple Smart Contract?

I have been trying a lot of ways of exploiting this simple token contract written in Solidity for the Ethereum blockchain; yet, I am unable to successfully do so.
pragma solidity ^0.8.2;
contract SimpleToken{
mapping(address => uint) public balances;
function buyToken() payable public {
balances[msg.sender]+=msg.value / 1 ether;
}
function sendToken(address _recipient, uint _amount) public {
require(balances[msg.sender]!=0); // You must have some tokens.
balances[msg.sender]-=_amount;
balances[_recipient]+=_amount;
}
}
I have been able to achieve such exploitation by sending transactions to the sendToken() function, but I am trying to write a contract that serves as the Exploit code for it.
Here is what I have tried:
pragma solidity ^0.8.2;
import "./vuln.sol";
contract Exploit {
function buyPoisoned() payable public {
SimpleToken t = new SimpleToken();
t.buyToken{gas: 50000, value: 10}();
}
function exploit(address recpt, uint amount) public {
SimpleToken t = new SimpleToken();
t.sendToken{gas: 50000}(recpt, amount);
}
}
I have also tried with prior versions of the Solidity compiler (0.4.2 to be more precise), and yet I was unable to succeed.
I do not know what I am missing to make it work.
Thanks in advance for the help!
Since the contract is compiled with Solidity 0.8, it seems to be currently unexploitable.
Solidity 0.8 introduced automatic exception on integer underflow/overflow, see the docs.
I run the source code through mythril and it didn't find any vulnerabilities either.
If it were compiled with v0.7.6 or older, it would be vulnerable to integer underflow on the line balances[msg.sender]-=_amount;.
For example you have 100 tokens, and you want to send 200:
It would pass the require() check, and subtracted 200 (amount to send) from 100 (the actual balance), which would result in integer underflow:
msg.sender would have 2^256 - 101 tokens (because 0-1 results in 2^256-1 in case of integer underflow)
_recipient would have 200 tokens (the sent amount)

How to convert SqlExpression<T> into SqlExpression<TU> with ServiceStack OrmLite?

I need to work with SqlExpression<T> in a private method but the result should be SqlExpression<TU> (due to my project context).
T and TU aims same structure (TU is a subset of T with some computed expressions)
I didn't find a way to convert SqlExpression<T> into SqlExpression<TU>.
In following code T = Product class and TU = Powder class.
// Sample code
private static SqlExpression<Powder> CreateDefaultExpression(IDbConnection db, IPowderListFilter request)
{
var ev = db.From<Product>()
// Joins are set here...
.Select(p => new
{
CustomRalId = Sql.As(p.CustomRalId, nameof(Powder.CustomRalId)),
Mass = Sql.As(Sql.Sum(p.Width * p.Height / 1000000) * 2 * Settings.LacqueringGramsPerSquareMeter / 1000, nameof(Powder.Mass))
});
// I need to do something like...
ev.ConvertTo<SqlExpression<Powder>>();
// or ...
return new SqlExpression<Powder>(ev);
}
You basically can’t, the typed SqlExpression is a query builder that you can’t just change the Type of and have it automatically erase and reapply all the mutations to the query builder using a different Type.
If reuse is the goal you’d need to use standard C# to DRY as much code as possible which won’t be much since all lambda expressions is typed to a different Type.

explicit POS tagged input provided and getting sentiment stanfordnlp

I am trying the code mentioned in question 11 from the URL.
I want to first give POS tagged input and second get sentiment analysis. First one I able to successfully get done. I able to print the tree and it looks fine. However second one returns me -1 (it should return me 4=very positive).
Please provide inputs/suggestions.
public static String test(){
try{
String grammer="/Users/lenin/jar/stanfordparser-master/stanford-parser/models/englishPCFG.ser.gz";
// set up grammar and options as appropriate
LexicalizedParser lp = LexicalizedParser.loadModel(grammer);
String[] sent3 = { "movie", "was","very", "good","." };
// Parser gets tag of second "can" wrong without help
String[] tag3 = { "PRP", "VBD", "RB", "JJ","." };
List sentence3 = new ArrayList();
for (int i = 0; i < sent3.length; i++) {
sentence3.add(new TaggedWord(sent3[i], tag3[i]));
}
Tree parse = lp.parse(sentence3);
parse.pennPrint();
int sentiment_score = RNNCoreAnnotations.getPredictedClass(parse);
System.out.println("score: "+sentiment_score);
}
catch(Exception e){
e.printStackTrace();
}
return "";
}
You're getting a value of -1 because you haven't run any sentiment analysis. You've only parsed the sentence for grammatical structure.
You can, of course, run the sentiment analyzer via code, but, unfortunately, at the moment there isn't an easy lower-level interface to do so. That would be a good thing to add sometime! You essentially need to duplicate the processing that happens in the class edu.stanford.nlp.pipeline.SentimentAnnotator:
Get a binarized tree from the parser (directly or by binarizing the tree returned)
Collapse unaries
Run the SentimentCostAndGradient class's forwardPropagateTree

Use 'owner' property in Groovy DSL

Let's consider a simple Groovy DSL
execute {
sendNotification owner
sendNotification payee
}
The implementation of execute is
public static void execute(Closure dslCode) {
Closure clonedCode = dslCode.clone()
def dslDelegate = new MyDslDelegate(owner: 'IncCorp', payee: 'TheBoss')
clonedCode.delegate = dslDelegate
clonedCode.call()
}
and custom Delegate is
public static class MyDslDelegate {
def owner
def payee
void sendNotification(to) {
println "Notification sent to $to"
}
}
The expected result of running execute block is
Notification sent to IncCorp
Notification sent to TheBoss
the actual one is
Notification sent to class package.OwnerClassName
Notification sent to TheBoss
The problem is owner is a reserved property in the Groovy Closure itself and no resolveStrategy options help to replace owner value with custom value from delegate due to Groovy getProperty implementation for Closure
public Object getProperty(final String property) {
if ("delegate".equals(property)) {
return getDelegate();
} else if ("owner".equals(property)) {
return getOwner();
...
} else {
switch(resolveStrategy) {
case DELEGATE_FIRST:
...
}
My question is how some one can outcome this limitation and use owner property name in a custom DSL?
This is a bit of a hack, but this should get you what you want, without altering Groovy source:
public static void execute(Closure dslCode) {
Closure clonedCode = dslCode.clone()
def dslDelegate = new MyDslDelegate(owner: 'IncCorp', payee: 'TheBoss')
clonedCode.#owner = dslDelegate.owner
clonedCode.resolveStrategy = Closure.DELEGATE_ONLY
clonedCode.delegate = dslDelegate
clonedCode.call()
}
Ref: Is it possible to change the owner of a closure?
The simple answer is no, you can't. 'owner' is a reserved keyword in Groovy, and therefore by definition cannot be used as an arbitrary symbol. Even if there is a way to hack around this, you're far better off just using a name that doesn't conflict with the implementation of the language- this is especially true in Groovy, which keeps promising to redesign its MOP completely, meaning that any hack you implement may well stop working in future versions.
Perhaps the question would make more sense if you explained why you are willing to offer a bounty and search for a way of hacking around this problem, rather than just changing the name to something different and avoiding the problem entirely. Reserved symbols are a pretty fundamental limitation of a language, and ever attempting to work around them seems very unwise.

MbUnit Icarus self-destructs on this test

I'm trying to test a multi-threaded IO class using MbUnit. My goal is to have the test fixture constructor execute 3 times, once for each row on the class. Then, for each instance, execute the tests multiple times on parallell threads.
However, Icarus blows up with an 'index out of range' on TaskRunner. I can't get the full stack, it spawns message boxes too fast.
What am I doing wrong, or is this a bug in MbUnit/Gallio?
using System;
using System.Collections.Generic;
using System.Text;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using System.IO;
namespace ImageResizer.Plugins.DiskCache.Tests {
[TestFixture]
[Row(0,50,false)]
[Row(0,50,true)]
[Row(8000,100,true)]
public class CustomDiskCacheTest {
public CustomDiskCacheTest(int subfolders, int totalFiles, bool hashModifiedDate) {
char c = System.IO.Path.DirectorySeparatorChar;
string folder = System.IO.Path.GetTempPath().TrimEnd(c) + c + System.IO.Path.GetRandomFileName();
cache = new CustomDiskCache(folder,subfolders,hashModifiedDate);
this.quantity = totalFiles;
for (int i = 0; i < quantity;i++){
cache.GetCachedFile(i.ToString(),"test",delegate(Stream s){
s.WriteByte(32); //Just one space
},defaultDate, 10);
}
}
int quantity;
CustomDiskCache cache = null;
DateTime defaultDate = new DateTime(2011, 1, 1);
[ThreadedRepeat(150)]
[Test(Order=1)]
public void TestAccess() {
CacheResult r =
cache.GetCachedFile(new Random().Next(0, quantity).ToString(), "test",
delegate(Stream s) { Assert.Fail("No files have been modified, this should not execute"); }, defaultDate, 100);
Assert.IsTrue(System.IO.File.Exists(r.PhysicalPath));
Assert.IsTrue(r.Result == CacheQueryResult.Hit);
}
volatile int seed = 0;
[Test (Order=2)]
[ThreadedRepeat(20)]
public void TestUpdate() {
//try to get a unique date time value
DateTime newTime = DateTime.UtcNow.AddDays(seed++);
CacheResult r =
cache.GetCachedFile(new Random().Next(0, quantity).ToString(), "test",
delegate(Stream s) {
s.WriteByte(32); //Just one space
}, newTime, 100);
Assert.AreEqual<DateTime>(newTime, System.IO.File.GetLastWriteTimeUtc(r.PhysicalPath));
Assert.IsTrue(r.Result == CacheQueryResult.Miss);
}
[Test(Order=3)]
public void TestClear() {
System.IO.Directory.Delete(cache.PhysicalCachePath, true);
}
}
}
I wont answer direct question about bug but I think following steps will help find the error and not get lost in popping message boxes
decrease numbers of totalfiles ,
subfolders to much lower values to
see if error persists in 2 or even 1
file counts
your tests code isn't
super easy, as it should be,
write tests for tests
so you know they are running
correct, maybe those random nexts
are the problem, maybe something
else, tests should be easy.
figure out what test breaks the
system, your code contains 3 tests,
and constructor, comment two other
tests and see which one produces
error
your threaded repeat 150
looks pretty sick, maybe try smaller
number like 2 or 3 if error is basic
even 2 threads might break, if you
run 150 threads I can understand
your trouble with message boxes
add logging and try catch - catch
that index exception and log your
class state carefully, after
inspecting it I think youll see
problem much more clearly.
Right now you cant figure out the problem I think, you got too many variables , not to mention you didnt provide code for your Cache class which might contain some simple error that is causing it, before MBunit features even begin to show up.

Resources