Usage of java.util.Logger

I have an API which has logs messages using java.util.Logger.
While using this API to perform activities, i need those log messages to tell me when something is going wrong. How can I view those log messages in console?
For eg: I have a class with following structure:-
public class sample
public static void main (String[] args)
APIClass api = new APIClass();
api.doStuff();
Now i want the messages which are printed inside api to appear in my system console, but only SEVERE messages seems to come out, not INFO, FINE etc.
Please let me how i can achieve this?

I was able to get the messages out by following
java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger("com.foo");
java.util.logging.ConsoleHandler ch = new java.util.logging.ConsoleHandler();
ch.setLevel(Level.FINE);
LOGGER.addHandler(ch);
LOGGER.setLevel(Level.FINE);

Similar Messages

  • Formatting Log message for Java.Util.Logger

    Hi,
    I want to format out put that i get when i logg the message
    example
    Sep 23, 2009 5:32:56 PM com.log.utils.helper info
    INFO: in Logging messagingI was wondering if I could get output like
    Sep 23, 2009 5:32:56 PM INFO: in Logging messagingThis is the code which i have used to generate logs
    public Logger logs() {
            makeLogFolder();
            Logger log = Logger.getLogger(UtilityHelper.class.getName());
            try {
                int limit = Integer.parseInt(loadProperties(
    Constants.PROPERTY_FILE_NAME)
    .getProperty(Constants.MAX_SIZE_OF_LOG_FILES));
                int numLogFiles = Integer.parseInt(getProperties(
    Constants.MAX_NO_OF_LOG_FILES));
                String LogFileName = getProperties(Constants.LOG_FOLDER) +
    File.separator + getLogInDate() + File.separator +
    getProperties(Constants.LOG_FILE) + getLogDate() +
    " " + getLogTime() + "_%g.log";
                FileHandler fh1 = new FileHandler(LogFileName, limit, numLogFiles);
                fh1.setFormatter(new SimpleFormatter());
                log.addHandler(fh1);
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (SecurityException ex) {
                ex.printStackTrace();
            return log;
    log.info(message);please let me know how can i do it
    thanks for the reply

    Note: This thread was originally posted in the [Java Virtual Machine (JVM)|http://forums.sun.com/forum.jspa?forumID=37] forum, but moved to this forum for closer topic alignment.

  • Java.util.Logger in ADF page

    The following code work fine in a standalone application and I can view the logs in my LogToFile2.txt
    public static void main(String args[]) throws IOException {
    Logger logger=Logger.getLogger("LogToFile");
    FileHandler logFile = new FileHandler("C:\\temp\\LogToFile2.txt",true);
    logFile.setFormatter(new SimpleFormatter());
    logger.addHandler(logFile);
    logger.info("[email protected]|PRP|listProject|21,Mar,2011:6:17");
    The same code I called from a managed bean it not logging anything just creates a LogToFile2.txt.lck file. Anybody know how to fix this ?
    Thanks
    Suneesh
    Edited by: Suneesh Raman on Mar 21, 2011 10:52 PM

    I want to log some details to a seperate log file. Idea to get the usage statistics. The access logs are not useful as its not changing the url for most of the cases. Is there any better way to get the usage statistics of each page ?
    Thanks
    Suneesh

  • Java.util.logger properties help

    Is there documentation somewhere describing what can be done with logging.properties? I can get the basics to work like setting the filehandler output name and setting level without any problem. However, what if I want 4 different output files for different packages within my application. Can I define 4 unique file handlers in the logger.properties and assign loggers or packages to my desired file handler/ output?
    Or does this have to be done in a java class such that I specify a logger class file at system instead of a logger config file. Of course, I'd prefer to use the config file if it has the capabilities needed. But, again, where are all the options documented?

    documentation for the set method
    * Sets the values for the calendar fields <code>YEAR</code>,
    * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.
    * Previous values of other calendar fields are retained. If this is not desired,
    * call {@link #clear()} first.
    * @param year the value used to set the <code>YEAR</code> calendar field.
    * @param month the value used to set the <code>MONTH</code> calendar field.
    * Month value is 0-based. e.g., 0 for January.
    * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
    * @see #set(int,int)
    * @see #set(int,int,int,int,int)
    * @see #set(int,int,int,int,int,int)
    *

  • Getting no output from java.util.logging.FileHandler

    I am new to Java as is the company I work for, but we have just landed a contract that specifies J2EE as the platform, so here we are. :-) Please bear with me.
    I have been charged with determining our logging architecture and it looks like what is available in java.util.logging will do well (though we may use log4j). However, at this point I am just trying to get anything to work and not having much luck.
    We are using JSF on the front end and I have created a very simple JSF page to test logging. The relevant code is below and I hope will be self explanatory: This code is not meant to be efficient or anything. It is just a proof of concept.
        public String button1_action() {
            // User event code here...
            try {
                Logger l = java.util.logging.Logger.getLogger(Page1.class.getName());
                l.entering(Page1.class.getName(), "button1_action");
                l.info(this.textField1.getValue().toString());
                l.exiting(Page1.class.getName(), "button1_action");
                java.util.logging.Handler h = l.getHandlers()[0];
                h.flush();
            catch(Exception ex) {
                //I have tested this and we aren?t catching any errors.
                System.err.println(ex);
            return "";
        }My logger.properties files looks like this:
    handlers= java.util.logging.FileHandler
    .level= FINEST
    java.util.logging.FileHandler.pattern = c:/sun/logs/test-%u.log
    java.util.logging.FileHandler.limit = 50000
    java.util.logging.FileHandler.count = 1
    java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatterI have developed and tested this in Sun Studio Creator 2004Q2 What is happening is that I am getting three log files in c:/sun/logs
    test-0.log, test-1.log and test-2.log. The first two contain output from various sun components. (sun.rmi.transport for example). The third log remains empty. (zero length)
    I have also deployed the test app to a tomcat 5.0.28 server and get similar results. The only difference is I get only one two log files and the second one remains empty.
    Any assistance or suggestions as to what direction I should be taking would be appreciated.
    --Ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Do not use default logger as getLoggers[0] , but use your java.util.Logger.FileHandler and add filehandler object to log your fButtonActions and you do not need to mess with logger.properties too.

  • Preventing java.util.logging.Logger from writing to STD ERR.

    Hi!
    I'm currently writing a program which uses the java.util.logging package for logging. For some reason it writes ALL logging to std err (as well as to the designated (file) handlers). From what I gather, this is probably done via a ConsoleHandler, but I certainly haven't added any ConsoleHandler. I've also tried printing all registered handlers, which only returns one FileHandler (i.e. the one I added :)).
    The following is a simplification of the code I use:
    private static Logger log = Logger.getLogger("my.package");
        static{
             String logfile = "log.txt";          
              try{
                   FileHandler fh = new FileHandler(logfile);
                   fh.setFormatter(new Formatter() {
                        public String format( LogRecord record){
                             return record.getLevel()+ " " +new Date(record.getMillis()).toString() + ": " +record.getMessage()+ "\n";
                   System.out.println(log.getHandlers().length);
                   log.addHandler(fh);
                   log.setLevel(Level.ALL);
              }catch(IOException e){
                   Frontend.getInstance().displayWarning("Unable to write to log file at "+logfile);
        }Any help on this would be greatly appreciated!

    The speed and on-the-spotness of that reply totally blew me away. Thanks alot, buddy :).

  • USage of import java.util.* & using another package

    When we use import java.util.*; from where does JAVA take the class that are related to util, when I did search for "util" in my machine, I got about 50 results for folders named util and also some where in a folder called "java" when I opened it it did not have the classes, that I was expecting. So I am not clear where does it get the class files from. This is not only for this but for any import commands like import java.io.*;
    When we get another package or source code which was written in java and want to use it in our code where do we have keep the files ? eg. i have the java code that i m writing in c:\java then do I put all the downloaded related files in that folder and then run the code ? or i keep a folder inside java folder and then import them into my code ?
    please do advice.
    Thanks in advance.

    When we use import java.util.*; from where does JAVA
    take the class that are related to util,It means when you use a classname in your code, and that classname is neither in the same package as the class you're writing, nor imported specifically by classname, that it will search for it.
    Where it searches is every folder called util whose parent folder is called java which in turn is at the root level of one of the classpath elements. That is, if classpath contains "A" and "B", and you refer to a class called "Foo", then it will look for "A/java/util/Foo.class" and "B/java/util/Foo.class".
    search for "util" in my machine, I got about 50
    results for folders named util and also some where in
    a folder called "java" when I opened it it did not
    have the classes, that I was expecting. So I am not
    clear where does it get the class files from. This is
    not only for this but for any import commands like
    import java.io.*; All the java.* and javax.* and whatever else it part of the core API is in rt.jar, which lives inside the Java distribution. Classpath elements can be directories or jar files or zip files.

  • Java.util.zip java.util.jar API usage

    I have been trying unsuccessfully for the past two days to be able to programatically add and extract files into and from a JAR using the API. I haven't found any API docs that cover the basics and I have been stumped using the nuggets that I have found on the Forum so far. Below is the code so far. Feel free to use what works in your programs, but if you find out how to get this to work. Sorry for the long post, but I gather this is a common problem that needs to be solved.
    ___________JAR CLASS_______________
    import java.io.*;
    import java.util.*;
    import java.util.jar.*;
    import java.util.zip.*;
    public class Jar {
        public Jar() {
        public boolean copyToJar(File[] sources, File destination) {
            if (destination == null) {
                return false;
            if (nameContainsWildcards(destination)) {
                return false;
            File[] sourceArray = expandWildcards(sources);
            if (sourceArray == null) {
                System.out.println("sourceArray was empty");
                return false;
              System.out.println("Ready to add " + sourceArray.length + " files to " + destination);
              //variables for copying the old destination file to the new destination
              File tmpFile = null;
              JarFile tmpJarFile = null;
              InputStream jarInput = null;
              JarInputStream jarIn = null;
            InputStreamReader jarDataFile = null;
              //variables for the destination
            OutputStream output = null;
            JarOutputStream jarOut = null;
            File input = null;
            FileInputStream dataFile = null;
            int buf = -1;
              if (destination.exists()) {
                   System.out.println("The destination file exists");
                   //copy the destination to temporary
                   //fix copyToJar to use the same .tmp file name as the destination (for reentrant code)
                   tmpFile = new File(destination.getParent() + "\\" + "jar.tmp");
                   if (tmpFile.exists()) {
                        tmpFile.delete();
                   //rename the original to the TempFile
                   destination.renameTo(tmpFile);
                   if (destination.exists()) {
                        destination.delete();
                   try {
                        tmpJarFile = new JarFile(tmpFile);
                   } catch (IOException ioe) {
                        System.out.println("Exception while creating JarFile " + ioe );
            try {
                   //initialize the destination
                output = new FileOutputStream(destination);
                jarOut = new JarOutputStream(output);
                   //if there is a tmpFile copy contents of tmpFile to the new destination
                   if (tmpFile != null) {
                        jarInput = new FileInputStream(tmpFile);
                        jarIn = new JarInputStream(jarInput);
                        ZipEntry ze = null;
                        boolean contains = false;
                        while((ze = jarIn.getNextEntry()) != null) {
                             System.out.println("Working on zipEntry " + ze.getName());
                             contains = false;
                             for (int i=0; i<sourceArray.length; i++) {
                                  if (ze.getName().compareToIgnoreCase(sourceArray.getName()) == 0) {
                                       contains = true;
                             if (contains == false) {
              jarDataFile = new InputStreamReader(tmpJarFile.getInputStream(ze));
                                  System.out.println("The zip Entry was copied from the old file");
                                  jarOut.putNextEntry(ze);
                                  buf = -1;
                                  buf = jarDataFile.read();
                                  while (buf != -1) {
                                       jarOut.write(buf);
                                       buf = jarDataFile.read();
                                  jarOut.closeEntry();
                                  jarDataFile.close();
                        jarIn.close();
                        jarInput.close();
                        tmpFile.delete();
                        tmpJarFile.close();
                   //copy the new files to the destination
    for (int i=0; i<sourceArray.length; i++) {
    if (sourceArray[i].isDirectory()) {
                             //fix copyToJar to copy entire directory if the directory is given as a source
    } else {
    System.out.println("Adding " + sourceArray[i].getAbsolutePath() + " to "
    + destination.getAbsolutePath());
    dataFile = new FileInputStream(sourceArray[i]);
    ZipEntry entry= new ZipEntry(sourceArray[i].getName());
    jarOut.putNextEntry(entry);
    buf = -1;
    buf = dataFile.read();
    while (buf != -1) {
    jarOut.write(buf);
    buf = dataFile.read();
    jarOut.closeEntry();
    jarOut.close();
    output.close();
    dataFile.close();
    } catch (IOException ioe) {
    System.out.println("Exception " + ioe + " occured while writing the backup jar file.");
    try {
    if (jarOut != null)
    jarOut.close();
    if (output != null)
    output.close();
    if (dataFile != null)
    dataFile.close();
    if (jarInput != null)
    jarInput.close();
    if (jarIn != null)
    jarIn.close();
    } catch (IOException ioe2) {
    System.out.println("Exception " + ioe2 + " closing the jar file.");
    return false;
    return true;
    public boolean copyToJar(File source, File destination) {
    File[] sourceArray = expandWildcards(source);
    if (sourceArray == null) {
    System.out.println("sourceArray was empty");
    return false;
    return copyToJar(sourceArray, destination);
         public boolean extractFromJar(File source, File extract, File destDirectory) {
              try {
                   JarFile jarIn = new JarFile(source);
                   ZipEntry ze = jarIn.getEntry(extract.getName());
                   if (ze == null) {
                        System.out.println("Could not find file " + extract + " in jarFile " + source);
                   } else {
                        JarInputStream jarInput = null;
                        InputStreamReader buf = null;
                        FileOutputStream out = null;
                        InputStream in = jarIn.getInputStream(ze);
                        buf = new InputStreamReader(in);
                        out = new FileOutputStream(extract);
                        int buffer = -1;
                        buffer = buf.read();
                        while (buffer != -1) {
                             out.write(buffer);
                             buffer = buf.read();
              } catch (IOException ioe) {
                   System.out.println("Could not extract the file " + extract + " from jarFile " + source);
                   return false;
              return true;
    public int numberOfLines(File fileToCount) {
    int num = 0;
    try {
    FileReader regRead = new FileReader(fileToCount);
    LineNumberReader regReadLine = new LineNumberReader(regRead);
    while (regReadLine.readLine() != null) {
    num = regReadLine.getLineNumber();
    regRead.close();
    regReadLine.close();
    } catch (IOException ioe) {
    System.out.println("Exception " + ioe + " occured in " + this.getClass().getName());
    return num;
    static public boolean nameContainsWildcards(File source) {
    if (source != null) {
    if ((source.getName().indexOf('*')) >=0) {
    return true;
    //fix this check to look for other wildcards
    return false;
    * Expands the * wildcard that does not start the expression. For example,
    * in a directory whose contents are TEST1.DAT, TEST2.DAT AND TEST3.DAT, this
    * funtion will return the following based on the input
    * Input Returns
    * TEST1.DAT File[] containing the first file
    * TEST*.DAT File[] containing all three files plus any that match TEST*.*
    * T*.* File[] containing all three files plus any that match T*.*
    * *.* File[] containing all three files plus any that match *.*
    * EST.DAT File[] containing no files (not a legal expression...yet)
    * ? or
    public File[] expandWildcards(File source) {
    if (source == null) {
    System.out.println("Cannot expand wildCards for a null File");
    return null;
    File[] sourceArray = null;
    if (nameContainsWildcards(source)) {
    FileFilter wildcardFilter = new WildcardFilter(source.getName());
    File sourceParent = new File(source.getParent());
    if (sourceParent != null) {
    sourceArray = sourceParent.listFiles(wildcardFilter);
    } else {
    sourceArray = new File[1];
    sourceArray[0] = source;
    } else {
    sourceArray = new File[1];
    sourceArray[0] = source;
    return sourceArray;
    public File[] expandWildcards(File[] sources) {
    File[] sourceArray = null;
    List fileArrays = new ArrayList();
    for (int i=0; i< sources.length; i++) {
    fileArrays.add(expandWildcards(sources[i]));
    int totalFiles = 0;
    for (int i=0; i < fileArrays.size(); i++) {
    File[] tmp = (File []) fileArrays.get(i);
    if (tmp != null) {
         //System.out.println("Adding " + tmp.length + " to total files");
         totalFiles += tmp.length;
    System.out.println("totalFiles expanded = " + totalFiles);
    sourceArray = new File[totalFiles];
    int nextIndex = 0;
    for (int i=0; i < fileArrays.size(); i++) {
    File[] tmp = (File []) fileArrays.get(i);
    if (tmp != null) {
                        for(int j=0; j < tmp.length; j++) {
                             //System.out.println("Adding file " + tmp[j] + " to sourceArray");
                             sourceArray[nextIndex] = tmp[j];
                             nextIndex++;
    return sourceArray;
    static public void main(String argv[]) {
    Jar jarRun = new Jar();
    File testFile = new File("D:\\test.jar");
              File testFile1 = new File("C:\\Program Files\\RBusinessSystems\\Location Sync\\LONGMONT\\LongmontDefaultCustomers.jar");
              File testFile2 = new File("C:\\Program Files\\RBusinessSystems\\Location Sync\\LONGMONT\\LongmontDefaultInventory.jar");
              File testFile3 = new File("C:\\Program Files\\RBusinessSystems\\Location Sync\\LONGMONT\\LongmontDefaultVendors.jar");
              File testFile4 = new File("C:\\Program Files\\RBusinessSystems\\Location Sync\\LONGMONT\\LongmontDefaultClerks.jar");
              if (argv.length >= 1) {
                   System.out.println("Creating the Jar File");
                   jarRun.copyToJar(testFile1, testFile);
                   jarRun.copyToJar(testFile2, testFile);
                   jarRun.copyToJar(testFile3, testFile);
                   jarRun.copyToJar(testFile4, testFile);
              } else {
                   System.out.println("Extracting from the Jar File");
                   jarRun.extractFromJar(testFile, new File("d:\\LongmontDefaultCustomers.jar"), new File("d:\\"));
                   jarRun.extractFromJar(testFile, new File("d:\\LongmontDefaultInventory.jar"), new File("d:\\"));
                   jarRun.extractFromJar(testFile, new File("d:\\LongmontDefaultVendors.jar"), new File("d:\\"));
                   jarRun.extractFromJar(testFile, new File("d:\\LongmontDefaultClerks.jar"), new File("d:\\"));
    ______________WILDCARD FILTER CLASS __________
    import java.io.File;
    import java.io.FileFilter;
    public class WildcardFilter implements FileFilter {
        private String compare = null;
        private String wildcardStart = null;
        private String wildcardMiddle = null;
        private String wildcardEnd = null;
        WildcardFilter(String comparison) {
            setCompare(comparison);
        public void setCompare(String comparison) {
            compare = comparison.toLowerCase();
            wildcardStart = null;
            wildcardMiddle = null;
            wildcardEnd = null;
            int index = compare.indexOf('*');
            if (index != -1) {
                wildcardStart = compare.substring(0, index);
                if (index + 1 < compare.length()) {
                    wildcardEnd = compare.substring(index + 1, compare.length());
                System.out.println("Expanding fileNames starting with " + wildcardStart
                          + " and ending with " + wildcardEnd);
        public boolean accept(File check) {
            String checkName = check.getName().toLowerCase();
            if (compare == null) {
                return false;
            if (((wildcardEnd == null) || (wildcardEnd.compareTo("") == 0))
                && ((wildcardStart == null) || (wildcardStart.compareTo("") ==0))) {
                return false;
            if (((wildcardStart == null) || (wildcardStart.compareTo("") ==0))
                && (wildcardEnd != null)) {
                if ((wildcardEnd.compareTo(".*") ==0) || (wildcardEnd.compareTo("*") == 0))
                    return true;
                if (checkName.endsWith(wildcardEnd))
                    return true;
            if (((wildcardEnd == null) || (wildcardEnd.compareTo("") == 0))
                && (wildcardStart != null)) {
                if (checkName.startsWith(wildcardStart))
                    return true;
            if ((checkName.startsWith(wildcardStart))
                && (checkName.endsWith(wildcardEnd))) {
                return true;
            return false;

    I figured it out based on some of the other posts I found on this Forum. Following is the working code. While this code is not as robust as it needs to be for production, it will at least get you started on extracting from jar files and writing to jarfiles.
    import java.io.*;
    import java.util.jar.*;
    import java.util.zip.*;
    //NOTE: You can only copy entries created by the Jar tool
    class JarTest {
        JarTest() {
        public boolean copyToJar(File[] fileList, File jarFile) {
            JarEntry je = null;
            File tmpFile = null;
            FileOutputStream fos = null;
            JarOutputStream jos = null;
            BufferedWriter bw = null;
            FileInputStream fis = null;
            JarInputStream jis = null;
            BufferedReader br = null;
            int buf = -1;
            boolean badZipFile = false;
            boolean refreshFromNewFile = false;
            String tmpFileName = jarFile.getAbsolutePath() + ".tmp";
            try {
                tmpFile = new File(tmpFileName);
                fos = new FileOutputStream(tmpFile);
                jos = new JarOutputStream(fos);
                bw = new BufferedWriter(new OutputStreamWriter(jos));
            } catch (IOException ioe) {
                ioe.printStackTrace();
        if(jarFile.exists()) {
                try {
                    fis = new FileInputStream(jarFile);
                    jis = new JarInputStream(fis);
                    br = new BufferedReader(new InputStreamReader(jis));
                } catch (IOException ioe) {
                    System.out.println(ioe);
                try {
                    while((je = jis.getNextJarEntry()) != null) {
                        refreshFromNewFile = false;
                        for (int i = 0; i < fileList.length; i++) {
                            if (je.getName().compareToIgnoreCase(fileList.getName()) == 0) {
    refreshFromNewFile = true;
    if (refreshFromNewFile) {
    //do nothing so we can add the new file below
    } else {
    jos.putNextEntry(je);
    int index = 0;
    buf = -1;
    while((buf = br.read()) != -1) {
    bw.write(buf);
    index++;
    System.out.println("Copied entry " + je.getName() + " of " + index + " bytes from " + jarFile.getName());
    bw.flush();
    jos.closeEntry();
    } catch (IOException ioe) {
    ioe.printStackTrace();
    badZipFile = true;
    try {
    br.close();
    jis.close();
    fis.close();
    } catch (IOException ioe) {
    ioe.printStackTrace();
    for (int i = 0; i < fileList.length; i++) {
    try {
    fis = new FileInputStream(fileList[i]);
    br = new BufferedReader(new InputStreamReader(fis));
    // write the new entries to the tmpFile
    je = new JarEntry(fileList[i].getName());
    jos.putNextEntry(je);
    int index = 0;
    buf = -1;
    while((buf = br.read()) != -1) {
    bw.write(buf);
    index++;
    bw.flush();
    System.out.println("Added entry " + je.getName() + " of " + index + " bytes.");
    jos.closeEntry();
    } catch (IOException ioe) {
    ioe.printStackTrace();
    badZipFile = true;
    try {
    jos.close();
    if (tmpFile != null) {
    // rename the tmpFile to jarFile
    jarFile.delete();
    tmpFile.renameTo(jarFile);
    } catch (IOException ioe) {
    ioe.printStackTrace();
    return true;
    public boolean extractFromJar(File[] fileList, File jarFile) {
    ZipEntry zen = null;
    BufferedReader br = null;
    FileOutputStream fos = null;
    BufferedWriter bw = null;
    try {
    for (int i = 0; i < fileList.length; i++) {
    JarFile jar = new JarFile(jarFile);
    zen = jar.getEntry(fileList[i].getName());
    if (zen == null) {
    System.out.println("Could not find the file " + fileList[i].getName() + " in the zip file " + jar.getName());
    } else {
    File parentDirectory = new File(fileList[i].getParent());
    parentDirectory.mkdirs();
    InputStream in = jar.getInputStream(zen);
    br = new BufferedReader(new InputStreamReader(in));
    fos = new FileOutputStream(fileList[i]);
    bw = new BufferedWriter(new OutputStreamWriter(fos));
    int buf = -1;
    int index = 0;
    while((buf = br.read()) != -1) {
    bw.write(buf);
    bw.flush();
    index++;
    System.out.println("Extracted file " + fileList[i] + " of " + index + " bytes from " + jarFile);
    br.close();
    bw.close();
    } catch (IOException ioe) {
    System.out.println(ioe);
    return false;
    return true;
    public static void main(String[] argv) {
    JarTest jt = new JarTest();
    File jarFile = new File("d:\\test\\test.zip");
    File[] fileList1 = new File[] {new File("d:\\test\\CustomerRefreshRequest.bat"),
                                            new File("d:\\test\\CustomerUpdateGet.bat"),
                                            new File("d:\\test\\CustomerUpdateRequest.bat"),
                                            new File("d:\\test\\LongmontDefaultClerks.jar"),
                                            new File("d:\\test\\LongmontDefaultCustomers.jar"),
                                            new File("d:\\test\\LongmontDefaultInventory.jar")};
    File[] fileList2 = new File[] { new File("d:\\test\\install.bat"),
    new File("d:\\test\\LongmontDefaultVendors.jar"),
    new File("d:\\test\\CustomerUpdateSend.bat") };
    jt.copyToJar(fileList1, jarFile);
    jt.copyToJar(fileList2, jarFile);
    File[] fileList3 = new File[] {new File("d:\\test\\temp\\CustomerRefreshRequest.bat"),
                                            new File("d:\\test\\temp\\CustomerUpdateGet.bat"),
                                            new File("d:\\test\\temp\\CustomerUpdateRequest.bat"),
                                            new File("d:\\test\\temp\\LongmontDefaultClerks.jar"),
                                            new File("d:\\test\\temp\\LongmontDefaultCustomers.jar"),
                                            new File("d:\\test\\temp\\LongmontDefaultInventory.jar")};
    File[] fileList4 = new File[] { new File("d:\\test\\temp\\INSTALL.BAT"),
    new File("d:\\test\\temp\\LongmontDefaultVendors.jar"),
    new File("d:\\test\\temp\\CustomerUpdateSend.bat") };
    jt.extractFromJar(fileList3, jarFile);
    jt.extractFromJar(fileList4, jarFile);

  • Unable to capture messages from java.util.logging

    I have a class called (Caller.java) which invokes a method called foo from another java class(Util.java) using reflection API.Now this method foo logs messages using Java's logger.My requirement is to call foo for 3 times from Caller and capture/redirect the log messages into 3 log files.
    But only the first log file is capturing the log messages(from logger) and other two are not ?
    Plz suggest if I am doing somethin wrong here ?
    Caller.java
    package project2;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintStream;
    import java.lang.reflect.Method;
    public class Caller {
        public Caller() {
        public static void main(String[] args) throws Exception {
            Caller caller = new Caller();
            for (int i = 0 ;i<3 ;i++ )  {
                caller.createLogStream(i);
                System.setOut(caller.getPs());
                System.setErr(caller.getPs());
                /*****************Invoking Util.java*****************************/
                Class clas = Class.forName("project2.Util");
                Method m = clas.getMethod("foo",null);
                Object obj =clas.newInstance();
                m.invoke(obj,null);
        public void createLogStream(int i) throws FileNotFoundException {
            ps = new PrintStream(new File(System.getenv("HOME")+File.separator+"MyLog"+i+".log"));
        public void closeLogStream(){
            ps.close();
            ps = null;
        private PrintStream ps = null;
        public PrintStream getPs() {
            return ps;
    } Util.java
    package project2;
    import java.util.logging.Logger;
    public class Util {
        Logger logger = null;
        public Util() {
            logger = Logger.getLogger(this.getClass().getName());
        public void foo(){
            System.out.println("Hello out stream");
            System.err.println("Hello error stream");
            logger.info("This is an information");
            logger.warning("This is a warning message");
            logger.severe("This is fatal!! ");
    }First Log file MyLog0.log:
    Hello out stream
    Hello error stream
    Feb 16, 2009 7:55:55 PM project2.Util foo
    INFO: This is an information
    Feb 16, 2009 7:55:55 PM project2.Util foo
    WARNING: This is a warning message
    Feb 16, 2009 7:55:55 PM project2.Util foo
    SEVERE: This is fatal!!
    Feb 16, 2009 7:55:55 PM project2.Util foo
    INFO: This is an information
    Feb 16, 2009 7:55:55 PM project2.Util foo
    WARNING: This is a warning message
    Feb 16, 2009 7:55:55 PM project2.Util foo
    SEVERE: This is fatal!!
    Feb 16, 2009 7:55:55 PM project2.Util foo
    INFO: This is an information
    Feb 16, 2009 7:55:55 PM project2.Util foo
    WARNING: This is a warning message
    Feb 16, 2009 7:55:55 PM project2.Util foo
    SEVERE: This is fatal!! Other 2 log files have only this much
    Hello out stream
    Hello error stream

    A stale Connection Factory or Connection Handle may be used in SOA 11g
    Regards,
    Anuj

  • Doubt in java.util.logging

    Hi,
    I have doubt in logging api provided in java 1.4.
    I have a simple program to get the logger and output log into it.
    This is how the program looks.
    LogTest.java
    import java.util.logging.*;
    import java.util.*;
    public class LogTest {
    public static void main(String args[]) {
         LogManager manager = LogManager.getLogManager();
         Logger l = manager.getLogger("global");
         System.out.println(l);
         l.severe("Test");
         System.out.println(manager.getLogger("ivy"));
         System.out.println(manager.getLogger("test"));
    I able to get the instance of the global logger, but im not able to get instance of other logger. I getting null for all the other logger
    test.properites
    =================
    handlers = java.util.logging.ConsoleHandler
    java.util.logging.ConsoleHandler.level=INFO
    java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
    ivy.level = INFO
    .ivy.level = INFO
    =================
    Compilation Command
    java -Djava.util.logging.config.file=C:\WorkSpace\test.properties LogTest Output:
    java.util.logging.Logger@13f5d07
    Jan 25, 2006 7:19:24 PM LogTest main
    SEVERE: Test
    null
    null
    I also tried the same with no config properties, Still im getting the null for logger.
    Can I know is there anything that im missing. Is there any property that must be set or do i hav set some config properties.
    Thanks,
    Siva

    Well, basically that's part of the formatdefinition
    that Properties uses. If you don't do it, then you
    aren't really using Properties format and you'llhave
    to do your own IO.Thanks for the reply. Is there anyother api or class
    that can be used to resolve my problem.What is the problem? A character is escaped, but you will get : when you read the value. You don't have a problem as long as all reading / writing is done through that class.

  • How is java.util.logging used to log to unix syslog?

    I'm trying to log out to syslog using the java.util.logging that is now in 1.4. I've read all I can find on this topic (not much) and have solicited the used of some syslog free ware (protomatter) but still can't get this to work. I feel like I'm missing something simple here, any help would be appreciated....
    Here is my latest attempt:
    import java.util.logging.*;
    import java.util.*;
    import java.io.*;
    import com.protomatter.syslog.SyslogHandler;
    public class SyslogTest
    public static void main(String argv[]){
    Logger logger2 = Logger.getLogger("local3");
    SyslogHandler ch = new SyslogHandler();
    ch.setLevel(Level.WARNING);
    logger2.addHandler(ch);
    logger2.warning("this is a log message");
    if (logger2.isLoggable(Level.WARNING)) {
    System.out.println("Is LOGGABLE");
    else {
    System.out.println("Is not loggable");
    When this is run nothing is printed to any of the local3 facilities. I've verified that syslog is running fine from the command line using unix logger, so the problem seems to be isolated to my java.
    Thanks.

    Hi,
    What is in your logging.properties file? Can you also include the contents of this file?
    Cheers,
    Craig.

  • Wsimport, mapping of xs:date to java.util.Date via ext file, and -B option

    Summary:
    JDK 1.7.0_09 and wsimport and xjc that comes with it.
    Global JAXB binding to map xs:date to java.util.Date
    I have the following external bindings file:
    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
         xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
         elementFormDefault="qualified" attributeFormDefault="unqualified"
         jaxb:extensionBindingPrefixes="xjc" jaxb:version="2.1">
         <xs:annotation>
              <xs:appinfo>
                   <jaxb:globalBindings>
                        <xjc:serializable />
                        <jaxb:javaType name="java.util.Date" xmlType="xs:date" parseMethod="au.com.xxx.jaxb.DateAdapter.parseDate" printMethod="au.com.xxx.jaxb.DateAdapter.printDate" />
                   </jaxb:globalBindings>
              </xs:appinfo>
         </xs:annotation>
    </xs:schema>The au.com.xxx.jaxb.DateAdapter code is as follows:
    package au.com.xxx.jaxb;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import javax.xml.bind.DatatypeConverter;
    public class DateAdapter {
         public static Date parseDate(String s) {
              return DatatypeConverter.parseDate(s).getTime();
         public static String printDate(Date dt) {
              Calendar cal = new GregorianCalendar();
              cal.setTime(dt);
              return DatatypeConverter.printDate(cal);
    }When I run the following wsimport from the command line, I get:
    salvojo@AUD20901BL /cygdrive/c/workspace/JSF/insurance
    $ /cygdrive/c/java/jdk1.7.0_09/x64/bin/wsimport -keep -s gen-src -b external/wsdl/jaxb-bindings.xml -wsdllocation /wsdl/Member.wsdl -d WebContent/WEB-INF/classes external/wsdl/Member.wsdl
    parsing WSDL...
    Generating code...
    Compiling code...
    C:\workspace\JSF\insurance\gen-src\org\w3\_2001\xmlschema\Adapter1.java:13: error: package au.com.xxx.jaxb does not exist
            return (au.com.xxx.jaxb.DateAdapter.parseDate(value));
                                   ^
    C:\workspace\JSF\insurance\gen-src\org\w3\_2001\xmlschema\Adapter1.java:17: error: package au.com.xxx.jaxb does not exist
            return (au.com.xxx.jaxb.DateAdapter.printDate(value));
                                   ^
    2 errors
    compilation failed, errors should have been reportedWhich means that wsimport or xjc needs to know the classpath to find au.com.xxx.jaxb.DateAdapter.
    But how do I pass the classpath from wsimport to the JAXB compiler ?
    There is the -B option in wsimport, but I could not get it to work.
    If I read it correctly, I should be able to pass the -classpath option to the JAXB compiler from wsimport via -B.
    I tried:
    salvojo@AUD20901BL /cygdrive/c/workspace/JSF/insurance
    $ /cygdrive/c/java/jdk1.7.0_09/x64/bin/wsimport -keep -s gen-src -B"-classpath WebContent/WEB-INF/classes" -b external/wsdl/jaxb-bindings.xml -wsdllocation /wsdl/Member.wsdl -d WebContent/WEB-INF/classes external/wsdl/Member.wsdl
    no such JAXB option: -classpath WebContent/WEB-INF/classes
    Usage: wsimport [options] <WSDL_URI>
    where [options] include:
      -b <path>                 specify jaxws/jaxb binding files or additional schemas
                                (Each <path> must have its own -b)
      -B<jaxbOption>            Pass this option to JAXB schema compiler
      -catalog <file>           specify catalog file to resolve external entity references
                                supports TR9401, XCatalog, and OASIS XML Catalog format.
      -d <directory>            specify where to place generated output files
    <...snipped...>... where WebContent/WEB-INF/classes is the classpath where au.com.xxx.jaxb.DateAdapter.class could be found. Obviously it did not like it.
    Also, why is wsimport generate org.w3._2001.xmlschema.Adapter1.java ? All it is doing is wrapping up the exact same call that I have specified in my DateAdapter. How can I tell wsimport or xjc to NOT create that extra Adapter1.java and simply directly use my DateAdapter ??

    create additional column of type LONG to represent date.
    dateFormat is of type java.util.Date:
    long newLongDate = dateFormat.getTime();
    select object(b) from MyEntity b where b.MYLONGDATE > ?1 and b.MYLOGDATE <= ?2

  • Java.security..AccesscontrolException: access denied (java.util.PropertyP..

    I am trying to access the Cisco PIX device manager to get access to my firewall, but get the error message above when trying to start the applet: Is this a bug? Thankful for any input! See the Java concole output below:
    Java Plug-in 1.5.0_06
    Using JRE version 1.5.0_06 Java HotSpot(TM) Client VM
    User home directory = C:\Documents and Settings\Kari
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    p: reload proxy configuration
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    Requesting URL: https://10.1.1.1/jploader.jar
    java.security.AccessControlException: access denied (java.util.PropertyPermission java.version read)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
         at java.lang.System.getProperty(Unknown Source)
         at com.cisco.pdm.e.c.q(Unknown Source)
         at com.cisco.pdm.e.c.h(Unknown Source)
         at com.cisco.pdm.a.byte(Unknown Source)
         at com.cisco.pdm.PDMApplet.start(Unknown Source)
         at com.cisco.nm.util.sgz.Env.start(Env.java:37)
         at com.cisco.nm.util.sgz.Loader.start(Loader.java:109)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)

    I had the same problem trying to open a Pix 506e through Internet Explorer.
    After downloading and installing and uninstalling again differt versions; the working solution for me was version JRE 1.4.2_07
    Be sure to download the 07, other versions of the 1.4.2 were not working!

  • Using ExecutorService class from java.util.concurrent package

    Dear java programmers,
    I have a question regarding the ExecutorService class from java.util.concurrent package.
    I want to parse hundreds of files and for this purpose I'm implementing a thread pool. The way I use the ExecutorService class is summarized below:
    ExecutorService executor = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 1000; i++){
                System.out.println("Parsing file No "+i);
                executor.submit(new Dock(i));
            executor.shutdown();
            try {
                executor.awaitTermination(30, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();However, the code snippet above creates all the 1000 threads (Dock objects) at once and loads them to the executor, and thus I'm worrying about memory leak. I haven't tested it on 1000 files yet but just on 50 small ones, and even if the program prints out "Parsing file No "+i 50 times at once, it executes normally the threads in the background.
    I guess the write way would be to keep the number of active/idle threads in the executor constant (lets say 20 if the thread pool's size is 10) and submit a new one whenever a thread has been finished or terminated. But for this to happen the program should be notified someway whenever a thread is done. Can anybody help me do that?
    thanks in advance,
    Tom

    Ok I found a feasible solution myself although I'm not sure if this is the optimum.
    Here's what I did:
            ExecutorService executor = Executors.newFixedThreadPool(10);
            Future<String> future0, future1, future2, future3, future4, future5, future6, future7, future8, future9;
            Future[] futureArray = {future0 = null, future1 = null, future2 = null, future3 = null, future4 = null, future5 = null,
            future6 = null, future7 = null, future8 = null, future9 = null};
            for (int i = 0; i < 10; i++){
                futureArray[i] = executor.submit(new Dock(i));
            }I created the ExecutorService object which encapsulates the thread pool and then created 10 Future objects (java.util.concurrent.Future) and added them into an Array.
    For java.util.concurrent.Future and Callable Interface usage refer to:
    [http://www.swingwiki.org/best:use_worker_thread_for_long_operations]
    [http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/concurrencyTools.html]
    I used a Future[] Array to make the code neater. So after that I submitted -and in this way filled up- the first 10 threads to the thread pool.
            int i = 9;
            while (i < 1000){
                for (int j = 0; j < 10; j++){
                    if (futureArray[j].isDone() && i < 999){
                        try{
                            i++;
                            futureArray[j] = executor.submit(new Dock(i));
                        } catch (ExecutionException ex) {
                            ex.printStackTrace();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                try {
                    Thread.sleep(100); // wait a while
                } catch(InterruptedException iex) { /* ignore */ }
            executor.shutdown();
            try {
                executor.awaitTermination(60, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();
        }Each of the future[0-9] objects represents a thread in the thread pool. So essentially I'm check which of these 10 threads has been finished (using the java.util.concurrent.Future.isDone() method) and if yes I replenish that empty future[0-9] object with a new one.

  • How to prevent java.util.logging from displaying pop-up dialog on SEVERE?

    Hi,
    I'm new to using java.util.logging. I notice that whenever I try to make a call to logger.SEVERE(msg) or logger.WARNING(msg), not only does it write the output to file (which I want), but it also pops up a dialog box displaying the exception. I don't want this pop up to appear. How do I prevent the logger from doing this?

    What are you talking about?
    Hello,
    In order to better assist you with your issue please provide us with a screenshot. If you need help to create a screenshot, please see [[How do I create a screenshot of my problem?]]
    Once you've done this, attach the saved screenshot file to your forum post by clicking the '''Browse...''' button below the ''Post your reply'' box. This will help us to visualize the problem.
    Thank you!

Maybe you are looking for