[java] check password against DB

To check the password against the database encoded value is simple, but it is not supported out of the box. You’ll have to convert the generated hash into hex format

		byte[] encoded = md.digest();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < encoded.length; i++) {
			sb.append(Integer.toString((encoded[i] & 0xff) + 0x100, 16).substring(1));
		}

Here’s a complete example:

public boolean validate(String username, String password) {
		final Query query = em.createQuery("SELECT u FROM User u WHERE u.username = :username");
		query.setParameter("username", username);

		List<User> foundUsers = (List<User>) query.getResultList();
		if (foundUsers == null || foundUsers.isEmpty()) {
			return false;
		}
		User foundUser = foundUsers.get(0);
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		md.update(password.getBytes());
		byte[] encoded = md.digest();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < encoded.length; i++) {
			sb.append(Integer.toString((encoded[i] & 0xff) + 0x100, 16).substring(1));
		}

		if (sb.toString().equals(foundUser.getPassword())) {
			return true;
		}

		return false;
	}

Advertisements

Simple DOM example Java

1. The DOM parser example:

package com.vvirlan;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DomExample {
	public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
		DomExample ex = new DomExample();
		ex.run();
	}

	public void run() throws SAXException, IOException, ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		// factory.setValidating(true);
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(new File("C:\\tmp\\myxml.xml"));
		NodeList nodeList = doc.getElementsByTagName("name");
		Node firstNode = nodeList.item(0);
		System.out.println(firstNode.getNodeName() + " = " + firstNode.getTextContent());
	}
}

2. The XML file

<?xml version="1.0" encoding="UTF-8"?>
<records>
	<record>
		<name>Queen I</name>
		<year>1988</year>
		<artist>Queen</artist>
	</record>
		<record>
		<name>Reloaded</name>
		<year>1992</year>
		<artist>Metallica</artist>
	</record>
</records>

Simple SAX example in Java

1. SaxExample class

package com.vvirlan;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class SaxExample {

	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		SaxExample ex = new SaxExample();
		ex.run();
	}

	public void run() throws ParserConfigurationException, SAXException, IOException {

		SAXParserFactory factory = SAXParserFactory.newInstance();
		factory.setNamespaceAware(true);
		SAXParser parser = factory.newSAXParser();
		XMLReader xmlReader = parser.getXMLReader();
		xmlReader.setContentHandler(new MyContentHandler());

		FileInputStream fis = new FileInputStream(new File("C:\\tmp\\myxml.xml"));
		InputSource source = new InputSource(fis);
		xmlReader.parse(source);
	}
}

2. MyHandler

package com.vvirlan;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

public class MyContentHandler implements ContentHandler {

	@Override
	public void setDocumentLocator(Locator locator) {
		// TODO Auto-generated method stub

	}

	@Override
	public void startDocument() throws SAXException {
		System.out.println("Documemt Started");

	}

	@Override
	public void endDocument() throws SAXException {
		System.out.println("Documemt Ended");

	}

	@Override
	public void startPrefixMapping(String prefix, String uri) throws SAXException {
		// TODO Auto-generated method stub

	}

	@Override
	public void endPrefixMapping(String prefix) throws SAXException {
		// TODO Auto-generated method stub

	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
		System.out.println("element Started "+localName);

	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		System.out.println("element ended "+localName);

	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("Characters: "+new String(ch).substring(start, start+length));

	}

	@Override
	public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
		// TODO Auto-generated method stub

	}

	@Override
	public void processingInstruction(String target, String data) throws SAXException {
		// TODO Auto-generated method stub

	}

	@Override
	public void skippedEntity(String name) throws SAXException {
		// TODO Auto-generated method stub

	}

}

3. The source XML file

<?xml version="1.0" encoding="UTF-8"?>
<records>
	<record>
		<name>Queen I</name>
		<year>1988</year>
		<artist>Queen</artist>
	</record>
		<record>
		<name>Reloaded</name>
		<year>1992</year>
		<artist>Metallica</artist>
	</record>
</records>

[SOLVED] Spring Java include interface implementation after compilation

So you need to be able to provide an interface in your main project and then allow users to implement this interface when they want and to be able to feed the implementation to your main project.

1. Build your implementation with maven
2. Take the resulting jar from target and copy it into your impl folder under your main project target folder
3. Start your project with:

java -classpath "demo-0.0.1-SNAPSHOT.jar;imp\*" demo.Application

[STARTER] JAX-RS: Jersey + Servlet 3.0 + Maven + Tomcat

Steps to configure a JAX-RS project that runs on Tomcat (here 8), Maven, Servlet 3.0 and having Jersey as a Reference Implementation.

1. Maven POM.XML dependencies:


	<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.10.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-common</artifactId>
            <version>2.10.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.10.1</version>
        </dependency>

 

2. web.xml (src/main/webapp/WEB-INF)


<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</web-app>

 

3. Application class (under: src/main/java/com/vvirlan/java/ws

package com.vvirlan.java.ws;

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

import com.vvirlan.java.ws.resources.Hello;

@ApplicationPath("/rest")
public class MyApplication extends Application {

	@Override
	public Set<Class<?>> getClasses() {
		final Set<Class<?>> returnValue = new HashSet<Class<?>>();
		returnValue.add(Hello.class);
		return returnValue;
	}
}

4. Resource class (which is the actual web service endpoint):

package com.vvirlan.java.ws.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;

@Path("hello")
public class Hello {

	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public String getIt() {
		return "Got it!";
	}

        @GET
	@Path("user/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public User getMe(@PathParam("id") String id) {
		User toReturn = new User();
		toReturn.setName(id);
		toReturn.setEmail("Email");
		return toReturn;
	}

}

5. Build the app as usually and deploy to tomcat webapp folder
6. Point the browser:
http://localhost:8080/demo2/rest/hello

Notes:
A. Folder layout:

screen

B. Complete pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.vvirlan.java.ws</groupId>
	<artifactId>demo2</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo2 Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-server</artifactId>
			<version>2.10.1</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-common</artifactId>
			<version>2.10.1</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>2.10.1</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>demo2</finalName>
	</build>
</project>

Jexcel API character problems [solved]

When you have problems with characters like � when reading excel files using JExcel API, then probably the problem is that the encodings are different. JExcel tries to read in UTF-8, but excel stores in CP1525 or something. Here is the solution:
WorkbookSettings ws = new WorkbookSettings();
ws
.setEncoding("Cp1252");
Workbook workbook = Workbook.getWorkbook(stream, ws);