Java validation of a URL through Regular Expression - java

Java validation of a URL through Regular Expression
String url = "https://my-company-08.vv.xyz.com/abc.svc/Abcdef(id='{0}',text='ABC.XYZ')?$query=xxxx&$format=xml";

URLs are potentially complex beasts with many possible variants. If you write your own regex parser you will most likely fail to cover all cases. Use the built in URI or URL class to do it for you...
private static boolean isValidUri(String candidate) {
try {
new URI(candidate);
return true;
} catch (URISyntaxException e) {
e.printStackTrace();
return false;
}
}
With URL
private static boolean isValidUrl(String candidate) {
try {
new URL(candidate);
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
}
}
Your specific syntax errors....
// returns false, error at character 51 which is the first (
System.out.println(isValidUri("https://my-company-08.vv.xyz.com/abc.svc/Abcdef(id= '{sd54asds2f21sddf}',text='ABC.XYZ')?$query=myClient&$format=xml"));
// returns true without the (id= '{sd54asds2f21sddf}',text='ABC.XYZ') stuff
System.out.println(isValidUri("https://my-company-08.vv.xyz.com/abc.svc/Abcdef?$query=myClient&$format=xml"));

Related

Do you need a return type method to be handled in front end?

So I am trying to get more insight on Java methods as I am still new to all this. And in my method type I declared as below:
public int insert_url(long nodeid,String url,String startdt,String enddt,int enable) {
try {
// UrlLink attr = em.find(UrlLink.class,n);
String sql="INSERT INTO urllink(NODEID,URL,STARTDT,ENDDT,ENABLE) VALUES("+nodeid+",'"+url+"','"+startdt+"','"+enddt+"',"+enable+")";
em.createNativeQuery(sql).executeUpdate();
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
And in my front end, I called it simply like below:
try {
fileFacade.insert_url(nd.getNodeid(), "f0=" + nd.getNodeid() + "&ts=" + hash, currentDate, defaultDate, 1);
} catch (Exception e) {
// error should be handled
}
Initially, I was using void method rather than int. My question is if I am not using a return method,can it be handled in the front end?
In the even that the end user encounters any error, they ought to know an error occurred.

how to use Properties for user login with several user accounts on java

I have this:
propiedades = new Properties();
try {
entrada = new FileInputStream("config.properties");
propiedades.load(entrada);
Set set =propiedades.stringPropertyNames();
System.out.println(set);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (entrada != null) {
try {
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
So basiclly whats inside "config.properties" is the following thing:
admin=admin
user=userpass
user1:userpas1
Next up,i have this code:
public boolean revisarCredenciales(String userName,String password)
{
Enumeration<?> e = propiedades.propertyNames();
while(e.hasMoreElements())
{
for (; e.hasMoreElements();) {
System.out.println(e.nextElement());
if (e.nextElement().equals(userName) && propiedades.getProperty(userName).equals(password))
{
return true;
}
}
}
return false;
}
In this block I tried to do a simple if where if the e.nextElement() equals userName (userName is just a txUserBox.getText()) and propiedades.getProperty(userName).equals(password(txPassword.getPassword()) then it returns a value, can be either false or true, and the method where it is called will access the program if true.
The problem comes where it always is returns true and with this, doesn't matter what I put on the textboxes it will log me on..
To quick answer in case somebody has an error like this i fixed this by just doing:
public boolean revisarCredenciales(String userName,String password,Set<String> setNombres)
{
for (String key:setNombres)
{
String pass=propiedades.getProperty(key);
if( userName.equals(key) && pass.equals(password)){
return true;
}
}
return false;
}
On the method to review credentials, because it was getting the setNombres from this:
propiedades = new Properties();
try {
entrada = new FileInputStream("config.properties");
propiedades.load(entrada);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (entrada != null) {
try {
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
setNombres=propiedades.stringPropertyNames();
So, when it reviews the credentials it receives first the username from the JTextField, the password and the set of strings. When u send the JPassword field do new String(txPassword.getPassword()). If you dont do it and send just txPassword.getPassword() it will send the password encripted and cant match then.
public boolean revisarCredenciales(String userName,String password,Set<String> setNombres)
{
for (key:setNombre(Position))
{
pass(the one written on the textbox)= propiedades.getProperty(key);
//Here it obtaions the value in properties, next to key
if( userName.equals(key) && pass.equals(password)){
//UserName is what is in the textbox /pass defined on top.equals(What is on the textbox)
return true;
//if that happens returns true, this proccess repeats for each line of the config.properties
}
}
return false;
}

enable or diable link based on condition in wicket framework

I have one requirement in WICKET framework.
I would like to enable and disable link based on if else condition. Anybody can give suggestion to how to archive it?
Here is the sample code:
Link<OrderAssetAncillaryListEntry> getDesc = new Link<OrderAssetAncillaryListEntry>(
"descLink", new Model(oale)) {
#Override
public void onClick() {
final OrderAssetAncillaryListEntry oale = this.getModelObject();
String[] scrids = {oale.getScrid()};
try {
byte[] content = getReportBytes(scrids);
IResourceStream resourceStream = new ByteArrayResourceStream(
content, "application/vnd.ms-excel");
getRequestCycle().setRequestTarget(
new ResourceStreamRequestTarget(resourceStream) {
#Override
public String getFileName() {
return oale.getShowCode() + "_desc.xls";
}
});
} catch (Exception e) {
LOGGER.error("Unable to fetch Description Report file", e);
}
}
};
// add label
getDesc.add(new Label("descLinkLabel", "Description"));
return getDesc;
#isEnabled () is called many times per request. It is better to override #onConfigure () and use setEnabled () in it.
I suggest that you override Link#isEnabled() and evaluate your condition there.
You have different options to do so:
//Business logic turning someCondition true or false
final boolean someCondition = verifyBusiness();
Link<String> testLink = new Link<String>("test", Model.of("someProperty")){
#Override
public boolean isEnabled() {//Option 1
if (someCondition){
return true;
} else {
return false;
}
}
#Override
public void onClick() {
//business logic
}
};
//OR use something as below
testLink.setEnabled(someCondition ? true : false);//Option 2
private boolean verifyBusiness(){
return true; //Whatever you want to return based upon your logic
}

Validating absence of an element

I have a test case:
Assert.assertTrue(test .verifyNoDrillDisplayForCourses());
and a boolean method verifyNoDrillDisplayForCourses which verifies element("xyz") is not displayed,
try{
if(element("xyz"). isDisplayed())
return false;
else return true;
}
catch (Exception e)
{
return false;
}
}
But the assertion fails as java .lang .AssertionError:expected [true] but found [false]. I am unable to figure out why?
The isDisplayed() method will throw an StaleElementReferenceException, if the given element is not in the DOM anymore. So you have to change the catch statement to return true;.
If you're testing for the presence of an element, if it's not found an exception will be thrown. So if you find it you're returning false, if you can't find it you're also returning false.
When testing for non-presence of an element you should have the catch block return true!
try{
if(element("xyz").isDisplayed()) {
return false;
} else return true;
}
catch (Exception e)
{
return false;
}
}
I believe your if statement is missing correct formatting from what you copied over.
I've amended it above, but in case try it like this:
if(element("xyz").isDisplayed()) {
return false;
} else return true;
Following code helped:
public boolean verifyNoelement()
{
try
{
if(element("element").isDisplayed())
{
return false;
}
return false;
}
catch(Exception e)
{
logMessage("No element displayed");
return true;
}
}

How to Validate JSON with Jackson JSON

I am trying to use Jackson JSON take a string and determine if it is valid JSON. Can anyone suggest a code sample to use (Java)?
Not sure what your use case for this is, but this should do it:
public boolean isValidJSON(final String json) {
boolean valid = false;
try {
final JsonParser parser = new ObjectMapper().getJsonFactory()
.createJsonParser(json);
while (parser.nextToken() != null) {
}
valid = true;
} catch (JsonParseException jpe) {
jpe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return valid;
}
Although Perception's answer probably will fit many needs, there are some problems it won't catch, one of them is duplicate keys, consider the following example:
String json = "{ \"foo\" : \"bar\", \"foo\" : \"baz\" }";
As a complement, you can check for duplicate keys with the following code:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
objectMapper.readTree(json);
It throws JsonProcessingException on duplicate key or other error.
With Jackson I use this function:
public static boolean isValidJSON(final String json) throws IOException {
boolean valid = true;
try{
objectMapper.readTree(json);
} catch(JsonProcessingException e){
valid = false;
}
return valid;
}
I would recommend using Bean Validation API separately: that is, first bind data to a POJO, then validate POJO. Data format level Schemas are in my opinion not very useful: one usually still has to validate higher level concerns, and schema languages themselves are clumsy, esp. ones that use format being validated (XML Schema and JSON Schema both have this basic flaw).
Doing this makes code more modular, reusable, and separates concerns (serialization, data validation).
But I would actually go one step further, and suggest you have a look at DropWizard -- it integrates Jackson and Validation API implementation (from Hibernate project).
private boolean isValidJson(String json) {
try {
objectMapper.readTree(json);
} catch (JsonProcessingException e) {
return false;
}
return true;
}
Another option would be using java.util.Optional in Java 8. This allows to return an object and to use in the calling code a more functional approach.
This is another possible implementation:
public Optional<JsonProcessingException> validateJson(final String json) {
try{
objectMapper.readTree(json);
return Optional.empty();
} catch(JsonProcessingException e){
return Optional.of(e);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
Then you can use this method like this:
jsonHelper.validateJson(mappingData.getMetadataJson())
.map(e -> String.format("Error: %s at %s", e.getMessage(), e.getLocation().toString()))
.orElse("Valid JSON");
Inproving the other answers
public static boolean isValidJSON(final String json) throws IOException {
boolean valid = true;
try{
mapper.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
objectMapper.readTree(json);
} catch(JsonProcessingException e){
valid = false;
}
return valid;
}

Categories