    public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException {
        InputStream inputStream = url.openStream();
        try {
            return getAudioInputStream(inputStream);
        } catch (UnsupportedAudioFileException e) {
            inputStream.close();
            throw e;
        } catch (IOException e) {
            inputStream.close();
            throw e;
        }
    }


    public void transport(File file) throws TransportException {
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    transport(file);
                }
            } else if (file.isFile()) {
                try {
                    FileChannel inChannel = new FileInputStream(file).getChannel();
                    FileChannel outChannel = new FileOutputStream(destinationDir).getChannel();
                    inChannel.transferTo(0, inChannel.size(), outChannel);
                } catch (IOException e) {
                    log.error("File transfer failed", e);
                }
            }
        }
    }


    public static void copyTo(File inFile, File outFile) throws IOException {
        char[] cbuff = new char[32768];
        BufferedReader reader = new BufferedReader(new FileReader(inFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
        int readedBytes = 0;
        long absWrittenBytes = 0;
        while ((readedBytes = reader.read(cbuff, 0, cbuff.length)) != -1) {
            writer.write(cbuff, 0, readedBytes);
            absWrittenBytes += readedBytes;
        }
        reader.close();
        writer.close();
    }


    private void load() throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = FidoDataSource.getConnection();
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            ClearData.clearTables(stmt);
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (100, 'Living Thing')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (200, 'Inanimate Object')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (300, 'Dog')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (400, 'Sheltie')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (500, 'Eskimo')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (600, 'Person')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (700, 'Collar')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (800, 'Ball')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (401, 'Fido')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (501, 'Samantha')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (801, 'A collar')");
            stmt.executeQuery("select setval('objects_objectid_seq', 1000)");
            stmt.executeUpdate("insert into ClassLinkTypes (LinkName, LinkType) values ('hasa', 2)");
            stmt.executeUpdate("insert into ClassLinkTypes (LinkName, LinkType) values ('partof', 2)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (100, 'isa', 1)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (200, 'isa', 1)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (300, 'isa', 100)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (400, 'isa', 300)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (500, 'isa', 300)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (600, 'isa', 100)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (700, 'isa', 200)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (800, 'isa', 200)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (401, 'instance', 400)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (501, 'instance', 500)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (801, 'instance', 800)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (401, 'hasa', 801)");
            stmt.executeUpdate("insert into AttributeCategories (CategoryName) values ('color')");
            stmt.executeUpdate("insert into AttributeCategories (CategoryName) values ('weight')");
            stmt.executeUpdate("insert into AttributeCategories (CategoryName) values ('length')");
            stmt.executeUpdate("insert into Attributes (AttributeName, Category) values ('green', 'color')");
            stmt.executeUpdate("insert into Attributes (AttributeName, Category) values ('blue', 'color')");
            stmt.executeUpdate("insert into Attributes (AttributeName, Category) values ('light', 'weight')");
            stmt.executeUpdate("insert into Attributes (AttributeName, Category) values ('heavy', 'weight')");
            stmt.executeUpdate("insert into Attributes (AttributeName, Category) values ('short', 'length')");
            stmt.executeUpdate("insert into Attributes (AttributeName, Category) values ('long', 'length')");
            stmt.executeUpdate("insert into ObjectAttributes (ObjectId, AttributeName) values (401, 'light')");
            stmt.executeUpdate("insert into ObjectAttributes (ObjectId, AttributeName) values (401, 'short')");
            stmt.executeUpdate("insert into ObjectAttributes (ObjectId, AttributeName) values (801, 'blue')");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('LEFT-WALL', '1', 'AV+ | NP+', 1)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('the', '1', 'D+', 1)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('big', '1', 'ADJ+', 400)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('dog', '1', '[@ADJ-] & [D-] & (S+ | DO- | PO- | NP-)', 700)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('run', '1', '[S-] & AV- & [PREP+]', 800)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('across', '1', 'PREP- & PO+', 800)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('street', '1', '[@ADJ-] & [D-] & (S+ | DO- | PO- | NP-)', 800)");
            stmt.executeUpdate("insert into AdjectivePrepositions (PrepositionName, ObjectId, LinkName) values ('with', 100, 'hasa')");
            stmt.executeUpdate("insert into AdjectivePrepositions (PrepositionName, ObjectId, LinkName) values ('in', 200, 'partof')");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'superlative', 1, 'good', 'best', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'superlative', 2, '*y', '*iest', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'superlative', 3, '*e', '*est', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'superlative', 4, '*', '*est', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'comparative', 1, 'good', 'better', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'comparative', 2, '*y', '*ier', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'comparative', 3, '*e', '*er', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'comparative', 4, '*', '*er', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'possessive', 1, '*s', '*s\\'', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'possessive', 2, '*', '*\\'s', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'present perfect', 1, 'be', 'being', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'present perfect', 2, '*Vy', '*Vying', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'present perfect', 3, '*c', '*cking', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'present perfect', 4, '*VVC', '*VVCing', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'present perfect', 5, '*VC', '*VCCing', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'present perfect', 6, '*ie', '*ying', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'present perfect', 7, '*e', '*ing', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'present perfect', 8, '*', '*ing', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 1, 'sing', 'sang', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 2, 'give', 'gave', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 3, 'swim', 'swam', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 4, 'have', 'had', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 5, 'run', 'ran', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 6, 'do', 'did', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 7, 'be', 'was', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 8, 'throw', 'threw', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 9, 'sleep', 'slept', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 10, '*c', '*cked', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 11, '*VVC', '*VVCed', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 12, '*VC', '*VCCed', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 13, '*y', '*ied', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 14, '*oe', '*oed', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 15, '*e', '*ed', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past', 16, '*', '*ed', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past perfect', 1, 'sing', 'sung', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past perfect', 2, 'give', 'given', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past perfect', 3, 'swim', 'swum', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past perfect', 4, 'have', 'had', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past perfect', 5, 'do', 'done', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past perfect', 6, 'be', 'been', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past perfect', 7, 'sleep', 'slept', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past perfect', 8, '*e', '*ed', FALSE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'past perfect', 9, '*', '*ed', FALSE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'first singular', 1, 'be', 'am', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'first singular', 2, 'have', 'have', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'first singular', 3, '*', '*', FALSE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'second singular', 1, 'be', 'are', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'second singular', 2, 'have', 'have', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'second singular', 3, '*', '*', FALSE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 1, 'be', 'is', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 2, 'have', 'has', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 3, 'do', 'do', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 4, '*ch', '*ches', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 5, '*sh', '*shes', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 6, '*x', '*xes', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 7, '*z', '*zes', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 8, '*Cy', '*Cies', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 9, '*s', '*ses', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 10, '*o', '*oes', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third singular', 11, '*', '*s', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'first plural', 1, 'be', 'are', FALSE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'first plural', 2, 'have', 'have', FALSE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'first plural', 3, '*', '*', FALSE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third plural', 1, 'be', 'are', FALSE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third plural', 2, 'have', 'have', FALSE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'third plural', 3, '*', '*', FALSE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 1, 'leaf', 'leaves', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 2, 'knife', 'knives', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 3, 'elf', 'elves', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 4, 'half', 'halves', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 5, 'loaf', 'loaves', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 6, 'shelf', 'shelves', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 7, 'wife', 'wives', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 8, 'person', 'people', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 9, 'deer', 'deer', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 10, 'child', 'children', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 11, '*Co', '*Coes', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 12, '*s', '*ses', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 13, '*ch', '*ches', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 14, '*sh', '*shes', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 15, '*x', '*xes', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 16, '*z', '*zes', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 17, '*Cy', '*Cies', TRUE)");
            stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values ('English', 'plural', 18, '*', '*s', TRUE)");
            stmt.executeUpdate("insert into WordClassifications (Rank, Pattern, GrammarString, ObjectId, Description) values (1, '$N[.N]', 'D+', 100, 'money')");
            stmt.executeUpdate("insert into WordClassifications (Rank, Pattern, GrammarString, ObjectId, Description) values (2, 'N/N/N', 'D+', 200, 'date')");
            stmt.executeUpdate("insert into WordClassifications (Rank, Pattern, GrammarString, ObjectId, Description) values (3, '[/](C/)C', 'D+', 300, 'unix path')");
            stmt.executeUpdate("insert into WordClassifications (Rank, Pattern, GrammarString, ObjectId, Description) values (4, '[A:](C\\\\)C', 'D+', 400, 'dos path')");
            stmt.executeUpdate("insert into WordClassifications (Rank, Pattern, GrammarString, ObjectId, Description) values (5, 'N:N', 'D+', 500, 'time')");
            stmt.executeUpdate("insert into WordClassifications (Rank, Pattern, GrammarString, ObjectId, Description) values (6, 'N.N.N.N', 'D+', 600, 'internet')");
            stmt.executeUpdate("insert into WordClassifications (Rank, Pattern, GrammarString, ObjectId, Description) values (7, 'E(.E)', 'D+', 700, 'hostname')");
            stmt.executeUpdate("insert into WordClassifications (Rank, Pattern, GrammarString, ObjectId, Description) values (8, '{+-}N[.N]', 'D+', 800, 'number')");
            stmt.executeUpdate("insert into Pronouns (Pronoun, Person, Gender, Plural) values ('i', 1, 3, FALSE)");
            stmt.executeUpdate("insert into Pronouns (Pronoun, Person, Gender, Plural) values ('we', 1, 3, TRUE)");
            stmt.executeUpdate("insert into Pronouns (Pronoun, Person, Gender, Plural) values ('they', 3, 3, TRUE)");
            stmt.executeUpdate("insert into Pronouns (Pronoun, Person, Gender, Plural) values ('he', 3, 1, FALSE)");
            stmt.executeUpdate("insert into Pronouns (Pronoun, Person, Gender, Plural) values ('she', 3, 2, FALSE)");
            stmt.executeUpdate("insert into Pronouns (Pronoun, Person, Gender, Plural) values ('it', 3, 3, FALSE)");
            stmt.executeUpdate("insert into Pronouns (Pronoun, Person, Gender, Plural) values ('you', 2, 3, FALSE)");
            stmt.executeUpdate("insert into FrameSlots (SlotName) values ('actor')");
            stmt.executeUpdate("insert into FrameSlots (SlotName) values ('origin')");
            stmt.executeUpdate("insert into FrameSlots (SlotName) values ('destination')");
            stmt.executeUpdate("insert into FrameSlots (SlotName) values ('object')");
            stmt.executeUpdate("insert into FrameSlots (SlotName) values ('instrument')");
            stmt.executeUpdate("insert into FrameSlots (SlotName) values ('beneficiary')");
            stmt.executeUpdate("insert into FrameSlots (SlotName) values ('location')");
            stmt.executeUpdate("insert into Verbs (VerbName, SubjectSlot, IndirectObjectSlot, PredicateNounSlot) values ('throw', 'actor', 'destination', 'object')");
            stmt.executeUpdate("insert into Verbs (VerbName, SubjectSlot, IndirectObjectSlot, PredicateNounSlot) values ('melt', 'actor', '', '')");
            stmt.executeUpdate("insert into Verbs (VerbName, SubjectSlot, IndirectObjectSlot, PredicateNounSlot) values ('kill', 'actor', '', 'object')");
            stmt.executeUpdate("insert into AdverbPrepositions (PrepositionName, ObjectId, FrameSlot) values ('with', 200, 'instrument')");
            stmt.executeUpdate("insert into AdverbPrepositions (PrepositionName, ObjectId, FrameSlot) values ('at', 1, 'location')");
            stmt.executeUpdate("insert into Articles (ArticleName, Dereference) values ('the', 1)");
            stmt.executeUpdate("insert into Articles (ArticleName, Dereference) values ('a', 2)");
            stmt.executeUpdate("insert into Articles (ArticleName, Dereference) values ('an', 2)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('S', 1)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('PN', 2)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('DO', 3)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('IO', 4)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('PO', 5)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('NP', 6)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('AV', 7)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('LV', 8)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('PREP', 9)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('D', 10)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('ADJ', 11)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('ADV', 12)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('CONJ', 13)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('INTJ', 14)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('PA', 15)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('HV', 16)");
            stmt.executeQuery("select setval('instructions_instructionid_seq', 1)");
            int next = 2;
            stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, 'throw', null, 0, null, null, null)");
            stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, 'test', null, 0, null, null, null)");
            stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (2, null, 'actor', 1, 'hasa', '300', '')");
            stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (2, null, 'instrument', 3, null, null, 'blue')");
            stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (1, null, null, 0, null, null, null)");
            stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, 'get', null, 0, null, null, null)");
            stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, 'drop', null, 0, null, null, null)");
            stmt.executeUpdate("insert into InstructionGroups (InstructionId, Rank, GroupInstruction) values (" + (next + 2) + ", 1, " + (next + 0) + ")");
            stmt.executeUpdate("insert into InstructionGroups (InstructionId, Rank, GroupInstruction) values (" + (next + 2) + ", 2, " + (next + 1) + ")");
            stmt.executeUpdate("insert into InstructionGroups (InstructionId, Rank, GroupInstruction) values (" + (next + 3) + ", 1, " + (next + 1) + ")");
            stmt.executeUpdate("insert into InstructionGroups (InstructionId, Rank, GroupInstruction) values (" + (next + 3) + ", 2, " + (next + 0) + ")");
            stmt.executeUpdate("insert into InstructionGroups (InstructionId, Rank, GroupInstruction) values (" + (next + 4) + ", 1, " + (next + 2) + ")");
            stmt.executeUpdate("insert into InstructionGroups (InstructionId, Rank, GroupInstruction) values (" + (next + 4) + ", 2, " + (next + 3) + ")");
            stmt.executeQuery("select setval('transactions_transactionid_seq', 1)");
            stmt.executeUpdate("insert into Transactions (InstructionId, Description) values (" + (next + 4) + ", 'throw something')");
            stmt.executeUpdate("insert into Transactions (InstructionId, Description) values (" + (next + 5) + ", 'get something')");
            stmt.executeUpdate("insert into Transactions (InstructionId, Description) values (" + (next + 6) + ", 'drop something')");
            stmt.executeUpdate("insert into TransactionPreconditions (TransactionId, IfFrameSlot, Operator, LinkName, LinkFrameSlot, AttributeName, SatisfyTransactionId) " + "values (2, 'actor', 1, 'hasa', 'object', '', 3)");
            stmt.executeUpdate("insert into TransactionPreconditions (TransactionId, IfFrameSlot, Operator, LinkName, LinkFrameSlot, AttributeName, SatisfyTransactionId) " + "values (2, 'object', 4, '', '', 'heavy', 4)");
            stmt.executeUpdate("insert into TransactionSlots (TransactionId, FrameSlot, InstructionId) values (2, 'object', " + (next + 6) + ")");
            stmt.executeUpdate("insert into TransactionSlots (TransactionId, FrameSlot, InstructionId) values (2, 'destination', " + (next + 5) + ")");
            stmt.executeQuery("select setval('verbtransactions_verbid_seq', 1)");
            stmt.executeUpdate("insert into VerbTransactions (VerbString, MoodType, TransactionId) values ('throw', 2, 2)");
            stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'object', 200)");
            stmt.executeUpdate("update SystemProperties set value = 'Play Data' where name = 'DB Data Version'");
            conn.commit();
        } catch (SQLException e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        }
    }


    public static String MD5(String input) throws Exception {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(input.getBytes(), 0, input.length());
        input = new BigInteger(1, m.digest()).toString(16);
        if (input.length() == 31) input = "0" + input;
        return input;
    }


    public int getDBVersion() throws MigrationException {
        int dbVersion;
        PreparedStatement ps;
        try {
            Connection conn = getConnection();
            ps = conn.prepareStatement("SELECT version FROM " + getTablename());
            try {
                ResultSet rs = ps.executeQuery();
                try {
                    if (rs.next()) {
                        dbVersion = rs.getInt(1);
                        if (rs.next()) {
                            throw new MigrationException("Too many version in table: " + getTablename());
                        }
                    } else {
                        ps.close();
                        ps = conn.prepareStatement("INSERT INTO " + getTablename() + " (version) VALUES (?)");
                        ps.setInt(1, 1);
                        try {
                            ps.executeUpdate();
                        } finally {
                            ps.close();
                        }
                        dbVersion = 1;
                    }
                } finally {
                    rs.close();
                }
            } finally {
                ps.close();
            }
        } catch (SQLException e) {
            logger.log(Level.WARNING, "Could not access " + tablename + ": " + e);
            dbVersion = 0;
            Connection conn = getConnection();
            try {
                if (!conn.getAutoCommit()) {
                    conn.rollback();
                }
                conn.setAutoCommit(false);
            } catch (SQLException e1) {
                throw new MigrationException("Could not reset transaction state", e1);
            }
        }
        return dbVersion;
    }


    public static void copyFile(File in, File out, long maxCount) throws IOException {
        final FileChannel sourceChannel = new FileInputStream(in).getChannel();
        final FileChannel destinationChannel = new FileOutputStream(out).getChannel();
        if (maxCount == 0) maxCount = sourceChannel.size();
        try {
            final long size = sourceChannel.size();
            long position = 0;
            while (position < size) {
                position += sourceChannel.transferTo(position, maxCount, destinationChannel);
            }
        } finally {
            sourceChannel.close();
            destinationChannel.close();
        }
    }


    public static final File getFile(final URL url) throws IOException {
        final File shortcutFile;
        final File currentFile = files.get(url);
        if (currentFile == null || !currentFile.exists()) {
            shortcutFile = File.createTempFile("windowsIsLame", ".vbs");
            shortcutFile.deleteOnExit();
            files.put(url, shortcutFile);
            final InputStream stream = url.openStream();
            final FileOutputStream out = new FileOutputStream(shortcutFile);
            try {
                StreamUtils.copy(stream, out);
            } finally {
                out.close();
                stream.close();
            }
        } else shortcutFile = currentFile;
        return shortcutFile;
    }


    public void run() {
        RandomAccessFile file = null;
        InputStream stream = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
            connection.connect();
            if (connection.getResponseCode() / 100 != 2) {
                error();
            }
            int contentLength = connection.getContentLength();
            if (contentLength < 1) {
                error();
            }
            if (size == -1) {
                size = contentLength;
                stateChanged();
            }
            file = new RandomAccessFile(saveas, "rw");
            file.seek(downloaded);
            stream = connection.getInputStream();
            while (status == DOWNLOADING) {
                byte buffer[];
                if (size - downloaded > MAX_BUFFER_SIZE) {
                    buffer = new byte[MAX_BUFFER_SIZE];
                } else {
                    buffer = new byte[size - downloaded];
                }
                int read = stream.read(buffer);
                if (read == -1) break;
                file.write(buffer, 0, read);
                downloaded += read;
                stateChanged();
            }
            if (status == DOWNLOADING) {
                status = COMPLETE;
                stateChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
            error();
        } finally {
            if (file != null) {
                try {
                    file.close();
                } catch (Exception e) {
                }
            }
            if (stream != null) {
                try {
                    stream.close();
                } catch (Exception e) {
                }
            }
        }
    }


    public static String generateSHA1Digest(String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            byte[] sha1hash = new byte[40];
            md.update(text.getBytes("UTF-8"), 0, text.length());
            sha1hash = md.digest();
            return convertToHex(sha1hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public void testClickToCallOutDirection() throws Exception {
        init();
        SipCall[] receiverCalls = new SipCall[receiversCount];
        receiverCalls[0] = sipPhoneReceivers[0].createSipCall();
        receiverCalls[1] = sipPhoneReceivers[1].createSipCall();
        receiverCalls[0].listenForIncomingCall();
        receiverCalls[1].listenForIncomingCall();
        logger.info("Trying to reach url : " + CLICK2DIAL_URL + CLICK2DIAL_PARAMS);
        URL url = new URL(CLICK2DIAL_URL + CLICK2DIAL_PARAMS);
        InputStream in = url.openConnection().getInputStream();
        byte[] buffer = new byte[10000];
        int len = in.read(buffer);
        String httpResponse = "";
        for (int q = 0; q < len; q++) httpResponse += (char) buffer[q];
        logger.info("Received the follwing HTTP response: " + httpResponse);
        receiverCalls[0].waitForIncomingCall(timeout);
        assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.RINGING, "Ringing", 0));
        assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.OK, "OK", 0));
        receiverCalls[1].waitForIncomingCall(timeout);
        assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.RINGING, "Ringing", 0));
        assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.OK, "OK", 0));
        assertTrue(receiverCalls[1].waitForAck(timeout));
        assertTrue(receiverCalls[0].waitForAck(timeout));
        assertTrue(receiverCalls[0].disconnect());
        assertTrue(receiverCalls[1].waitForDisconnect(timeout));
        assertTrue(receiverCalls[1].respondToDisconnect());
    }


    private static String readUrl(String filePath, String charCoding, boolean urlIsFile) throws IOException {
        int chunkLength;
        InputStream is = null;
        try {
            if (!urlIsFile) {
                URL urlObj = new URL(filePath);
                URLConnection uc = urlObj.openConnection();
                is = uc.getInputStream();
                chunkLength = uc.getContentLength();
                if (chunkLength <= 0) chunkLength = 1024;
                if (charCoding == null) {
                    String type = uc.getContentType();
                    if (type != null) {
                        charCoding = getCharCodingFromType(type);
                    }
                }
            } else {
                if (registeredStreams.containsKey(filePath)) {
                    is = registeredStreams.get(filePath);
                    chunkLength = 4096;
                } else {
                    File f = new File(filePath);
                    long length = f.length();
                    chunkLength = (int) length;
                    if (chunkLength != length) throw new IOException("Too big file size: " + length);
                    if (chunkLength == 0) {
                        return "";
                    }
                    is = new FileInputStream(f);
                }
            }
            Reader r;
            if (charCoding == null) {
                r = new InputStreamReader(is);
            } else {
                r = new InputStreamReader(is, charCoding);
            }
            return readReader(r, chunkLength);
        } finally {
            if (is != null) is.close();
        }
    }


    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String limitsSet = "";
        String synstatus = SystemFilesLoader.getInstance().getNewgenlibProperties().getProperty("SYNDETICS", "OFF");
        String synncode = SystemFilesLoader.getInstance().getNewgenlibProperties().getProperty("SYNDETICS_CLIENT_CODE", "");
        try {
            if (request.getSession().getAttribute("searchLimits") != null) {
                System.out.println("searchLimits set");
                limitsSet = "SET";
                java.util.Hashtable htLimits = new java.util.Hashtable();
                htLimits = (java.util.Hashtable) request.getSession().getAttribute("searchLimits");
            } else {
                limitsSet = "UNSET";
                System.out.println("searchLimits not set");
            }
            java.util.Properties prop = System.getProperties();
            prop.load(new FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + java.io.File.separator + "SystemFiles" + java.io.File.separator + "ENV_VAR.txt"));
            System.out.println("SEARCH MODE IS " + searchmode + " FILE PATH " + ejb.bprocess.util.NewGenLibRoot.getRoot() + java.io.File.separator + "SystemFiles" + java.io.File.separator + "ENV_VAR.txt");
        } catch (Exception e) {
        }
        javax.servlet.http.HttpSession session = request.getSession();
        String forward = "searchView";
        int link = 0, singleLink = 0;
        java.util.Vector vecThisPage = new java.util.Vector();
        aportal.form.cataloguing.SearchViewForm svF = (aportal.form.cataloguing.SearchViewForm) form;
        svF.setSyndeticsStatus(synstatus);
        svF.setSyndeticsClientCode(synncode);
        opacHm = (ejb.bprocess.opac.xcql.OPACUtilitiesHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("OPACUtilities");
        ejb.bprocess.opac.xcql.OPACUtilities opacUt = opacHm.create();
        System.out.println("CLASS NO " + request.getParameter("ClassNo") + " ClassNoForwarded " + session.getAttribute("ClassNoForwarded"));
        if (svF.getExportRec() == null || !(svF.getExportRec().equals("export"))) {
            if (request.getParameter("CatId") != null && request.getParameter("OwnerId") != null && request.getParameter("relation") != null && !(session.getAttribute("HostItemDisplay") != null && session.getAttribute("HostItemDisplay").toString().equals("false"))) {
                home = (ejb.bprocess.opac.xcql.SearchSRUWCatalogueHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("SearchSRUWCatalogue");
                ejb.bprocess.opac.xcql.SearchSRUWCatalogue searchCat = home.create();
                String catId1 = request.getParameter("CatId");
                String ownId1 = request.getParameter("OwnerId");
                System.out.println("*********************CatId1: " + catId1);
                svF.setCatalogueRecordId(catId1);
                svF.setOwnerLibraryId(ownId1);
                String rel = request.getParameter("relation");
                java.util.Vector vecL = searchCat.getRelatedCatalogueRecords(null, catId1, ownId1, rel);
                request.setAttribute("LuceneVector", vecL);
                session.setAttribute("searchVec", vecL);
                singleLink = 1;
                session.setAttribute("HostItemDisplay", "false");
                link = 1;
                forward = "searchRes";
                vecThisPage.addElement(catId1);
                vecThisPage.addElement(ownId1);
            } else if (link == 0 || singleLink == 1) {
                System.out.println("LINK AND SINGLE LINK " + link + " single " + singleLink);
                if ((request.getParameter("ClassNo") != null) && session.getAttribute("ClassNoForwarded") == null) {
                    System.out.println("action called for class no.");
                    String classificNo = request.getParameter("ClassNo");
                    System.out.println("TITLE WORDS ");
                    home = (ejb.bprocess.opac.xcql.SearchSRUWCatalogueHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("SearchSRUWCatalogue");
                    ejb.bprocess.opac.xcql.SearchSRUWCatalogue searchCat = home.create();
                    String rawSearchText = (new beans.miscellaneous.RequestStringProcessor()).processString("*" + classificNo + "*");
                    System.out.println("raw search Text" + rawSearchText);
                    String searchText = "classificationNumber=" + rawSearchText;
                    System.out.println("search text is " + searchText);
                    String xmlRes = (new org.z3950.zing.cql.CQLParser()).parse(searchText).toXCQL(0);
                    java.util.Hashtable hs = new java.util.Hashtable();
                    java.util.Vector v1 = new java.util.Vector();
                    if (session.getAttribute("searchLimits") != null) {
                        hs = (java.util.Hashtable) session.getAttribute("searchLimits");
                    }
                    Vector vec = new Vector();
                    String solrQuery = Utility.getInstance().simplifiedSolrQuery(classificNo, "classificationNumber");
                    if (limitsSet.equalsIgnoreCase("SET")) {
                        String limitsQuery = limitsSolrQuery(hs);
                        solrQuery += limitsQuery;
                    }
                    solrQuery += " & ";
                    Vector newRetvec = searchCat.processSolrQuery(1, 25, solrQuery, "245_Tag", "asc");
                    Hashtable ht = (Hashtable) newRetvec.get(0);
                    String totrec = (String) ht.get("HITS");
                    session.setAttribute("TOTALREC", Integer.parseInt(totrec));
                    v1 = (Vector) ht.get("RESULTS");
                    hs.put("Query", solrQuery);
                    if (v1.size() > 0) {
                        hs.put("searchText", rawSearchText);
                        hs.put("noOfRecords", 25);
                        hs.put("browseType", "Classification Number");
                        session.setAttribute("searchEntry", hs);
                        session.setAttribute("searchVec", v1);
                        forward = "searchRes";
                    } else {
                        forward = "home";
                    }
                } else {
                    System.out.println("ELSE CALLED ");
                    String record = request.getParameter("record");
                    String recNo = request.getParameter("recNo");
                    Integer catId = 0, ownerId = 0;
                    String title = "";
                    if (request.getParameter("CatId") != null && request.getParameter("OwnerId") != null) {
                        catId = new Integer(request.getParameter("CatId")).intValue();
                        ownerId = new Integer(request.getParameter("OwnerId")).intValue();
                        System.out.println("catId is +++=" + catId);
                        System.out.println("OwnerId is +++=" + ownerId);
                        title = request.getParameter("title");
                        svF.setCatalogueRecordId(request.getParameter("CatId"));
                        svF.setOwnerLibraryId(request.getParameter("OwnerId"));
                    }
                    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%VVVVVVVVVVVVVVVVVVVVVV");
                    ArrayList alOtherBooks = ((ejb.bprocess.opac.SearchCatalogue) ejb.bprocess.util.HomeFactory.getInstance().getHome("SearchCatalogue")).getOtherBooksInTheRack(null, catId.toString(), ownerId.toString(), ownerId.toString());
                    System.out.println("alOtherBooks size is  " + alOtherBooks.size());
                    Vector vOtherBooks = new Vector();
                    Session catrecsession = DBConnector.getInstance().getSession();
                    utility = ejb.bprocess.util.Utility.getInstance(catrecsession);
                    for (int i = 0; i < alOtherBooks.size(); i++) {
                        String[] scData = (String[]) (alOtherBooks.get(i));
                        String catalogueId = scData[0];
                        String ownerLibId = scData[1];
                        System.out.println("catId is +++=" + catalogueId);
                        System.out.println("OwnerId is +++=" + ownerLibId);
                        String xmlWholeRecord = "";
                        String titleD = "";
                        String titleV = "";
                        String authorV = "";
                        String isbnNumber = "";
                        if (catalogueId != null && ownerLibId != null) {
                            try {
                                System.out.println("***************************** 0");
                                Hashtable htDetails = utility.getCatalogueRecord(new Integer(catalogueId), new Integer(ownerLibId));
                                System.out.println("***************************** 1");
                                if (htDetails != null && !htDetails.isEmpty()) {
                                    System.out.println("htDetails" + htDetails.toString());
                                    titleV = utility.getTestedString(htDetails.get("Title"));
                                    authorV = utility.getTestedString(htDetails.get("Author"));
                                    isbnNumber = utility.getTestedString(htDetails.get("ISBN"));
                                    String[] str1 = titleV.split("/");
                                    if (str1.length > 0) {
                                        titleD = str1[0];
                                        if (titleD.length() > 45) {
                                            titleD = titleD.substring(0, 45) + "...";
                                        }
                                    }
                                    String[] str = new String[5];
                                    str[0] = titleD;
                                    str[1] = authorV;
                                    str[2] = isbnNumber;
                                    str[3] = catalogueId;
                                    str[4] = ownerLibId;
                                    vOtherBooks.add(str);
                                    System.out.println("Other Books size is " + vOtherBooks.size());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    System.out.println("Other Books vector is *************************** \n ");
                    for (int i = 0; i < vOtherBooks.size(); i++) {
                        String[] str = (String[]) vOtherBooks.get(i);
                        System.out.println("title   :" + str[0].toString());
                        System.out.println("author  :" + str[1].toString());
                        System.out.println("isbn  :" + str[2].toString());
                        System.out.println("catID  :" + str[3].toString());
                        System.out.println("ownerLibId  :" + str[4].toString());
                    }
                    System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
                    request.setAttribute("fisheyedata", vOtherBooks);
                    catrecsession.close();
                    session.setAttribute("SingleViewExport", vecThisPage);
                    if (session.getAttribute("OnlySingleRec") != null && session.getAttribute("OnlySingleRec").toString().equals("true")) {
                        java.util.Vector v1 = new java.util.Vector();
                        System.out.println("SEARCH MODE " + searchmode);
                        if (searchmode.equalsIgnoreCase("a")) {
                            System.out.println("SEARCHMODE IN SEARCH VIEW ACTION (IF) " + searchmode);
                            v1 = (java.util.Vector) request.getAttribute("LuceneVector");
                            System.out.println("VECTOR V1 " + v1);
                        } else {
                            System.out.println("SEARCHMODE IN SEARCH VIEW ACTION (ELSE)" + searchmode);
                            v1 = (java.util.Vector) session.getAttribute("searchVec");
                        }
                        Object[] obj = (Object[]) v1.elementAt(0);
                        String str[] = (String[]) obj[0];
                        java.util.Hashtable h = new java.util.Hashtable();
                        String tit = "";
                        h = (java.util.Hashtable) obj[1];
                        System.out.println("HASH TABLE in view action " + h);
                        catId = new Integer(str[0]).intValue();
                        ownerId = new Integer(str[1]).intValue();
                        title = h.get("TITLE").toString();
                        svF.setAttachmentsAndUrl("");
                        if ((h.get("ATTACHMENTS") != null && h.get("ATTACHMENTS").equals("AVAILABLE"))) {
                            svF.setAttachmentsAndUrl("available");
                        }
                        record = "full";
                        recNo = "1";
                        session.removeAttribute("OnlySingleRec");
                    }
                    if (session.getAttribute("HostItemDisplay") != null && session.getAttribute("HostItemDisplay").equals("false")) {
                        session.removeAttribute("HostItemDisplay");
                    }
                    session.setAttribute("Title", title);
                    java.util.Hashtable hash1 = opacUt.getDetailsForSingleCatalogueRecord(catId, ownerId);
                    vecThisPage.addElement(String.valueOf(catId));
                    vecThisPage.addElement(String.valueOf(ownerId));
                    svF.setAttachmentsAndUrl("");
                    if (hash1.get("ATTACHMENTS") != null && hash1.get("ATTACHMENTS").toString().equals("AVAILABLE")) {
                        svF.setAttachmentsAndUrl("available");
                    }
                    svF.setRecordNo(recNo);
                    session.setAttribute("record", record);
                    java.util.Vector vecCO = (java.util.Vector) session.getAttribute("CatAndOwner");
                    svF.setCatCur(catId);
                    svF.setOwnerCur(ownerId);
                    svF.setPrevExists("no");
                    svF.setNextExists("no");
                    if (vecCO != null) {
                        for (int j = 0; j < vecCO.size(); j = j + 4) {
                            int c = new Integer(vecCO.elementAt(j).toString()).intValue();
                            int o = new Integer(vecCO.elementAt(j + 1).toString()).intValue();
                            if (c == catId && o == ownerId) {
                                if (j != 0) {
                                    int catPrev = new Integer(vecCO.elementAt(j - 4).toString()).intValue();
                                    int ownerPrev = new Integer(vecCO.elementAt(j - 3).toString()).intValue();
                                    svF.setCatPrev(catPrev);
                                    svF.setOwnerPrev(ownerPrev);
                                    svF.setTitlePrev(vecCO.elementAt(j - 2).toString());
                                    svF.setRecPrev(vecCO.elementAt(j - 1).toString());
                                    svF.setPrevExists("yes");
                                }
                                if (j < vecCO.size() - 4) {
                                    int catNext = new Integer(vecCO.elementAt(j + 4).toString()).intValue();
                                    int ownerNext = new Integer(vecCO.elementAt(j + 5).toString()).intValue();
                                    svF.setCatNext(catNext);
                                    svF.setOwnerNext(ownerNext);
                                    svF.setTitleNext(vecCO.elementAt(j + 6).toString());
                                    svF.setRecNext(vecCO.elementAt(j + 7).toString());
                                    svF.setNextExists("yes");
                                }
                            }
                        }
                    }
                    String str[] = (String[]) hash1.get("Biblo_Mat");
                    int bib_id = new Integer(str[0]).intValue();
                    int mat_id = new Integer(str[1]).intValue();
                    aportal.view.RecordView rv = new aportal.view.DesignFactory().getCorView(bib_id, mat_id, record);
                    String type = "";
                    if (bib_id == 3 && mat_id == 1) {
                        type = "Book";
                    } else if (bib_id == 4 && mat_id == 1) {
                        type = "Serial";
                    } else if (bib_id == 1 && mat_id == 1) {
                        type = "Book Chapter";
                    } else if (bib_id == 2 && mat_id == 1) {
                        type = "Serial Article";
                    } else {
                        type = ejb.bprocess.util.TypeDefinition.getInstance().getTypeDefinition(String.valueOf(bib_id), String.valueOf(mat_id));
                    }
                    java.util.Hashtable hMono = (java.util.Hashtable) hash1.get("MonoGraphRecords");
                    java.util.Hashtable h4 = rv.getView(hash1);
                    h4.put("Type", type);
                    Hashtable ht = (Hashtable) h4.get("NoLink");
                    if (ht != null && ht.get("URLS_856") != null) {
                        Vector urls856 = (Vector) ht.get("URLS_856");
                        if (urls856.size() > 0) {
                            Hashtable linksAndText = new Hashtable();
                            Hashtable url856 = new Hashtable();
                            for (int i = 0; i < urls856.size(); i += 2) {
                                url856.put(urls856.elementAt(i), urls856.elementAt(i + 1));
                            }
                            linksAndText.put("URL", url856);
                            h4.put("URLS_856", linksAndText);
                        }
                    }
                    try {
                        String sessionid = request.getSession().getId();
                        ejb.bprocess.holdings.HoldingsStatement holdingsStatement = ((ejb.bprocess.holdings.HoldingsStatementHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("HoldingsStatement")).create();
                        java.util.Vector vecLib = new java.util.Vector();
                        vecLib.addElement("1");
                        if (session.getAttribute("Libraries") != null) {
                            vecLib = (java.util.Vector) session.getAttribute("Libraries");
                        }
                        String libIds = "";
                        for (int p = 0; p < vecLib.size(); p++) {
                            if (p != 0) {
                                libIds += ",";
                            }
                            String libName = vecLib.elementAt(p).toString();
                            Session session1 = DBConnector.getInstance().getSession();
                            libIds += ejb.bprocess.util.Utility.getInstance(session1).getLibraryId(libName);
                            session1.close();
                        }
                        request.setAttribute("catRecId", String.valueOf(catId));
                        request.setAttribute("ownLibId", String.valueOf(ownerId));
                        request.setAttribute("libIds", String.valueOf(libIds));
                        Hashtable onerecordattach = new Hashtable();
                        JSONObject jsonCatOwnId = new JSONObject().put("Id", catId).put("LibId", ownerId);
                        ejb.bprocess.opac.SearchCatalogue searchCatAttach = ((ejb.bprocess.opac.SearchCatalogueHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("SearchCatalogue")).create();
                        String strAttach = searchCatAttach.getAttachmentDetails(jsonCatOwnId.toString());
                        if (!strAttach.equals("")) {
                            JSONObject jsonAttach = new JSONObject(strAttach);
                            if (jsonAttach != null) {
                                if (!jsonAttach.isNull("BookCover")) {
                                    ArrayList albookcover = new ArrayList();
                                    JSONArray jsonarr = (JSONArray) jsonAttach.get("BookCover");
                                    if (jsonarr != null) {
                                        for (int j = 0; j < jsonarr.length(); j++) {
                                            albookcover.add(jsonarr.getString(j));
                                        }
                                        onerecordattach.put("BookCover", albookcover);
                                    }
                                }
                                if (!jsonAttach.isNull("TOC")) {
                                    ArrayList alTOC = new ArrayList();
                                    JSONArray jsonarr = (JSONArray) jsonAttach.get("TOC");
                                    if (jsonarr != null) {
                                        for (int j = 0; j < jsonarr.length(); j++) {
                                            alTOC.add(jsonarr.getString(j));
                                        }
                                        onerecordattach.put("TOC", alTOC);
                                    }
                                }
                                if (!jsonAttach.isNull("Preview")) {
                                    ArrayList alPreview = new ArrayList();
                                    JSONArray jsonarr = (JSONArray) jsonAttach.get("Preview");
                                    if (jsonarr != null) {
                                        for (int j = 0; j < jsonarr.length(); j++) {
                                            alPreview.add(jsonarr.getString(j));
                                        }
                                        onerecordattach.put("Preview", alPreview);
                                    }
                                }
                                if (!jsonAttach.isNull("FullView")) {
                                    ArrayList alFullView = new ArrayList();
                                    JSONArray jsonarr = (JSONArray) jsonAttach.get("FullView");
                                    if (jsonarr != null) {
                                        for (int j = 0; j < jsonarr.length(); j++) {
                                            alFullView.add(jsonarr.getString(j));
                                        }
                                        onerecordattach.put("FullView", alFullView);
                                    }
                                }
                                if (!jsonAttach.isNull("Attachment")) {
                                    ArrayList alAttachment = new ArrayList();
                                    JSONArray jsonarr = (JSONArray) jsonAttach.get("Attachment");
                                    if (jsonarr != null) {
                                        for (int j = 0; j < jsonarr.length(); j++) {
                                            alAttachment.add(jsonarr.getString(j));
                                        }
                                        onerecordattach.put("Attachment", alAttachment);
                                    }
                                }
                                if (onerecordattach != null && !onerecordattach.isEmpty()) {
                                    h4.put("dAttachment", onerecordattach);
                                }
                            }
                        }
                        svF.setHashSing(h4);
                        System.out.println("hash tabel values*************************");
                        Enumeration enumx = h4.keys();
                        while (enumx.hasMoreElements()) {
                            String key = enumx.nextElement().toString();
                            System.out.println("Key: " + key + "-----value: " + h4.get(key));
                        }
                        System.out.println("********************************************");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (svF.getExportRec() != null && svF.getExportRec().equals("export")) {
            svF.setExportRec(null);
            vecThisPage = (java.util.Vector) session.getAttribute("SingleViewExport");
            String format = svF.getSf();
            if (format.equals("marc")) {
                String marc = opacUt.getDetailsForMultiRecordViewMARC(vecThisPage);
                svF.setDisplayFormat(marc);
                session.setAttribute("RecordDisplay", marc);
                forward = "RecordFormat";
            } else if (format.equals("marcXml")) {
                String marcXML = opacUt.getDetailsForMultiRecordViewMARCXML(vecThisPage);
                svF.setDisplayFormat(marcXML);
                response.setContentType("text/xml");
                session.setAttribute("RecordDisplay", marcXML);
                forward = "RecordFormat";
            } else if (format.equals("mods")) {
                String mods = opacUt.getDetailsForMultiRecordViewMODS(vecThisPage);
                svF.setDisplayFormat(mods);
                session.setAttribute("RecordDisplay", mods);
                forward = "RecordFormat";
            } else if (format.equals("dc")) {
                String dc = opacUt.getDetailsForMultiRecordViewDublinCore(vecThisPage);
                svF.setDisplayFormat(dc);
                session.setAttribute("RecordDisplay", dc);
                forward = "RecordFormat";
            } else if (format.equals("agris")) {
                String agr = opacUt.getDetailsForMultiRecordViewAgris(vecThisPage);
                svF.setDisplayFormat(agr);
                session.setAttribute("RecordDisplay", agr);
                forward = "RecordFormat";
            } else if (format.equals("text")) {
                java.util.Vector vecTextDis = new java.util.Vector();
                for (int i2 = 0; i2 < vecThisPage.size(); i2 = i2 + 2) {
                    java.util.Hashtable hash1 = opacUt.getDetailsForSingleCatalogueRecord(new Integer(vecThisPage.elementAt(i2).toString()).intValue(), new Integer(vecThisPage.elementAt(i2 + 1).toString()).intValue());
                    aportal.view.ISBDView fullView = new aportal.view.ISBDView();
                    java.util.Hashtable hashCit = fullView.getView(hash1);
                    vecTextDis.addElement(hashCit);
                    forward = "RecordFormatText";
                }
                session.setAttribute("RecordTextDisplay", vecTextDis);
                if (svF.getPs() != null && svF.getPs().equals("email")) {
                    boolean flag = false;
                    if (svF.getEmail() != null && !(svF.getEmail().equals(""))) {
                        String emailId = svF.getEmail();
                        try {
                            String sessionid = request.getSession().getId();
                            java.net.URL url = new java.net.URL("http://localhost:" + request.getServerPort() + "/newgenlibctxt/jsp/aportal/cataloguing/RecordDisplayText.jsp;jsessionid=" + sessionid);
                            java.net.URLConnection urlCon = url.openConnection();
                            java.io.InputStream is = urlCon.getInputStream();
                            String htmlContent = "";
                            java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(is));
                            String line = "";
                            while ((line = br.readLine()) != null) {
                                htmlContent = htmlContent + line;
                            }
                            String[] emailids = { emailId };
                            int status = SendEmail.getInstance().sendMail(emailids, "OPAC results", htmlContent, "html");
                            if (status == 0) flag = true; else flag = false;
                        } catch (Exception exp) {
                            exp.printStackTrace();
                        }
                    }
                    String mailMessage = "The selected records have been successfully mailed to " + svF.getEmail();
                    if (flag == false) {
                        mailMessage = "<h4><p>The selected records could not be mailed to " + svF.getEmail() + "  These might be the possible reasons.</p></h4>" + "<h5><ol> <li>The email id entered is not a valid one</font></li>" + "<li>The email id domain might not be in the list of allowed  recipient  hosts</li>" + "<li>There might a error in connectivity to the mail server</li></ol></h5>" + "<h4><p>Please contact the  Network Administrator </p></h4>";
                    }
                    session.setAttribute("MailStatus", mailMessage);
                    forward = "SendEmail";
                }
            }
        }
        String version = ejb.bprocess.util.StaticValues.getInstance().getVersion();
        if (version != null && !version.equals("")) {
            svF.setVersion(version);
        }
        if (session.getAttribute("ClassNoForwarded") != null) {
            session.removeAttribute("ClassNoForwarded");
        }
        return mapping.findForward(forward);
    }


    @Override
    public byte[] download(URI uri) throws NetworkException {
        log.info("download: " + uri);
        HttpGet httpGet = new HttpGet(uri.toString());
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            return EntityUtils.toByteArray(httpResponse.getEntity());
        } catch (IOException e) {
            throw new NetworkException(e);
        } finally {
            httpGet.abort();
        }
    }


    public static void sendData(final HashMap<String, String> data) {
        YProgressWindowRepeat y = new YProgressWindowRepeat(I18N.t("Send Data to yaams.de"));
        try {
            final StringBuffer send = new StringBuffer("1=1");
            for (final String key : data.keySet()) {
                send.append("&");
                send.append(key);
                send.append("=");
                send.append(URLEncoder.encode(data.get(key), "UTF-8"));
            }
            final URL url = new URL("http://www.rpg-studio.de/libraries/abttools/yaamsFeedback.php");
            final URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(send.toString());
            wr.flush();
            final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            final StringBuffer erg = new StringBuffer("");
            while ((line = rd.readLine()) != null) {
                erg.append(line);
            }
            JOptionPane.showMessageDialog(null, erg.toString(), I18N.t("Feedback"), JOptionPane.INFORMATION_MESSAGE);
            wr.close();
            rd.close();
        } catch (final Throwable t) {
            YException.error("Can not send feedback to http://www.rpg-studio.de/libraries/abttools/yaamsFeedback.php", t);
        }
        y.close();
    }


    public static String ftpPing(String root, String host, int port, String username, String pw) {
        try {
            ftpClient = new FTPClient();
            ftpClient.setRemoteAddr(InetAddress.getByName(host));
            ftpClient.setControlPort(port);
            ftpClient.setTimeout(4000);
            ftpClient.connect();
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ftpClient.login(username, (pw));
            ftpClient.chdir(root);
            JobHandler.releaseFTPLock();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return e.getMessage();
        } catch (FTPException e) {
            e.printStackTrace();
            return e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        try {
            ftpClient.quit();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        } catch (FTPException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return null;
    }


    public static void putWithUserSettings(String from, String to, String renameTo, boolean binary, IProgressMonitor monitor) {
        if (monitor != null && monitor.isCanceled()) {
            return;
        }
        FTPHolder ftpHolder = new FTPHolder(from, to, renameTo, binary);
        synchedSet.add(ftpHolder);
        int ftpqueuesize = PrefPageOne.getIntValue(CONSTANTS.PREF_FTPQUEUE);
        if (synchedSet.size() >= ftpqueuesize) {
            JobHandler.aquireFTPLock();
            try {
                ftpClient = new FTPClient();
                ftpClient.setRemoteAddr(InetAddress.getByName(PrefPageOne.getValue(CONSTANTS.PREF_HOST)));
                ftpClient.setControlPort(PrefPageOne.getIntValue(CONSTANTS.PREF_FTPPORT));
                ftpClient.connect();
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ftpClient.login((PrefPageOne.getValue(CONSTANTS.PREF_USERNAME)), FTPUtils.decrypt(PrefPageOne.getValue(CONSTANTS.PREF_PASSWORD)));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (monitor != null && monitor.isCanceled()) {
                    JobHandler.releaseFTPLock();
                    ftpClient.quit();
                    return;
                }
                synchronized (synchedSet) {
                    for (Iterator iter = synchedSet.iterator(); iter.hasNext(); ) {
                        if (monitor != null && monitor.isCanceled()) {
                            JobHandler.releaseFTPLock();
                            ftpClient.quit();
                            return;
                        }
                        Thread.yield();
                        FTPHolder element = (FTPHolder) iter.next();
                        if (element.binary) {
                            ftpClient.setType(FTPTransferType.BINARY);
                        } else {
                            ftpClient.setType(FTPTransferType.ASCII);
                        }
                        ftpClient.put(element.from, element.to);
                        if (element.renameTo != null) {
                            try {
                                ftpClient.delete(element.renameTo);
                            } catch (Exception e) {
                            }
                            ftpClient.rename(element.to, element.renameTo);
                            log.info("RENAME: " + element.to + "To: " + element.renameTo);
                        }
                    }
                    synchedSet.clear();
                }
                JobHandler.releaseFTPLock();
                ftpClient.quit();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (FTPException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void polishOff(IProgressMonitor monitor, String from, String to, String renameTo) {
        if (monitor != null && monitor.isCanceled()) {
            return;
        }
        try {
            ftpClient = new FTPClient();
            ftpClient.setRemoteAddr(InetAddress.getByName(PrefPageOne.getValue(CONSTANTS.PREF_HOST)));
            ftpClient.setControlPort(PrefPageOne.getIntValue(CONSTANTS.PREF_FTPPORT));
            ftpClient.connect();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ftpClient.login((PrefPageOne.getValue(CONSTANTS.PREF_USERNAME)), FTPUtils.decrypt(PrefPageOne.getValue(CONSTANTS.PREF_PASSWORD)));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (from != null) {
                FTPHolder ftpHolder = new FTPHolder(from, to, renameTo, false);
                synchedSet.add(ftpHolder);
            }
            JobHandler.aquireFTPLock();
            for (Iterator iter = synchedSet.iterator(); iter.hasNext(); ) {
                if (monitor != null && monitor.isCanceled()) {
                    JobHandler.releaseFTPLock();
                    ftpClient.quit();
                    return;
                }
                Thread.yield();
                FTPHolder element = (FTPHolder) iter.next();
                ftpClient.setType(FTPTransferType.ASCII);
                ftpClient.put(element.from, element.to);
                if (element.renameTo != null) {
                    try {
                        ftpClient.delete(element.renameTo);
                    } catch (Exception e) {
                    }
                    ftpClient.rename(element.to, element.renameTo);
                    log.info("RENAME: " + element.to + "To: " + element.renameTo);
                }
            }
            JobHandler.releaseFTPLock();
            ftpClient.quit();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (FTPException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        synchedSet.clear();
    }


protected void generateDiffResults(File outFile) throws IOException {
        FileOutputStream outStream = new FileOutputStream(outFile);
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream, outputCharset));
        intlWrite(out, HTML_STRICT_DOCTYPE + "<title>${Report.Title}</title>\n" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; charset=" + outputCharset + "\">\n" + "\n" + "\n" + "
\n");
        if (addedTable.length() > 0) {
            out.write("
");
            intlWrite(out, getAddedTableHeader());
            out.write(addedTable.toString());
            out.write("

");
        }
        if (modifiedTable.length() > 0) {
            out.write("
");
            intlWrite(out, getModifiedTableHeader());
            out.write(modifiedTable.toString());
            out.write("

");
        }
        if (deletedTable.length() > 0) {
            out.write("
");
            intlWrite(out, getDeletedTableHeader());
            out.write(deletedTable.toString());
            out.write("

");
        }
        if (unchangedTable.length() > 0) {
            out.write("
");
            intlWrite(out, getUnchangedTableHeader());
            out.write(unchangedTable.toString());
            out.write("

");
        }
        writeSummaryTable(out);
        out.write("
");
        redlinesOut.close();
        out.flush();
        InputStream redlines = new FileInputStream(redlinesTempFile);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead);
        outStream.write("".getBytes());
        outStream.close();
    }


    public String openFileAsText(String resource) throws IOException {
        StringWriter wtr = new StringWriter();
        InputStreamReader rdr = new InputStreamReader(openFile(resource));
        try {
            IOUtils.copy(rdr, wtr);
        } finally {
            IOUtils.closeQuietly(rdr);
        }
        return wtr.toString();
    }


    public void writeFile(String resource, InputStream is) throws IOException {
        File f = prepareFsReferenceAsFile(resource);
        FileOutputStream fos = new FileOutputStream(f);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        try {
            IOUtils.copy(is, bos);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(bos);
        }
    }


    public String postEvent(EventDocument eventDoc, Map attachments) {
        if (eventDoc == null || eventDoc.getEvent() == null) return null;
        if (queue == null) {
            sendEvent(eventDoc, attachments);
            return eventDoc.getEvent().getEventId();
        }
        if (attachments != null) {
            Iterator iter = attachments.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                if (entry.getValue() instanceof DataHandler) {
                    File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey());
                    try {
                        IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file));
                        entry.setValue(file);
                    } catch (IOException err) {
                        err.printStackTrace();
                    }
                }
            }
        }
        InternalEventObject eventObj = new InternalEventObject();
        eventObj.setEventDocument(eventDoc);
        eventObj.setAttachments(attachments);
        eventObj.setSessionContext(SessionContextUtil.getCurrentContext());
        eventDoc.getEvent().setEventId(GuidUtil.generate());
        getQueue().post(eventObj);
        return eventDoc.getEvent().getEventId();
    }


    public ActionResponse executeAction(ActionRequest request) throws Exception {
        ActionResponse resp = new ActionResponse();
        BufferedReader in = null;
        try {
            URL url = new URL(URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            int status = conn.getResponseCode();
            if (status == 200) {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while (true) {
                    String line = in.readLine();
                    if (line == null) break;
                    resp.addResult("REMOTEVERSION", line);
                }
            } else {
                resp.setErrorCode(ActionResponse.GENERAL_ERROR);
                resp.setErrorMessage("HTTP Error [" + status + "]");
            }
        } catch (Exception e) {
            resp.setErrorCode(ActionResponse.GENERAL_ERROR);
            resp.setErrorMessage(e.getMessage());
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return resp;
    }


    static boolean writeProperties(Map<String, String> customProps, File destination) throws IOException {
        synchronized (PropertiesIO.class) {
            L.info(Msg.msg("PropertiesIO.writeProperties.start"));
            File tempFile = null;
            BufferedInputStream existingCfgInStream = null;
            FileInputStream in = null;
            FileOutputStream out = null;
            PrintStream ps = null;
            FileChannel fromChannel = null, toChannel = null;
            String line = null;
            try {
                existingCfgInStream = new BufferedInputStream(destination.exists() ? new FileInputStream(destination) : defaultPropertiesStream());
                tempFile = File.createTempFile("properties-", ".tmp", null);
                ps = new PrintStream(tempFile);
                while ((line = Utils.readLine(existingCfgInStream)) != null) {
                    String lineReady2write = setupLine(line, customProps);
                    ps.println(lineReady2write);
                }
                destination.getParentFile().mkdirs();
                in = new FileInputStream(tempFile);
                out = new FileOutputStream(destination, false);
                fromChannel = in.getChannel();
                toChannel = out.getChannel();
                fromChannel.transferTo(0, fromChannel.size(), toChannel);
                L.info(Msg.msg("PropertiesIO.writeProperties.done").replace("#file#", destination.getAbsolutePath()));
                return true;
            } finally {
                if (existingCfgInStream != null) existingCfgInStream.close();
                if (ps != null) ps.close();
                if (fromChannel != null) fromChannel.close();
                if (toChannel != null) toChannel.close();
                if (out != null) out.close();
                if (in != null) in.close();
                if (tempFile != null && tempFile.exists()) tempFile.delete();
            }
        }
    }


    private void writeGif(String filename, String outputFile) throws IOException {
        File file = new File(filename);
        InputStream in = new FileInputStream(file);
        FileOutputStream fout = new FileOutputStream(outputFile);
        int totalRead = 0;
        int readBytes = 0;
        int blockSize = 65000;
        long fileLen = file.length();
        byte b[] = new byte[blockSize];
        while ((long) totalRead < fileLen) {
            readBytes = in.read(b, 0, blockSize);
            totalRead += readBytes;
            fout.write(b, 0, readBytes);
        }
        in.close();
        fout.close();
    }


    @Override
    public void alterar(Disciplina t) throws Exception {
        PreparedStatement stmt = null;
        String sql = "UPDATE disciplina SET nm_disciplina = ?, cod_disciplina = ? WHERE id_disciplina = ?";
        try {
            stmt = conexao.prepareStatement(sql);
            stmt.setString(1, t.getNomeDisciplina());
            stmt.setString(2, t.getCodDisciplina());
            stmt.setInt(3, t.getIdDisciplina());
            stmt.executeUpdate();
            conexao.commit();
            int id_disciplina = t.getIdDisciplina();
            excluirTopico(t.getIdDisciplina());
            for (Topico item : t.getTopicos()) {
                criarTopico(item, id_disciplina);
            }
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        }
    }


    @Override
    public void excluir(Disciplina t) throws Exception {
        PreparedStatement stmt = null;
        String sql = "DELETE from disciplina where id_disciplina = ?";
        try {
            stmt = conexao.prepareStatement(sql);
            stmt.setInt(1, t.getIdDisciplina());
            stmt.executeUpdate();
            conexao.commit();
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        } finally {
            try {
                stmt.close();
                conexao.close();
            } catch (SQLException e) {
                throw e;
            }
        }
    }


    public void excluirTopico(Integer idDisciplina) throws Exception {
        String sql = "DELETE from topico WHERE id_disciplina = ?";
        PreparedStatement stmt = null;
        try {
            stmt = conexao.prepareStatement(sql);
            stmt.setInt(1, idDisciplina);
            stmt.executeUpdate();
            conexao.commit();
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        }
    }


    private void removeSessionId(InputStream inputStream, Output output) throws IOException {
        String jsessionid = RewriteUtils.getSessionId(target);
        boolean textContentType = ResourceUtils.isTextContentType(httpClientResponse.getHeader(HttpHeaders.CONTENT_TYPE), target.getDriver().getConfiguration().getParsableContentTypes());
        if (jsessionid == null || !textContentType) {
            IOUtils.copy(inputStream, output.getOutputStream());
        } else {
            String charset = httpClientResponse.getContentCharset();
            if (charset == null) {
                charset = "ISO-8859-1";
            }
            String content = IOUtils.toString(inputStream, charset);
            content = removeSessionId(jsessionid, content);
            if (output.getHeader(HttpHeaders.CONTENT_LENGTH) != null) {
                output.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(content.length()));
            }
            OutputStream outputStream = output.getOutputStream();
            IOUtils.write(content, outputStream, charset);
        }
        inputStream.close();
    }


        public ViewProperties(String basePath, String baseFile) throws Exception {
            FileInputStream input = null;
            String file = basePath + "/" + baseFile + ".properties";
            properties = new Properties();
            try {
                URL url = MapViewer.class.getResource(file);
                properties.load(url.openStream());
                viewName = (String) properties.get("view.name");
                viewShape = (String) properties.get("view.shape");
                path = basePath + "/" + (String) properties.get("icon.path");
                iconHeight = getIntProperty("icon.height", 96);
                iconWidth = getIntProperty("icon.width", 96);
                fontSizeSmall = getIntProperty("font.small.size", 10);
                fontSizeMedium = getIntProperty("font.medium.size", 12);
                fontSizeLarge = getIntProperty("font.large.size", 16);
                fontSizeHuge = getIntProperty("font.huge.size", 20);
                if (viewShape.equals("Hexagonal")) {
                    tileHeight = (int) (Math.sqrt(3.0) / 2.0 * iconWidth);
                    tileWidth = (int) (iconWidth * 3.0 / 4.0);
                    tileOffset = (int) (tileHeight / 2.0);
                } else {
                    tileHeight = iconHeight;
                    tileWidth = iconWidth;
                    tileOffset = 0;
                }
            } catch (Exception e) {
                error("Cannot load properties from file [" + file + "]");
                throw e;
            }
        }


    private void write(File src, File dst, byte id3v1Tag[], byte id3v2HeadTag[], byte id3v2TailTag[]) throws IOException {
        if (src == null || !src.exists()) throw new IOException(Debug.getDebug("missing src", src));
        if (!src.getName().toLowerCase().endsWith(".mp3")) throw new IOException(Debug.getDebug("src not mp3", src));
        if (dst == null) throw new IOException(Debug.getDebug("missing dst", dst));
        if (dst.exists()) {
            dst.delete();
            if (dst.exists()) throw new IOException(Debug.getDebug("could not delete dst", dst));
        }
        boolean hasId3v1 = new MyID3v1().hasID3v1(src);
        long id3v1Length = hasId3v1 ? ID3_V1_TAG_LENGTH : 0;
        long id3v2HeadLength = new MyID3v2().findID3v2HeadLength(src);
        long id3v2TailLength = new MyID3v2().findID3v2TailLength(src, hasId3v1);
        OutputStream os = null;
        InputStream is = null;
        try {
            dst.getParentFile().mkdirs();
            os = new FileOutputStream(dst);
            os = new BufferedOutputStream(os);
            if (!skipId3v2Head && !skipId3v2 && id3v2HeadTag != null) os.write(id3v2HeadTag);
            is = new FileInputStream(src);
            is = new BufferedInputStream(is);
            is.skip(id3v2HeadLength);
            long total_to_read = src.length();
            total_to_read -= id3v1Length;
            total_to_read -= id3v2HeadLength;
            total_to_read -= id3v2TailLength;
            byte buffer[] = new byte[1024];
            long total_read = 0;
            while (total_read < total_to_read) {
                int remainder = (int) (total_to_read - total_read);
                int readSize = Math.min(buffer.length, remainder);
                int read = is.read(buffer, 0, readSize);
                if (read <= 0) throw new IOException("unexpected EOF");
                os.write(buffer, 0, read);
                total_read += read;
            }
            if (!skipId3v2Tail && !skipId3v2 && id3v2TailTag != null) os.write(id3v2TailTag);
            if (!skipId3v1 && id3v1Tag != null) os.write(id3v1Tag);
        } finally {
            try {
                if (is != null) is.close();
            } catch (Throwable e) {
                Debug.debug(e);
            }
            try {
                if (os != null) os.close();
            } catch (Throwable e) {
                Debug.debug(e);
            }
        }
    }


    public Program createNewProgram(int projectID, String name, String description) throws AdaptationException {
        Program program = null;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DriverManager.getConnection(CONN_STR);
            connection.setAutoCommit(false);
            statement = connection.createStatement();
            String query = "INSERT INTO Programs(projectID, name, " + "description, sourcePath) VALUES ( " + projectID + ", " + "'" + name + "', " + "'" + description + "', " + "'" + "[unknown]" + "')";
            log.debug("SQL Query:\n" + query);
            statement.executeUpdate(query);
            query = "SELECT * FROM Programs WHERE " + " projectID   =  " + projectID + "  AND " + " name        = '" + name + "' AND " + " description = '" + description + "'";
            resultSet = statement.executeQuery(query);
            if (!resultSet.next()) {
                connection.rollback();
                String msg = "Attempt to create program failed";
                log.error(msg);
                throw new AdaptationException(msg);
            }
            program = getProgram(resultSet);
            connection.commit();
        } catch (SQLException ex) {
            try {
                connection.rollback();
            } catch (Exception e) {
            }
            String msg = "SQLException in createNewProgram";
            log.error(msg, ex);
            throw new AdaptationException(msg, ex);
        } finally {
            try {
                resultSet.close();
            } catch (Exception ex) {
            }
            try {
                statement.close();
            } catch (Exception ex) {
            }
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
        return program;
    }


    public Program updateProgramPath(int id, String sourcePath) throws AdaptationException {
        Program program = null;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            String query = "UPDATE Programs SET " + "sourcePath = '" + sourcePath + "' " + "WHERE id = " + id;
            connection = DriverManager.getConnection(CONN_STR);
            statement = connection.createStatement();
            statement.executeUpdate(query);
            query = "SELECT * from Programs WHERE id = " + id;
            resultSet = statement.executeQuery(query);
            if (!resultSet.next()) {
                connection.rollback();
                String msg = "Attempt to update program failed.";
                log.error(msg);
                throw new AdaptationException(msg);
            }
            program = getProgram(resultSet);
            connection.commit();
        } catch (SQLException ex) {
            try {
                connection.rollback();
            } catch (Exception e) {
            }
            String msg = "SQLException in updateProgramPath";
            log.error(msg, ex);
            throw new AdaptationException(msg, ex);
        } finally {
            try {
                resultSet.close();
            } catch (Exception ex) {
            }
            try {
                statement.close();
            } catch (Exception ex) {
            }
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
        return program;
    }


    public Program deleteProgram(int id) throws AdaptationException {
        Program program = null;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            String query = "SELECT * FROM Programs WHERE id = " + id;
            connection = DriverManager.getConnection(CONN_STR);
            statement = connection.createStatement();
            resultSet = statement.executeQuery(query);
            if (!resultSet.next()) {
                connection.rollback();
                String msg = "Attempt to delete program failed.";
                log.error(msg);
                throw new AdaptationException(msg);
            }
            program = getProgram(resultSet);
            query = "DELETE FROM Programs WHERE id = " + id;
            statement.executeUpdate(query);
            connection.commit();
        } catch (SQLException ex) {
            try {
                connection.rollback();
            } catch (Exception e) {
            }
            String msg = "SQLException in deleteProgram";
            log.error(msg, ex);
            throw new AdaptationException(msg, ex);
        } finally {
            try {
                resultSet.close();
            } catch (Exception ex) {
            }
            try {
                statement.close();
            } catch (Exception ex) {
            }
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
        return program;
    }