Java: Running Linux Commands from your Class


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Terminal {

public Terminal() {
}

public void doCommand(String termCommand) {
try {

Runtime rt = Runtime.getRuntime();

Process pr = rt.exec(termCommand);

BufferedReader input =
new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;

while ((line = input.readLine()) != null) {
System.out.println(line);
}

} catch (Exception e) {

System.out.println(e.toString());
e.printStackTrace();

}
}
}

Read More

Java: Jakarta Apache Commons FileUpload


After headaches, 7 coffee, 1 Cheese Burger and 7 hours of sleep. I finally got Apache Commons FileUpload to work! : )

My working environment: JDeveloper 10g, Tomcat 5.x and Oracle DB 10g, Apache Commons Lib

The working code:

public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

try {

// Parse the request
List items = upload.parseRequest(request);

// Process the uploaded items
Iterator iter = items.iterator();

while (iter.hasNext()) {

FileItem item = (FileItem)iter.next();
if (item.isFormField()) {

String name = item.getFieldName();
String value = item.getString();
if(name.equals(“username”)) {  username= value; }
if(name.equals(“pass”)) {  passwd=value;}
if(name.equals(“email”)) {  email=value;}

} else {

//Process the file upload

// *************************************************
// This is where you would process the uploaded file
// *************************************************
File uploadedFile = null;
String myFullFileName = fileItem.getName(), myFileName =
“”, slashType =
(myFullFileName.lastIndexOf(“\\”) > 0) ? “\\” : “/”;
int startIndex = myFullFileName.lastIndexOf(slashType);
myFileName =
myFullFileName.substring(startIndex + 1, myFullFileName.length());

uploadedFile =
new File(“/home/gulshanbeejan/uploads”,
myFileName);
fileItem.write(uploadedFile);
//fileItem.delete();

}

}

//Do stuff with fields collected here.. like save in a db?

} catch (Exception e) {
System.out.println(e);
}

enctype=”multipart/form-data” will only work that way, you cannot use a multipart/form-data and use request.getParameter(“username”); it will never work.

I hope this helps other souls!

Read More