GOF Patterns in Java

I am currently reading the GOF book 'Design Patterns'.
I was wondering if anyone could point me to a good book,
or online link where GOF patterns are identified in the
J2SE/J2EE packages?
For example, the Decorator pattern appears to form the basis
of the java.io package?
Iterator is obviously the same, except the C++ examples benefit
from using templates, so that the resulting Iterators are type-safe
(coming soon with Generics?).
And the Flyweight pattern appears to have some relation to EJB,
where extrinsic state is loaded/unloaded using ejbLoad/ejbStore
methods?
Thanks, Neil

oops - didn't read your entire post, sorry.
Check out
http://java.sun.com/blueprints/corej2eepatterns/index.html
For patterns related to J2EE development - not sure where you can find same for J2SE, but you seem to have a pretty good handle on that anyway.
Good Luck
Lee

Similar Messages

  • Desperately trying to find patterns with Java code samples

    Greetings. Is there anyone who knows where I can find Java patterns, I am particularly looking for template, literator, composite, observer and decorator. I have gone to Hillside and Portland Repository sites, but did not find pattern sample code.
    I bought the head first Java book which I love, but I would like to see more sample code. They mention pattern catalogues, and besides the Gof I cannot find any. I really want to look at loads of actual samples to get a real feel how these patterns can be applied. Where can I go please?
    Thank you for any and all help.
    Peace,

    You're most welcome - you might check out the Head
    First Design Patterns book as well.Yes, that was fun to read!

  • Design Patterns for java swing application front a J2EE server

    Hi,
    i dont nkow that i stay in the correct forum. I am development a java swing client application, no web, and i dont know that if there are any patterns for a client of this type.
    I have readed http://java.sun.com/blueprints/corej2eepatterns/Patterns/index.html
    but after of Buissnes Delegate pattern, the others one, over ejb tier, are applicated only for web clients, using servlets and jsp pages.
    If i have a swing client application, what patterns i must folow for implement the client logic of my swing application??
    thanks

    MVC pattern is one of the most used
    http://en.wikipedia.org/wiki/MVC
    http://csis.pace.edu/~bergin/mvc/mvcgui.html
    ...

  • DAO pattern and Java Persistence API

    Hi
    This is a question for anyone who might be familiar with the standard DAO design pattern and the Java Persistence API (JPA - part of EJB3). I'm new to this technology, so apologies for any terminology aberrations.
    I am developing the overall architecture for an enterprise system. I intend to use the DAO pattern as the conceptual basis for all data access - this data will reside in a number of forms (e.g. RDBMS, flat file). In the specific case of the RDBMS, I intend to use JPA. My understanding of JPA is that it does/can support the DAO concept, but I'm struggling to get my head around how the two ideas (can be made to) relate to each other.
    For example, the DAO pattern is all about how business objects, data access objects, data transfer objects, data sources, etc relate to each other; JPA is all about entities and persistence units/contexts relate to each other. Further, JPA uses ORM, which is not a DAO concept.
    So, to summarise - can DAO and JPA work together and if so how?
    Thanks
    P.S. Please let me know if you think this topic would be more visible in another forum (e.g. EJB).

    Thanks, duffymo, that makes sense. However ... having read through numerous threads in which you voice your opinion of the DAO World According to Sun, I'd be interested to know your thoughts on the following ...
    Basically, I'm in the process of proposing an enterprise system architecture, which will use DAO as the primary persistence abstraction, and DAO + JPA in the particular case of persistence to a RDBMS. In doing so, I'd like to illustrate the various elements of the DAO pattern, a la the standard class diagram that relates BusinessObject / DataAccessObject / DataSource / TransferObject (http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html). With reference to this model, I know that you have a view on the concept of TransferObject (aka ValueObject?) - how would you depict the DAO pattern in its most generic form? Or is the concept of a generic DAO pattern compromised by the specific implementation that is used (in this case JPA)?

  • How to apply patterns in Java desktop system

    Dear experts,
    I have developed a System which now only can be use through Browser, in other words,a WEB application for the System has developed which I use MVC pattern in it
    now,I should develop a client software for some local customers to use system,but I have not any experiences in developing client desktop software,the main problem now is that I don't know which patterns to use?
    Can you help me ? thanks!!!

    Hi,
    Implement the same MVC arch, but the client side which I suppose you are going to develope in Java AWT/Swing should call the controller (Servlet) using the java.net packages. This works very fine but needs some small hardships....
    jHeaven

  • Bit patterns in Java

    How do I create a bit pattern (bit string, bit stream?) in Java?
    What I'd like to do is to contract data and use a bit pattern instead of the Java built-in standard classes. With what Java tools/classes can I achieve this?
    Example: Storing personal data for a high school student:
    Bit 1 (nationality): American=0, Foreigner=1
    Bit 2 (sex): male=0, female=1
    Bit 3-4 (grade/class): freshman=00, sophomore=01, junior=10, senior=11
    And so on...
    The bit pattern is supposed to be able to hold a lot of information, at least a 100 bits or so.
    Thanks!
    /peso

    peso wrote:
    Thanks for your reply JoachimSauer. You're right in what you're saying that space is cheap and all, but in this case it's essential for my application that I store the information in as few bits as possible.Why is that, I wonder? Out of curiosity. Are you storing/transfering so many records or is the space/bandwidth so limited?
    And I'm also interested in learning the best way to create and build a bit pattern with the information I have.
    Say I have about a hundred different strings containing different information:
    String nationality = "American";
    String sex = "Male";
    String grade = "Sophomore";
    String age = "17";
    Etc...
    I could store this as for example "American;Male;Sophomore;17".The first step would be to get rid of any Strings and transfer that to some better-fitting datatypes. For example create an enum for nationality (even if it only got the values AMERICAN and FOREIGN, I wouldn't call that nationality, btw).
    Then an enum for the sex and grade. And use an int to store the age.
    Because using Strings for things which aren't arbitary (or at least somewhat freeform) character strings is ... wrong.
    But what I'd like to do is to encode this information in a bit pattern like for example "0 0 01 10001" and then converting the bit pattern into a string of ASCII characters by taking lets say 5 bits at a time. Say the beginning of my bit pattern would look like "01011 00101 11001 11110 01000". That would produce the following string with ASCII characters (if I add 33 to the value in order to get a value which represents a writable ASCII character) ",&:?)".I'd use the Base64 encoding, if an ASCII-representation was absolutely needed. But if you really need to use as little space as possible, then you should keep a binary format.
    So the question is, what's the best way to build my bit pattern? Say I need 124 bits for all my information. Do I create a byte array of size 16 and manipulate each byte by shifting and masking? Or is there another way to do it?Use a BitSet.

  • Change log pattern on Java Plugin traced logs

    Hello,
    I have read the following documentation about Tracing and Logging information from the Java Plugin.
    http://docs.oracle.com/javase/6/docs/technotes/guides/deployment/deployment-guide/tracing_logging.html
    Configuring the following properties through Java Console Panel:
    -Djavaplugin.trace=true
    -Djavaplugin.trace.option=basic|net|cache|security|ext|liveconnect|temp
    -Djava.security.debug=access:failure
    However, I cannot find any information concerning how to specify the log pattern of the information traced. Basically, I need to append the timestamp of each generated trace message.
    Please, is there any config parameter to set on JRE Control Panel in order to change that log pattern?
    Thanks in advance!
    Joan Esteve

    Sounds like the server can't find the JAR file on its classpath. Have you tried putting the jar into one of the directories already on the path? Check out the opmn.xml to see what is already configured.

  • Search for Pattern using Java

    hello friends,
    I am trying to read a 'C' file and trying to look for all the lines in the 'C' cod, wherever a function call has happened. How could I do that ??
    Thanks
    ashu

    import java.io.*;
    import java.util.Scanner;
    import java.util.regex.Matcher;
    import java.util.regex.*;
    class FileParser{
        Scanner sc;
        FileParser(String fileName)throws FileNotFoundException{
         sc = new Scanner(new File(fileName));
        void getFunctions(){
         //sc.findInLine("([a-zA-Z]+) (\p{Punct})");
         sc.findInLine("");
         MatchResult result = sc.match();
         //for (int i=1; i<=result.groupCount(); i++)
            // System.out.println(result.group(i));//typo in API
         //System.out.println(result.group(1));
         //System.out.println(result.group(2));
        void getLoops(){
         //Search for patterns FOR, WHILE, DO-WHILE
         sc.findInLine("void");
         MatchResult result = sc.match();
         for (int i=0; i<=result.groupCount(); i++)
             System.out.println(result.group(i));
         /*     sc.findInLine("main");
         result = sc.match();
         for (int i=0; i<=result.groupCount(); i++)
             System.out.println(result.group(i));
         sc.findInLine("void");
         result = sc.match();
         for (int i=0; i<=result.groupCount(); i++)
             System.out.println(result.group(i));
        //Search for pattern FOR
        void getForLoops(){
        //Search for pattern WHILE
        void getWhileLoops(){
        //Search for pattern DO-WHILE
        void getDoWhileLoops(){
        //Search for Union
        //Search for Struct
    }I have added/deleted stuff to try all the different combinations. This class basically will have methods to ....
    1) Get a List of Function Calls with Line# in 'C' code
    2) Get a List of Loops with Line# in 'C' code
    import java.io.*;
    class TestScan{
        public static void main(String[] args)throws IOException{
         FileParser fp = new FileParser("main.c");
         //     fp.getFunctions();
         fp.getLoops();
    }Message was edited by:
    ashucool83

  • Pattern, Matcher Java classes - Several patterns at the same time

    Hi,
    Thank you for reading my post.
    My post is about the Java classes "Pattern" and "Matcher".
    Pattern class: http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
    Matcher class: http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Matcher.htmlSuppose I want to match two or more different patterns in a character sequence.
    Do I have to scan the whole character sequence (which can be large) twice (or
    more according to the number of patterns being searched)?
    Or: is it possible to scan it only once searching for two or more different patterns
    at the same time?
    I have tried the following:
    private static final String REGEX = "\\bdog\\b | \\bcat\\b";
    private static final String INPUT = "The black cat is teasing the white dog. The cat is nibbling at the dog.";
        public static void main(String[] args)
           Pattern p = Pattern.compile(REGEX);
           Matcher m = p.matcher(INPUT); // get a matcher object
           int count = 0;
           while(m.find())
               count++;
               System.out.println("Match number " + count);
               System.out.println("start(): " + m.start());
               System.out.println("end(): " + m.end());
        }But only "\bcat\b" occurrences are matched...
    Here is the result:
    Match number 1
    start(): 9
    end(): 13
    Match number 2
    start(): 43
    end(): 47Moreover, if "\bdog\b" occurrences were correctly matched too
    how would I make the difference between a "\bcat\b"
    and a "\bdog\b" match?
    Additional question:
    When "cat" is matched, it is not "cat" which is matched but " cat "
    (with a leading and a trailing space).
    Maybe this is obvious but I do not understand why.
    Can you help :) ?
    Best regards,
    Lmhelp
    Nota:
    \b: matches a word boundary.
    "\\bdog\\b" is a regular expression which is used for matching occurrences of the whole word "dog".

    Well, you are right again :) !
    I thank you for the code you sent me
    which allows for instance given the following string:
    "The quick \n${colour} \n${animal} jumps ${how} \nthe ${x} lazy dog.";to return:
    "The quick \nbrown \nfox jumps over \nthe ${x} lazy dog.";
    (I don't know what to replace ${x} with...)In the post I sent previously (#7), I realized I could maybe use the
    "Matcher" class's "group()" method to extract some sub-patterns
    inside the firstly extracted patterns themselves.
    However, I also realized I did not really understand the synopsis of the
    "group(int group)" method:
    String - group(int group) - Returns the input subsequence captured by
    the given group during the previous match operation.and actually when I tried the following:
    private static final String REGEX_TITLE = "<title>(.*?)</title>";
    private static final String REGEX_INNER_LINK = " \\[\\[(.*?)\\]\\]";
    private static final String REGEX = REGEX_TITLE + "|" + REGEX_INNER_LINK;
    private static final String INPUT = "<title>Dogs story</title> the [[little]] dog was eaten [[by]] the big dog.";
        public static void main(String[] args)
        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(INPUT);
        int count = 0;
            while(m.find())
                count++;
                System.out.println("Match number " + count);
                System.out.println("start(): " + m.start());
                System.out.println("end(): " + m.end());
                System.out.println("group(): " + m.group());
                System.out.println("m.groupCount(): " + m.groupCount());
                for(int i=0 ; i<=m.groupCount() ; i++)
                    System.out.println("group(" + i + "): " + m.group(i));
        }I had the following result:
    Match number 1
    start(): 0
    end(): 25
    group(): <title>Dogs story</title>
    m.groupCount(): 2
    group(0): <title>Dogs story</title>
    group(1): Dogs story
    group(2): null
    Match number 2
    start(): 29
    end(): 40
    group():  [[little]]
    m.groupCount(): 2
    group(0):  [[little]]
    group(1): null
    group(2): little
    Match number 3
    start(): 54
    end(): 61
    group():  [[by]]
    m.groupCount(): 2
    group(0):  [[by]]
    group(1): null
    group(2): byand I realized that:
    - in the case of "<title>...</title>"
    "m.group(1)" was "what I was looking for"
    - but that, in the case of "[[...]]"
    it was "m.group(2)" that I was looking for.
    So, I can't say in both cases, "m.group(1)"
    is what is between either "<title>...</title>" or "[[...]]".
    Can you explain me in the previous example why:
    - in the first case, we have:
    group(0): <title>Dogs story</title>
    group(1): Dogs story
    group(2): null- and in the second case, we have:
    group(0):  [[little]]
    group(1): null
    group(2): littleIn the synopsis: "Returns the input subsequence captured by the given
    group during the previous match operation."
    I do not understand what is meant by "during the previous match operation".
    Thank you for noticing when I'm being illogical or missing the point :/ :) .
    Thanks and all the best,
    Lmhelp

  • Patterns in java imageio API

    Hello,
    Can somebody help me in figuring out 'Patterns' used in creating the javax.imageio API. By patterns I mean the Gang of Four Patterns like singleton, Decorator, Chain of responsibility....
    Please tell me if you know of any pattern used in this API.
    Thanks a lot for your help,
    Ganesh

    Dennis,
    I am creating a list of patterns used by the imageio API. Yes, this is indeed an assignment. I am not proficient in patterns. Any help in pointing the existing patterns will help me.
    Thanks,
    Ganesh

  • Can not replicate Java 1.4 pattern using Java 5 generics

    I am trying to migrate some 1.4 code to Java 5. The code below captures the essence of what I am trying to do. Trouble is I get the following error
    Name clash : The method readAll(List<XyzData>) of type Generics has the same erasure as readAll(List<Data>) of type Generics.DAO but does not override it
    I sort of understand why it doesn't compile however I am unsure how to fix it, or even if I can use generics in this instance and if I can what is the syntax?
        public abstract class DAO
            public abstract void readAll(List<Data> data);
        public class XyxDAO
        extends DAO
            public void readAll(List<XyzData> xyzData)
        }I certainly need to do some more reading about this generics stuff but any help now would be much appreciated.

    Without a bit more background, it's difficult to be precise, but I would imagine you want something like this (untested):
    // Should this be an interface?
    public abstract class DAO<T extends Data> {
      public abstract void readAll(List<T> data);
    public class MyDAO extends DAO<MyData> {
      public void readAll(List<MyData> myData) {
    }

  • Factory Design Pattern with Java generics

    I was wondering if it was possible to implement the factory pattern using a generic like sintax with java5. Something like:
    IFactory factory = new ConcreteFactory();
    Car c=factory.CreateObject<Car>();
    I saw this article the other day http://weblogs.asp.net/pgielens/archive/2004/07/01/171183.aspx
    done in C# for the framework 2.0 and tryed to re-implement it with java5 however I was less then fortunate, can someone do a functional conversion?

    I had to change the signature a bit but this is the best I came with:
    (I don't like I have to write Type.class but if someone has a better idea please share, I deliberatly used classes are return types but you can easily program to the interfaces as well)
    use:
    ConcreteFactory cf=new ConcreteFactory();
    Car c=cf.Create(Car.class);
    public interface Vehicle {
    String getName();
    public class Plane implements Vehicle {
    String name="Mig 29";
    public String getName() {
    return name;
    public class Car implements Vehicle {
    String name="Volvo";
    public String getName() {
    return name;
    public interface IFactory{
    <T> T Create(Class<T> type);
    public class ConcreteFactory implements IFactory {
    public <T extends Vehicle> T Create(Class<T> type) {
    try {
    return type.newInstance();
    } catch (InstantiationException e) {
    return null;
    } catch (IllegalAccessException e) {
    return null;
    }

  • Need a Regular Expression pattern in Java

    Hi,
        Thanks in advance for your help. I have to replace a string if it's not available inside any single quote.
       e.g.
                   name = 'abc12namexyz234' or name='def234namewsr345name' and name like '%ab123name345rt%'
          In the above I've to replace "name" with "ApplicantEntity.name" but I don't want to replace the string that is available inside the single quote i.e. 'abc12namexyz234'. The result after the replacement should be:
                   ApplicantEntity.name= 'abc12namexyz234' or ApplicantEntity.name='def234namewsr345name' and ApplicantEntity.name like '%ab123name345rt%'
         I am trying to find a appropriate regex. But still no success on that. Please Help....
    Thanks,
    Utpal

    .* matches with any character occuring 0 or more times (except newline characters)
    The problem is more likely to be that you really mean any character once or more times (any number of times include 0 times)
    To do this you need .+

  • Using the Model Facade Pattern in a Java EE 5 Web application

    Hi,
    Yutaka and I did a Tech tip
    http://java.sun.com/mailers/techtips/enterprise/2006/TechTips_Nov06.html#2 on using a model facade pattern in Java EE 5 web-only applications recently. We got some questions about it, and these were some of the questions raised...
    Question 1) the first part of the tech tip(it has two articles in it) http://java.sun.com/mailers/techtips/enterprise/2006/TechTips_Nov06.html showed how to access Java Persistence objects directly from a JSF managed bean, is this a good practice?
    Question 2) when to use a facade(as mentioned in the second part of tech tip) ?
    and maybe
    Question 3) why doesn't the platform make this easier and provide the facade for you?
    Briefly, I will take a shot at answering these three questions
    Answer 1) You can access Java persistence directly from your managed beans, but as your application grows and you start to add more JSF managed beans or other web components(servlets, JSP pages etc) that also directly access Java Persistence objects, you will start to see that you are cutting/pasting similiar code to handle the transactions and to handle the Java Persistence EntityManager and other APIs in many places. So for larger applications, it is a good practice to introduce a model facade to centralize code and encapsulate teh details of the domain model management
    Answer 2) IAs mentioned in answer 1, its good to use a model facade when your application starts to grow. For simple cases a spearate model facade class may not be needed and having managed beans do some of the work is a fast way to jumpstart you application development. But a facade can help keep the code clean and easier to maintain as the aplication grows.
    Answer 3) First note that both of the articles in the tech tip were about pure web apps(not using any EJBs) and running on the Java EE5 platform. Yes it would be nice if a facility like this was made available for web-only applications(those not using EJBs). But for web-only applications you will need to use a hand-rolled facade as we outlined in the tech tip. The Java EE platform does provide a way to make implementing a facde easier though, and the solution for that is to use a Session Bean. This solution does require that you use ythe EJB container and have a Session Bean facade to access your Java Persistence objects and manage the transactions. The EJB Session Facade can do a lot of the work for you and you dont have to write code to manage the transactions or manage the EntityManager. This solution was not covered in this tech tip article but is covered in the Java BluePrints Solutions Catalog for Perssitence at
    https://blueprints.dev.java.net/bpcatalog/ee5/persistence/facade.html in the section "Strategy 2: Using a Session Bean Facade" . Maybe we can cover that in a future tech tip.
    Please ask anymore questions about the tech tip topic on this forum and we will try to answer.
    hth,
    Sean

    Hi Sean,
    I'm working on an implementation of the Model Facade pattern where you can possibly have many facades designed as services. Each service extends a basic POJO class which I'm calling CRUDService: its short code is provided below for your convenience.
    The CRUDService class is meant to generalize CRUD operations regardless of the type of the object being used. So the service can be called as follows, for example:
    Job flightAtt = new Job();
    SERVICE.create(flightAtt);
    Runway r = (Runway) SERVICE.read(Runway.class, 2);
    Employee e = (Employee) SERVICE.read(Employee.class, 4);
    SERVICE.update(e);
    SERVICE.delete(r);SERVICE is a Singleton, the only instance of some service class extending CRUDService. Such a class will always include other methods encapsulating named queries, so the client won't need to know anything about the persistence layer.
    Please notice that, in this scenario, DAOs aren't needed anymore as their role is now distributed among CRUDService and its subclasses.
    My questions, then:
    . Do you see any obvious pitfalls in what I've just described?
    . Do you think traditional DAOs should still be used under JPA?
    . It seems to me the Model Facade pattern isn't widely used because such a role can be fulfilled by frameworks like Spring... Would you agree?
    Thanks so much,
    Cristina Belderrain
    Sao Paulo, Brazil
    public class CRUDService {
        protected static final Logger LOGGER = Logger.
            getLogger(Logger.GLOBAL_LOGGER_NAME);
        protected EntityManager em;
        protected EntityTransaction tx;
        private enum TransactionType { CREATE, UPDATE, DELETE };
        protected CRUDService(String persistenceUnit) {
            em = Persistence.createEntityManagerFactory(persistenceUnit).
                createEntityManager();
            tx = em.getTransaction();
        public boolean create(Object obj) {
            return execTransaction(obj, TransactionType.CREATE);
        public Object read(Class type, Object id) {
            return em.find(type, id);
        public boolean update(Object obj) {
            return execTransaction(obj, TransactionType.UPDATE);
        public boolean delete(Object obj) {
            return execTransaction(obj, TransactionType.DELETE);
        private boolean execTransaction(Object obj, TransactionType txType) {
            try {
                tx.begin();
                if (txType.equals(TransactionType.CREATE))
                    em.persist(obj);
                else if (txType.equals(TransactionType.UPDATE))
                    em.merge(obj);
                else if (txType.equals(TransactionType.DELETE))
                    em.remove(obj);
                tx.commit();
            } finally {
                if (tx.isActive()) {
                    LOGGER.severe(txType + " FAILED: ROLLING BACK!");
                    tx.rollback();
                    return false;
                } else {
                    LOGGER.info(txType + " SUCCESSFUL.");
                    return true;
    }

  • Java Program with Adapter / Facade Pattern

    Hey All:
    I'm very new to the Java language and have been given a fairly complicated (to me) program to do for a course I'm taking. The following is the scenario. I'll post code examples I have and any help will be greatly appreciated. Let me apologize ahead of time for all the code involved and say thank you in advance :).
    The program is the follow the following logic:
    Organizations A's Client (Org_A_Client.java) uses Organization A's interface (Org_A_Interface.java) but we want A's Client to also be able to use Organization B's services as well (Org_B_FileAuthorMgr.java, Org_B_FileDateMgr.java, Org_B_FileIOMgr.java).
    Now a portion of this program also involves validating an xml file to it's dtd, extracting information from that source xml file through the use of a XMLTransformation file, and applying the transformation to produce a targetxml file which is then validated against a target DTD. (I've done this portion as I have a much better understanding of XML).
    At this point we have been given the following java classes:
    Org_A_Client.java
    package project4;
    /* This class is the Organization A Client.
    It reads a source xml file as input and it invokes methods defined in the
    Org_A_Doc_Interface Interface on a class that implements that interface */
    import java.io.*;
    import java.util.Scanner;
    public class Org_A_Client {
         // Define a document object of type Org_A_Doc_Interface
         private Org_A_Doc_Interface document;
         // The Org_A_Client constructor
         public Org_A_Client() {
              // Instanciate the document object with a class that implements the
              // Org_A_Doc_Interface
              this.document = new Adapter();
         // The Main Method
         public static void main(String Args[]) {
              // Instanciate a Client Object
              Org_A_Client client = new Org_A_Client();
              // Create a string to store user input
              String inputFile = null;
              System.out.print("Input file name: ");
              // Read the Source xml file name provided as a command line argument
              Scanner scanner = new Scanner(System.in);
              inputFile = scanner.next();
              // Create a string to store user input
              String fileID = null;
              System.out.print("Input file ID: ");
              // Read the Source xml file name provided as a command line argument
              fileID = scanner.next();
              //Convert the String fileID to an integer value
              int intFileID = Integer.parseInt(fileID);
              if (inputFile != null && !inputFile.equals("")) {
                   // Create and empty string to store the source xml file
                   String file = "";
                   try {
                        // Open the file
                        FileInputStream fstream = new FileInputStream(inputFile);
                        // Convert our input stream to a
                        // BufferedReader
                        BufferedReader d = new BufferedReader(new InputStreamReader(
                                  fstream));
                        // Continue to read lines while
                        // there are still some left to read
                        String temp = "";
                        while ((temp = d.readLine()) != null) {
                             // Add file contents to a String
                             file = file + temp;
                        d.close();
                        // The Client Calls the archiveDoc Method on the Org_A_Document
                        // object
                        if (!file.equals("")) {
                             client.document.archiveDoc(file, intFileID);
                   } catch (Exception e) {
                        System.err.println("File input error");
              } else
                   System.out.println("Error: Invalid Input");
    Org_A_Doc_Interface.java
    package project4;
    /* This class is the Standard Organization A Document Interface.
    * It defines various methods that any XML document object
    * in Organization A should understand
    public interface Org_A_Doc_Interface {
         void archiveDoc(String XMLSourceDoc, int fileID);
         String getDoc(int fileID);
         String getDocDate(int fileID);
         void setDocDate(String date, int fileID);
         String[] getDocAuthors(int fileID);
         void setDocAuthor(String authorname, int position, int fileID);
    Org_B_FileAuthorMgr.java
    package project4;
    public class Org_B_FileAuthorMgr {
         // This function returns the list of file authors for the file that matches
         // the given fileID. For the purpose of the assignment we have not
         // provided any implementation
         public String[] getFileAuthors(String fileID) {
              // Since we do not have any implementation, we just return a
              // null String array of size 2
              return new String[2];
         // This function sets the authorname at a given position for the file that
         // matches the given fileID.
         // For the purpose of the assignment we have not provided any
         // implementation
         public void setFileAuthor(String authorname, int position, String fileID) {
    Org_B_FileDateMgr.java
    package project4;
    public class Org_B_FileDateMgr {
         // This function returns the creation date for the file that matches
         // the given fileID. For the puprposes of the assignment we have not
         // provided any implementation but only return a date string.
         String getFileDate(String fileID) {
              return "1st Nov 2007";
         // This function sets the creation datefor the file that
         // matches the given fileID.
         // For the puprposes of the assignment we have not provided any
         // implementation
         void setFileDate(String date, String fileID) {
    Org_B_FileIOMgr.java
    package project4;
    import java.io.*;
    public class Org_B_FileIOMgr {
         // This class variable stores the file location for all files
         private String fileLocation;
         // This function stores the given String of XMLTargetFile at the
         // fileLocation which is set using the setFileLocation method
         boolean storeFile(String XMLTargetFile, String fileID) {
              if (this.fileLocation != null) {
                   FileOutputStream out; // declare a file output object
                   PrintStream p; // declare a print stream object
                   try {
                        // Create a new file output stream
                        // connected to "myfile.txt"
                        out = new FileOutputStream(fileLocation);
                        // Connect print stream to the output stream
                        p = new PrintStream(out);
                        p.println(XMLTargetFile);
                        p.close();
                        System.out.println("MSG from Org_B_FileIOMgr: Target File Successfully Saved with ID " + fileID);
                   } catch (Exception e) {
                        System.err.println("Error writing to file");
                        return false;
                   return true;
              System.out.println("MSG from Org_B_FileIOMgr: Please set the File Location before storing a file");
              return false;
         // This function sets the fileLocation where the file will be stored for
         // archive
         void setFileLocation(String fileLocation) {
              this.fileLocation = fileLocation;
         // This function retreives the file that matches the given fileID and
         // returns its contents as a string
         // Only for the puprposes of the assignment we have not provided any
         // implementation
         String retrieveFile(String fileID) {
              return "This is the retreived file";
    }Also, we've been given the following two classes which I believe are used to help with the xml transformation using SAX (I've done alot of research regarding parsing XML using SAX/DOM so I understand how it works, but I'm really struggling with the integration...)
    FileDetailsProvider.java
    package project4;
    /* This is the FileDetailsProvider Class which implements the Singleton design pattern.
    The class can be used in the following manner:
         // Declare a object of the class type
            FileDetailsProvider fp;
            // Get the single instance of this class by calling the getInstance static method
            fp= FileDetailsProvider.getInstance();
            // Initialize the class with providing it the file name of our configuration XML file
              fp.loadConfigFile("C:\\assignment4\\XMLTransformerConfig.xml");
    import java.io.File;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    public class FileDetailsProvider {
         private InputHandler handler;
         private SAXParserFactory factory;
         private SAXParser saxParser;
         private final static FileDetailsProvider INSTANCE = new FileDetailsProvider();
         // Private constructor suppresses generation of a (public) default
         // constructor
         private FileDetailsProvider() {
              // Create the content handler
              handler = new InputHandler();
              // Use the default (non-validating) parser
              factory = SAXParserFactory.newInstance();
              // Validate the XML as it is parsed by the SAX Parser: only works
              // for dtd's
              factory.setValidating(true);
              try {
                   saxParser = factory.newSAXParser();
              } catch (Throwable t) {
                   t.printStackTrace();
                   System.exit(0);
         // This is the public static method that returns a single instance of the
         // class everytime it is invoked
         public static FileDetailsProvider getInstance() {
              return INSTANCE;
         // After instantiation this method needs to be called to load the XMLTransformer Configuration xml
         // file that includes the xsl file details needed
         // for our assignment
         public void loadConfigFile(String configFile) {
              try {
                   INSTANCE.saxParser.parse(new File(configFile), INSTANCE.handler);
              } catch (Throwable t) {
                   t.printStackTrace();
                   // Exceptions thrown if validation fails or file not found
                   System.out.println();
                   System.out.println("C:\\Documents and Settings\\Jig\\Desktop\\Project 4\\Project4\\Transform.xsl");
                   System.exit(0);
         // This method return the xsl file name
         public String getXslfileName() {
              return handler.getXslfileName();
         // This method returns the xsl file location
         public String getXslfileLocation() {
              return handler.getXslfileLocation();
    InputHandler.java
    package project4;
    /* This class is used by the FileDetailsProvider Class to read the XMLTranformerConfig xml
    * file using a SAX parser which is a event based parser
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.helpers.DefaultHandler;
    public class InputHandler extends DefaultHandler {
         private String xslfileName = "";
         private String xslfileLocation = "";
         int fileName = 0, fileLoc = 0, DTDUrl = 0;
         boolean endOfFile = false;
         public InputHandler() {
         // Start XML Document Event
         public void startDocument() throws SAXException {
              super.startDocument();
         // End XML Document Event
         public void endDocument() throws SAXException {
              super.endDocument();
              // display();
         public void display() {
              System.out.println(xslfileName);
              System.out.println(xslfileLocation);
         public void startElement(String uri, String localName, String qName,
                   Attributes attributes) throws SAXException {
              String eName = localName; // element name
              if ("".equals(eName))
                   eName = qName; // not namespace-aware
              if (eName.equals("File Name:")) {
                   fileName++;
              } else if (eName.equals("File Location:")) {
                   fileLoc++;
         public void endElement(String uri, String localName, String qName)
                   throws SAXException {
              String eName = localName; // element name
              if ("".equals(eName))
                   eName = qName; // not namespace-aware
         public void characters(char ch[], int start, int length)
                   throws SAXException {
              String str = new String(ch, start, length);
              // Getting the Transform File Location
              if (fileLoc == 1 && xslfileLocation.equals("C:\\Documents and Settings\\Jig\\Desktop\\Project 4\\Project4\\")) {
                   xslfileLocation = str;
              // Getting the Transform File Name
              if (fileName == 1 && xslfileName.equals("Transform.xsl")) {
                   xslfileName = str;
         public void processingInstruction(String target, String data)
                   throws SAXException {
         // treat validation errors as fatal
         public void error(SAXParseException e) throws SAXParseException {
              throw e;
         // This method return the xsl file name
         public String getXslfileName() {
              return xslfileName;
         // This method returns the xsl file location
         public String getXslfileLocation() {
              return xslfileLocation;
    }I need to do the following:
    1. Create an adapter class and a facade class that allows Client A through the use of Organization's A interface to to use Organization B's services.
    2. Validate the Source XML against its DTD
    3. Extract information regarding the XSL file from the given XMLTransformerConfig xml file
    4. Apply the XSL Transformation to the source XML file to produce the target XML
    5. Validate the Target XML against its DTD
    Now I'm not asking for a free handout with this program completed as I really want to learn how to do a program like this, but I really don't have ANY prior java experience other than creating basic classes and methods. I don't know how to bring the whole program together in order to make it all work, so any guidance for making this work would be greatly appreciated.
    I've researched over 100 links on the web and found alot of useful information on adapter patterns with java and facade patterns, as well as SAX/DOM examples for parsing xml documents and validation of the DTD, but I can't find anything that ties this all together. Your help will be saving my grade...I hope :). Thanks so much for reading this.

    No one has anything to add for working on this project? I could really use some help, especially for creating the code for the adapter/facade pattern classes.

Maybe you are looking for

  • Where is the frame rate setting control when making a slide show?

    I am trying to make a slide show using QuickTime Pro and cannot find the frame rate control.I put all my consectively-numbered jpegs in one folder. I then clicked on "File," the "Open Image Sequence," then a window opened up and I click on the first

  • Is there a way of changing photos' dates all at once?

    Hi, I imported a number of photos taken within one week into iPhoto - some of them were assigned a wrong date by my camera which made the last photos the first ones in the folder. I know I can change the photos' dates manually one by one, but is ther

  • NodeIterator Objects different in ChangeAwareClassLoader and bootloader?

    I have an application that does xpath stuff, and just got an error java.lang.LinkageError: loader constraint violation: when resolving method "com.sun.org.apache.xpath.internal.XPathAPI.selectNodeIterator(Lorg/w3c/dom/Node;Ljava/lang/String;)Lorg/w3c

  • Adobe Forms Error while using Webservice

    Hi All,      I have created a interactive adobe form in abap . The adobe form has a button , on click of this button a webservice has to triggered. I have written the script to call the webservice(data connection) in FORMCALC but the webservice does

  • Org. Unit  to ESS

    How it will be mapped organization structure to ESS.  1.Supervisor has to see his entire subordinate attendance/ Absences 2.Subordinate will apply leave through ESS for approval it has display supervisor ESS. Please give some directions to complete m