Tag Archive: Java


Sample Maven File For Eclipse

When creating a maven project in Eclipse, the archetypes use ridiculously outdated default parameters, such as Java 1.5 or Dynamic Web Module 2.3.

When using the webapp archetype, a few of the default settings can be corrected, using the following 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>de.test</groupId>
    <artifactId>MyService</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>MyService Maven Webapp</name>
    <url>http://maven.apache.org</url>
  
    <dependencies>
        <!-- JUnit Files -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>MyService</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Next replace your web.xml with the following web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:web="http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee">

</web-app>

Next switch to the Navigator View, open org.eclipse.wst.common.project.facet.core.xml from your .settings folder and replace

<installed facet="jst.web" version="2.3"/>

with

<installed facet="jst.web" version="3.1"/>

Now right click your project and click on Maven -> Update Project.

Go to your Navigator again and

  • create the folder java under src/main
  • create the folder java under src/test

This should fix most of the problems and enable you to use Maven in Eclipse.

Read file completely in Java 8

In Java 8, there’s a short hand method to read a file in one step from disk:

byte[] b = Files.readAllBytes(Paths.get("test.txt"));

The newer Java 7 releases (e.g. Java 7 Update 51) restricts the permission to listen on arbitrary ports. Formerly, Java allowed to listen to all ports greater than 1023

// allows anyone to listen on un-privileged ports
permission java.net.SocketPermission "localhost:1024-", "listen";

The newest Java only allows listening on „port 0“ and port 1099.

If you want to use Apache Derby DB (which is written in Java) on its standard port 1527, for example, you have to configure Java’s security manager. You can do that by adding the following line to JAVA_HOME/lib/security/java.policy

permission java.net.SocketPermission "localhost:1527", "listen";

Upload file with Servlet 3.0

<html>
<body>
    <form action="UploadServlet" method="post" enctype="multipart/form-data">
        Select File <input type="file" name="photo"><br/> 
        <input type="submit" value="Submit">
    </form>
</body>
</html>
@WebServlet("/UploadServlet")
@MultipartConfig(location = "C:/Temp")
public class UploadServlet extends HttpServlet
{
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    Part file = request.getPart("photo");
    file.write(UUID.randomUUID() + ".jpg");
    response.getWriter().append("Upload successful");
  }
}
 yum install java 

To export your JDK (i.e. set your environment variable) for applications like Tomcat:

export JAVA_HOME=/usr/lib/jvm/jre-1.6.0-openjdk.x86_64/ 

To start Tomcat you need to make the sh-scripts executable, e.g. execute in your tomcat/bin directory

 chmod 774 *.sh 

Pretty print XML in Java

File file = new File("./");
for (String filename : file.list()) {
	if (!(new File(filename).isDirectory()))
	{
	  try {
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
		StreamResult result = new StreamResult(new StringWriter());
		DOMSource source = new DOMSource(parseXmlFile(INPUT_XML_STRING);
		transformer.transform(source, result);
		String xmlString = result.getWriter().toString();
		System.out.println(xmlString);
		FileOutputStream fos = new FileOutputStream("dest/" + filename);
		BufferedWriter bos = new BufferedWriter(new OutputStreamWriter(fos));
		bos.write(xmlString);
		bos.close();
	  } catch (Exception e) {
		e.printStackTrace();
	  }
	}
}

private static Document parseXmlFile(String input) {
	try {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		InputSource is = new InputSource(new StringReader(input));
		return db.parse(is);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
FileInputStream fis = new FileInputStream("file.xml");
byte[] b = new byte[4096];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (fis.available() > 0) {
  int n = fis.read(b);
  if (n == -1)
  break;
  baos.write(b, 0, n);
}
System.out.println(baos.toString());