Redirecting All Web Requests to the WWW. DNS Entry for Your Web Site

If you would like to redirect all non ‘www’ requests for pages on your site to the ‘www’ dns entry add the following to your .htaccess file in the document root of your site:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Enabling Parsing and Processing of PHP code in Files With .html Extensions for GoDaddy.com Hosting Accounts

There are times when a web master will want to have the default file extension for a given website stay consistent regardless of how the files are preprocessed on the server-side or what server-side scripting language is being used.

To set up your GoDaddy.com 4GH, Linux hosted account to parse PHP code in .html files, do the following:

  1. Log in to your account.
  2. Go to the control panel for the web site in question.
  3. In the control panel click on the ‘Settings’ sub-section.
  4. Click on the ‘File Extensions Management’ icon/link.
  5. Click on the ‘Custom Extensions’ link in the left-hand column.
  6. Click on ‘New Extension’ in the upper right of the page.
  7. Enter ‘.html’ for the extension, and select ‘PHP 5.x.x’ from the drop-down.
  8. Click ‘OK’

Once you click the ‘OK’ button you can now add PHP code to your .html files.

Cloned VMware CentOS6 Server and "device eth0 does not seem to be present, delaying initialization" Error

Recently, I cloned a vmware install of CentOS6 and after firing up the clone and trying to start networking received the error: “device eth0 does not seem to be present, delaying initialization”

It turns out that the NIC on the cloned machine was being renamed and registered to eth1.

To list the current ethn devices:

# ls /sys/class/net
eth1 lo

There is a device manager, udev, which stores the settings from the NIC of the vm prior to the cloning process.  When you clone a vm it also changes the mac address of the NIC and as a result the vm sees it as a new NIC and assigns it to /dev/eth1.

As a result, we now have to edit the udev config file as well as the ifcfg-eth0 file to get the newly update virtual NIC card to operate on the eth0 device.

First, edit: /etc/udev/rules.d/70-persistent-net.rules

# This file was automatically generated by the /lib/udev/write_net_rules
# program, run by the persistent-net-generator.rules rules file.
#
# You can modify it, as long as you keep each rule on a single
# line, and change only the value of the NAME= key.

# PCI device 0x15ad:0x07b0 (vmxnet3) (custom name provided by external tool)
SUBSYSTEM==”net”, ACTION==”add”, DRIVERS==”?*”, ATTR{address}==”00:50:56:bc:00:45″, ATTR{type}==”1″, KERNEL==”eth*”, NAME=”eth0″

# PCI device 0x15ad:0x07b0 (vmxnet3)
SUBSYSTEM==”net”, ACTION==”add”, DRIVERS==”?*”, ATTR{address}==”00:50:56:bc:00:46″, ATTR{type}==”1″, KERNEL==”eth*”, NAME=”eth1″

Delete the first SUBSYSTEM entry in the file.

Update the ‘eth1’ attribute in the remaining entry to ‘eth0’

Edit /etc/sysconfig/network-scripts/ifcfg-eth0

. Change the HWADDR to match the new mac address listed in the newly edited 70-persistent-net.rules file.

reboot.

Java: How To Use RandomAccessFile and FileChannel to Write to a Specific Location in a File

If there is ever a need to write bytes to a specific location to an existing file, here is an example of how to use the RandomAccessFile and FileChannel Java classes to do so:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Will write bytes to the beginning of an existing file.
 *
 * @author Ryan Chapin
 */
public class RandomAccessFileTest {

    public static void main(String[] args) {

        // Generate input string and the ByteBuffer for it
        String stringToInsert = “This is a string to insert into a file.”;
        byte[] answerByteArray = stringToInsert.getBytes();
        ByteBuffer byteBuffer = ByteBuffer.wrap(answerByteArray);

        File fileToModify = new File(“/path/to/file”);

        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(fileToModify, “rw”);
        } catch (FileNotFoundException e1) {
            // TODO error handling and logging
        }

        FileChannel outputFileChannel = randomAccessFile.getChannel();

        // Move to the beginning of the file and write out the contents
        // of the byteBuffer.
        try {
            outputFileChannel.position(0);

            while(byteBuffer.hasRemaining()) {
                outputFileChannel.write(byteBuffer);
            }
        } catch (IOException e) {
            // TODO error handling and logging
        }

        try {
            outputFileChannel.close();
        } catch (IOException e) {
            // TODO error handling and logging
        }

        try {
            randomAccessFile.close();
        } catch (IOException e) {
            // TODO error handling and logging
        }
    }
}

Using a ProcessBuilder to Execute an OS Level Command and Properly Read the Exit Code from a Java Process

There are many a situation where a developer will want to execute an OS level command in another process and read not only the standard out (stdout), and standard error (sterr), but also the exit code returned from the process.

To do so, utilize the ProcessBuilder class along with a helper class (ProcessWrapper) that will provide the ability to set a timeout for the process and read the exit code in a separate thread.

Following is an example and the ProcessWrapper class with an explaination:

import java.io.IOException;

public class ProcessBuilderTest {

    /**
     * Time in milliseconds that we will wait for the process to complete before
     * timing out and killing it.
     */
    private static final long fTimeout = 10000;

    public static void main(String[] args) {

        String[] commandArray = { “some”, “command” };

        ProcessBuilder processBuilder = new ProcessBuilder(commandArray);

        Process process = null;
        try {
            process = processBuilder.start();
        } catch (IOException e) {
            // TODO: Error handling, logging
        }

        // ——————————————————————–
        // Read the exit code from the fProcess
        ProcessWrapper processWrapper = new ProcessWrapper(process);
        processWrapper.start();

        int exitCode = 0;
        try {
            processWrapper.join(fTimeout);

            // Check for an exit code from the process
            if (processWrapper.getfExitCode() != null) {
                exitCode = processWrapper.getfExitCode();
            } else {
                // Set our exit code to 1
                exitCode = 1;
                process.destroy();
            }
        } catch (InterruptedException e) {
            processWrapper.interrupt();
            Thread.currentThread().interrupt();
            process.destroy();
        }

        System.out.print(“exitCode = ” + exitCode);
    }

    public static class ProcessWrapper extends Thread {

        private final Process fProcess;

        private Integer fExitCode;

        public Integer getfExitCode() {
            return fExitCode;
        }

        public ProcessWrapper(Process fProcess) {
            this.fProcess = fProcess;
        }

        public void run() {
            try {
                fExitCode = fProcess.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

In the ProcessBuilderTest main() method the command to be executed is build in the commandArray String[].

A ProcessBuilder instance is created and passed the command to execute. Then a Process instance providing a reference to the process running on the OS is instantiated via the ProcessBuilder.start() command.

Here is where the wrapper class that helps us to read the exit code comes in. A ProcessWrapper is instantiated and passed a reference to the process on construction, and then the thread started with the .start() invocation.

Then processWrapper.join(fTimeout) is invoked telling the current thread to wait for the completion of the processWrapper thread, or interrupt it (timeout) after the value of fTimeout (in this case 10 seconds).

If the processWrapper thread completes before the timeout the main thread invokes processWrapper.getfExitCode(), to acquire the exit code from the process. If not, the process is killed and we pass an exitCode of 1 to indicate abnormal completion.

Attached is a .zip of the java classes for reference and testing.

Dynamically Instantiating Classes in Java

Edited 2021-02-08 to reflect API changes for Java 11.

There are a number of cases when you may not know exactly what class you will be instantiating and want to be able to dynamically instantiate specific classes based on a configuration file or a condition during runtime.

To do so, you will need to define a parent class, abstract class, or interface for your classes and can then use the following code as a guide.

Given the following class definitions:

An abstract class

package com.ryanchapin.examples;

public abstract class MyAbstractClass {

    protected int x;
    protected int y;

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public MyAbstractClass() {}

    public MyAbstractClass(Integer x, Integer y) {
        this.x = x;
        this.y = y;
    }

    public abstract int doSomething();
}

Two concrete implementations

package com.ryanchapin.examples;

public class MyMultiplyingClass extends MyAbstractClass {

    public MyMultiplyingClass() {}

    public MyMultiplyingClass(Integer x, Integer y) {
        super(x, y);
    }

    @Override
    public int doSomething() {
        return x * y;
    }
}
package com.ryanchapin.examples;

public class MyAddingClass extends MyAbstractClass {

    public MyAddingClass() {}

    public MyAddingClass(Integer x, Integer y) {
        super(x, y);
    }

    @Override
    public int doSomething() {
        return x + y;
    }
}

A Main class in which we can run the example

package com.ryanchapin.examples;

public class Main {

    public static void main(String[] args) {
        String myMultiplyingClass = "com.ryanchapin.examples.MyMultiplyingClass";
        String myAddingClass = "com.ryanchapin.examples.MyAddingClass";

        /*
         * Instantiating the class via the no-arg constructor and then using the
         * setters to "configure" the instance.
         */
        MyAbstractClass noArgConstructorInstance = null;
        try {
            @SuppressWarnings("unchecked")
            Class<MyAbstractClass> instanceClass =
                (Class<MyAbstractClass>) Class.forName(myMultiplyingClass);
            noArgConstructorInstance = instanceClass
                .getDeclaredConstructor()
                .newInstance();
        } catch(Exception e) {
            e.printStackTrace();
        }
        noArgConstructorInstance.setX(5);
        noArgConstructorInstance.setY(2);
        System.out.println(noArgConstructorInstance.doSomething());

        /*
         * Instantiating the class via the constructor that takes the x and y
         * parameter values.
         */
        MyAbstractClass xyArgConstructorInstance = null;
        try {
            @SuppressWarnings("unchecked")
            Class<MyAbstractClass> instanceClass =
                (Class<MyAbstractClass>) Class.forName(myAddingClass);
            /*
             * Specify the signature of the constructor that we want to invoke
             * by passing in the types defined in the target constructor.  Then,
             * pass in the arguments to the constructor with the newInstance
             * method.
             */
            xyArgConstructorInstance = instanceClass
                .getDeclaredConstructor(Integer.class, Integer.class)
                .newInstance(5, 2);
        } catch(Exception e) {
            e.printStackTrace();
        }
        System.out.println(xyArgConstructorInstance.doSomething());
    }
}

The Main class illustrates two different ways that we can instantiate our class. One, using the no-arg constructor, and another, by using reflection to get a reference to the constructor with the defined arguments.

The Main class assumes that it will be called with the fully qualified class name as the first argument and will use that String to attempt to instantiate a concrete instance of the MyAbstractClass. The abstract class can be either an interface, or a concrete parent class.

Preserving File Permissions When Copying Files with Ant

If you want to retain the file permissions of a file that you copy with ant you must use the <exec> command instead of? <copy>.

So, instead of:

<copy file=”${source.file}” tofile=”${dest.path}/${dest.file}” overwrite=”true”/>

Use:

<exec executable=”cp”>
? <arg value=”-pf”/>
? <arg value=”${source.file}”/>
? <arg value=”${dest.path}/${dest.file}”/>
</exec>

java.lang.OutOfMemoryError: unable to create new native thread Exception When Using SmbFileInputStream

I am writing an application that copies files from a Samba share using the JCIFC Java CIFS Client Library (which, btw, is a very helpful, widely used, and well developed project).

As usual I am under the gun to get something up and running so I do not have the luxury to explore all of the details as much as I would like. My application gets a directory listing of a Samba share and then spawns a new thread for each new file (with a limit, of course) which copies the file to the local file system via a SmbFileInputStream and FileOutputStream as follows (without the obligatory try/catch blocks for readability):

(An SmbFile instance is provided by the calling code)

byte[] readBuffer = new byte[1024];
int bytesRead = 0;

File fileDestination = new File(“/tmp/”, “destinationFile”);
FileOutputStream fileDestinationFOS = new FileOuputStream(fileDestination);

SmbFileInputStream smbFIS = new SmbFileInputStream(smbFile);

while ((bytesRead = smbFIS.read(readBuffer)) != -1 ) {
fileDestination.write(readBuffer, 0, bytesRead);
}

smbFIS.close();
fileDestinationFOS.close();

When I run it I get the following Exception:

Exception in thread “Thread-3” java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:614)
at jcifs.UniAddress.lookupServerOrWorkgroup(UniAddress.java:173)
at jcifs.UniAddress.getAllByName(UniAddress.java:290)
at jcifs.UniAddress.getByName(UniAddress.java:245)
at jcifs.smb.Dfs.getTrustedDomains(Dfs.java:62)
at jcifs.smb.Dfs.resolve(Dfs.java:167)
at jcifs.smb.SmbFile.resolveDfs(SmbFile.java:671)
at jcifs.smb.SmbFile.send(SmbFile.java:773)
at jcifs.smb.SmbFileInputStream.readDirect(SmbFileInputStream.java:181)
at jcifs.smb.SmbFileInputStream.read(SmbFileInputStream.java:142)
at jcifs.smb.SmbFileInputStream.read(SmbFileInputStream.java:132)
at com.ngc.amap.mapDaemon.FileScanDaemon$RemoteFileCopier.run(FileScanDaemon.java:461)
at java.lang.Thread.run(Thread.java:636)

After considerable searching and testing I determined that the call to jcifs.smb.SmbFile.resolveDfs(SmbFile.java:671) was spawning numerous Threads that were consuming all of the RAM availble to naitive thread in my JVM. Increasing the amount of RAM to the JVM didn’t help.

The solution that I found was to set the following properties in my application prior to the instantiation of any of the jcifs.* classes. In this case, these properties were set in the main method of my entry point class.

System.setProperty(“jcifs.resolveOrder”, “DNS”);
System.setProperty(“jcifs.smb.client.dfs.disabled”, “true”);

Once set, I was able to run as expected without the OutOfMemoryErrors