Example usage for org.springframework.context.support ClassPathXmlApplicationContext close

List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext close

Introduction

In this page you can find the example usage for org.springframework.context.support ClassPathXmlApplicationContext close.

Prototype

@Override
public void close() 

Source Link

Document

Close this application context, destroying all beans in its bean factory.

Usage

From source file:com.hygenics.parser.MainApp.java

/**
 * The entire programs main method.//w w  w  . j a v a  2s .co  m
 * 
 * @param args
 */
public static void main(String[] args) {
    final Logger log = LoggerFactory.getLogger(MainApp.class);
    log.info("Starting Parse @ " + Calendar.getInstance().getTime().toString());

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            ("file:" + System.getProperty("beansfile").trim()));
    log.info("Found beans @ " + System.getProperty("beansfile").trim());
    log.info("Starting");
    ArrayList<String> results = null;

    String activity = null;
    log.info("Obtaining Activities");
    ActivitiesStack stack = (ActivitiesStack) context.getBean("ActivitiesStack");

    // integers keeping track of bean number to pull (e.g. DumpToText0 or
    // DumpToText1)
    // in keeping with the spirit of dumping out data
    int n = 0, srn = 0, mv = 0, cen = 0, pps = 0, sb = 0, kv = 0, cf = 0, zip = 0, bm = 0, dump = 0, kettle = 0,
            execute = 0, transfer = 0, sqls = 0, job = 0, parsepages = 0, getpages = 0, map = 0, js = 0,
            sdump = 0, transforms = 0, execs = 0, gim = 0, ems = 0, jd = 0;

    Pattern p = Pattern.compile("[A-Za-z]+[0-9]+");
    Matcher m;

    // start stack init
    log.info("Stack Initialized with Size of " + stack.getSize() + " @ "
            + Calendar.getInstance().getTime().toString());

    while (stack.getSize() > 0) {
        // pop activity form stack
        activity = stack.Pop();
        log.info("Activities Remaining " + stack.getSize());
        m = p.matcher(activity);

        log.info("\n\nACTIVITY: " + activity + "\n\n");
        if (activity.toLowerCase().contains("manualrepconn")) {
            log.info("Manual Transformation Started @ " + Calendar.getInstance().getTime().toString());
            ManualReplacement mrp = (ManualReplacement) context.getBean("ManualRepConn");
            mrp.run();
            log.info("Manual Transformation Finished @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("cleanfolder")) {
            log.info("Folder Cleanup Started @ " + Calendar.getInstance().getTime().toString());

            CleanFolder c;
            if (cf == 0 || context.containsBean("CleanFolder")) {
                c = (CleanFolder) ((context.containsBean("CleanFolder")) ? context.getBean("CleanFolder")
                        : context.getBean("CleanFolder" + cf));
            } else {
                c = (CleanFolder) context.getBean("CleanFolder" + cf);
            }
            c.run();
            cf++;
            log.info("File Cleanup Complete @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("zip")) {

            log.info("Zip File Creation Started @ " + Calendar.getInstance().getTime().toString());

            Archiver a;
            if (zip == 0 || context.containsBean("Zip")) {
                a = (Archiver) ((context.containsBean("Zip")) ? context.getBean("Zip")
                        : context.getBean("Zip" + zip));
            } else {
                a = (Archiver) context.getBean("Zip" + zip);
            }
            a.run();
            zip++;
            log.info("Zip File Creation Complete @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("transfer")) {
            log.info("File Transfer Started @ " + Calendar.getInstance().getTime().toString());

            Upload u;
            if (transfer == 0 || context.containsBean("FileTransfer")) {
                u = (Upload) ((context.containsBean("FileTransfer")) ? context.getBean("FileTransfer")
                        : context.getBean("FileTransfer" + transfer));
            } else {
                u = (Upload) context.getBean("FileTransfer" + transfer);
            }
            u.run();
            transfer++;
            log.info("File Transfer Complete @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("droptables")) {
            // drop tables
            log.info("Dropping Tables @ " + Calendar.getInstance().getTime().toString());

            DropTables droptables = (DropTables) context.getBean("DropTables");
            droptables.run();

            droptables = null;
            log.info("Done Dropping Tables @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().equals("createtables")) {
            // create tables
            log.info("Creating Tables @ " + Calendar.getInstance().getTime().toString());

            CreateTable create = (CreateTable) context.getBean("CreateTables");
            create.run();
            create = null;

            log.info("Done Creating Tables @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("createtableswithreference")) {
            // create tables
            log.info("Creating Tables @ " + Calendar.getInstance().getTime().toString());

            CreateTablesWithReference create = (CreateTablesWithReference) context
                    .getBean("CreateTablesWithReference");
            create.run();
            create = null;

            log.info("Done Creating Tables @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("truncate")) {
            // truncate table
            log.info("Truncating @ " + Calendar.getInstance().getTime().toString());
            Truncate truncate = (Truncate) context.getBean("Truncate");
            truncate.truncate();
            truncate = null;
            log.info("Truncated @ " + Calendar.getInstance().getTime().toString());
            Runtime.getRuntime().gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().equals("enforce")) {
            // enforce schema
            log.info("Enforcing Schema @" + Calendar.getInstance().getTime().toString());
            ForceConformity ef = (ForceConformity) context.getBean("EnforceStandards");
            ef.run();
            log.info("Done Enforcing Schema @" + Calendar.getInstance().getTime().toString());
            Runtime.getRuntime().gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().contains("enforcewithreference")) {
            // enforce schema
            ForceConformityWithReference ef = (ForceConformityWithReference) context
                    .getBean("EnforceStandardsWithReference");
            log.info("Enforcing Schema By Reference @" + Calendar.getInstance().getTime().toString());
            ef.run();
            log.info("Done Enforcing Schema @" + Calendar.getInstance().getTime().toString());
            Runtime.getRuntime().gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().trim().equals("repconn")) {
            log.info("Replacing Transformation Connection Information  @"
                    + Calendar.getInstance().getTime().toString());

            RepConn rep = (RepConn) context.getBean("repconn");
            rep.run();

            log.info("Finished Replacing Connection Information  @"
                    + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("job")) {
            // run a Pentaho job as opposed to a Pentaho Transformation
            log.info("Run Job kjb file @" + Calendar.getInstance().getTime().toString());

            RunJob kjb = null;

            if (m.find()) {
                kjb = (RunJob) context.getBean(activity);
            } else {
                kjb = (RunJob) context.getBean("Job" + job);
            }

            kjb.run();
            kjb = null;
            log.info("Pentaho Job Complete @" + Calendar.getInstance().getTime().toString());
            Runtime.getRuntime().gc();
        } else if (activity.toLowerCase().compareTo("execute") == 0) {
            // Execute a process
            log.info("Executing Process @" + Calendar.getInstance().getTime().toString());

            if (context.containsBean("Execute") && execs == 0) {
                ExecuteProcess proc = (ExecuteProcess) context.getBean(("Execute"));
                proc.Execute();
            } else {
                ExecuteProcess proc = (ExecuteProcess) context.getBean(("Execute" + execute));
                proc.Execute();
            }

            execs++;
            log.info("Pages Obtained @" + Calendar.getInstance().getTime().toString());
            Runtime.getRuntime().gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().contains("parsepageswithscala")
                || activity.toLowerCase().contains("parsepagesscala")) {
            //parse pages with scala
            log.info("Parsing Pages with Scala @ " + Calendar.getInstance().getTime().toString());
            ScalaParseDispatcher pds = null;
            if (context.containsBean("ParsePagesScala" + pps)) {
                pds = (ScalaParseDispatcher) context.getBean("ParsePagesScala" + pps);
            } else if (context.containsBean("ParsePagesScala") && pps > 0) {
                pds = (ScalaParseDispatcher) context.getBean("ParsePagesScala");
            }
            pps++;
            pds.run();
            Runtime.getRuntime().gc();
            log.info("Finished Parsing Pages with Scala @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("parsepages")) {

            // Parse Pages with java
            log.info("Parsing Individual Pages  @" + Calendar.getInstance().getTime().toString());
            if (context.containsBean("ParsePages") && parsepages == 0) {
                ParseDispatcher pd = (ParseDispatcher) context.getBean("ParsePages");
                pd.run();
                pd = null;
            } else {
                ParseDispatcher pd = (ParseDispatcher) context.getBean("ParsePages" + parsepages);
                pd.run();
                pd = null;
            }

            parsepages++;
            log.info("Finished Parsing @" + Calendar.getInstance().getTime().toString());
            Runtime.getRuntime().gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().contains("kvparser")) {
            // Parse Pages using the KV Parser
            log.info("Parsing Individual Pages with Key Value Pairs  @"
                    + Calendar.getInstance().getTime().toString());
            if (context.containsBean("KVParser") && parsepages == 0) {
                KVParser pd = (KVParser) context.getBean("KVParser");
                pd.run();
                pd = null;
            } else {
                KVParser pd = (KVParser) context.getBean("KVParser" + kv);
                pd.run();
                pd = null;
            }

            parsepages++;
            log.info("Finished Parsing @" + Calendar.getInstance().getTime().toString());
            Runtime.getRuntime().gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().contains("parsewithsoup")) {

            // Parse Pages with Jsoup
            log.info("Parsing Pages with JSoup @ " + Calendar.getInstance().getTime().toString());

            if (context.containsBean("ParseJSoup") && js == 0) {
                ParseJSoup psj = (ParseJSoup) context.getBean("ParseJSoup");
                psj.run();
            } else {
                ParseJSoup psj = (ParseJSoup) context.getBean("ParseJSoup" + Integer.toString(js));
                psj.run();
            }
            js++;
            log.info("Finished Parsing @" + Calendar.getInstance().getTime().toString());
            Runtime.getRuntime().gc();
            log.info("Finished Parsing with JSoup @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("breakmultiplescala")
                || activity.toLowerCase().contains("breakmultiplewithscala")) {
            log.info("Breaking Records");
            BreakMultipleScala bms = null;
            if (context.containsBean("BreakMultipleScala" + ems)) {
                bms = (BreakMultipleScala) context.getBean("BreakMultipleScala" + sb);
            } else {
                bms = (BreakMultipleScala) context.getBean("BreakMultipleScala");
            }
            bms.run();
            bms = null;
            sb++;
            Runtime.getRuntime().gc();
            System.gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
            log.info("Completed Breaking Tasks");
        } else if (activity.toLowerCase().contains("breakmultiple")) {

            // break apart multi-part records
            log.info("Breaking apart Records (BreakMultiple) @" + Calendar.getInstance().getTime().toString());

            if (context.containsBean("BreakMultiple") && bm == 0) {
                BreakMultiple br = (BreakMultiple) context.getBean(("BreakMultiple"));
                br.run();
                br = null;
            } else {
                BreakMultiple br = (BreakMultiple) context.getBean(("BreakMultiple" + Integer.toString(bm)));
                br.run();
                br = null;
            }
            bm++;

            log.info("Finished Breaking Apart Records @" + Calendar.getInstance().getTime().toString());
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().compareTo("mapper") == 0) {
            // remap data
            log.info("Mapping Records @" + Calendar.getInstance().getTime().toString());

            if (context.containsBean("Mapper") && map == 0) {
                Mapper mp = (Mapper) context.getBean("Mapper");
                mp.run();
                mp = null;
            } else {
                Mapper mp = (Mapper) context.getBean("Mapper" + Integer.toString(map));
                mp.run();
                mp = null;
            }
            map++;
            log.info("Completed Mapping Records @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("getimages")) {
            // Get Images in a Separate Step
            log.info("Beggining Image Pull @ " + Calendar.getInstance().getTime().toString());

            if (context.containsBean("getImages") && gim == 0) {
                GetImages gi = (GetImages) context.getBean("getImages");
                gi.run();
                log.info("Image Pull Complete @ " + Calendar.getInstance().getTime().toString());
                gi = null;
            } else {
                GetImages gi = (GetImages) context.getBean("getImages");
                gi.run();
                log.info("Image Pull Complete @ " + Calendar.getInstance().getTime().toString());
                gi = null;
            }
            gim++;
            Runtime.getRuntime().gc();
            System.gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());

        } else if (activity.toLowerCase().compareTo("sql") == 0) {
            // execute a sql command
            log.info("Executing SQL Query @ " + Calendar.getInstance().getTime().toString());

            if (context.containsBean("SQL") && sqls == 0) {
                ExecuteSQL sql;

                if (m.find()) {
                    sql = (ExecuteSQL) context.getBean(activity);
                } else {
                    sql = (ExecuteSQL) context.getBean("SQL");
                }

                sql.execute();
                sql = null;
            } else {

                ExecuteSQL sql;

                if (m.find()) {
                    sql = (ExecuteSQL) context.getBean(activity);
                } else {
                    sql = (ExecuteSQL) context.getBean("SQL" + sqls);
                }

                sql.execute();
                sql = null;
            }

            sqls++;

            log.info("Finished SQL Query @ " + Calendar.getInstance().getTime().toString());
            Runtime.getRuntime().gc();
            System.gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().compareTo("kettle") == 0) {
            // run one or more kettle transformation(s)
            log.info("Beginning Kettle Transformation @ " + Calendar.getInstance().getTime().toString());
            RunTransformation rt = null;

            if (context.containsBean("kettle") && transforms == 0) {
                if (m.find()) {
                    rt = (RunTransformation) context.getBean(activity);
                } else {
                    rt = (RunTransformation) context.getBean(("kettle"));
                }

                rt.run();
                rt = null;
            } else {
                if (m.find()) {
                    rt = (RunTransformation) context.getBean(activity);
                } else {
                    rt = (RunTransformation) context.getBean(("kettle" + kettle));
                }

                rt.run();
                rt = null;
            }
            transforms++;
            log.info("Ending Kettle Transformation @ " + Calendar.getInstance().getTime().toString());
            Runtime.getRuntime().gc();
            System.gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
            kettle++;
        } else if (activity.toLowerCase().contains("dumptotext")) {
            // dump to a text file via java
            log.info("Dumping to Text @ " + Calendar.getInstance().getTime().toString());

            DumptoText dtt = null;
            if (m.find()) {
                dtt = (DumptoText) context.getBean(activity);
            } else {
                dtt = (DumptoText) context.getBean("DumpToText" + dump);
            }

            dtt.run();
            dump++;
            log.info("Completed Dump @ " + Calendar.getInstance().getTime().toString());
            dtt = null;
            Runtime.getRuntime().gc();
            System.gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().equals("jdump")) {
            log.info("Dumping via JDump @ " + Calendar.getInstance().getTime().toString());
            if (jd == 0 && context.containsBean("JDump")) {
                JDump j = (JDump) context.getBean("JDump");
                jd++;
                j.run();
            } else {
                JDump j = (JDump) context.getBean("JDump" + jd);
                jd++;
                j.run();
            }
            Runtime.getRuntime().gc();
            System.gc();
            log.info("Finished Dumping via JDump @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("jdumpwithreference")) {
            log.info("Dumping via JDump @ " + Calendar.getInstance().getTime().toString());
            if (jd == 0 && context.containsBean("JDumpWithReference")) {
                JDumpWithReference j = (JDumpWithReference) context.getBean("JDumpWithReference");
                jd++;
                j.run();
            } else {
                JDumpWithReference j = (JDumpWithReference) context.getBean("JDumpWithReference" + jd);
                jd++;
                j.run();
            }
            Runtime.getRuntime().gc();
            System.gc();
            log.info("Finished Dumping via JDump @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().compareTo("commanddump") == 0) {

            // dump to text using a client side sql COPY TO command
            log.info("Dumping via SQL @ " + Calendar.getInstance().getTime().toString());
            CommandDump d = (CommandDump) context.getBean("dump");
            d.run();
            d = null;
            log.info("Completed Dump @ " + Calendar.getInstance().getTime().toString());
            // most likely not needed by satisfies my paranoia
            Runtime.getRuntime().gc();
            System.gc();
        } else if (activity.toLowerCase().equals("specdump")) {
            // Specified Dump
            log.info("Dumping via Specified Tables, Files, and Attributes @ "
                    + Calendar.getInstance().getTime().toString());

            if (context.containsBean("SpecDump") && sdump == 0) {
                sdump++;
                SpecifiedDump sd = (SpecifiedDump) context.getBean("SpecDump");
                sd.run();
                sd = null;
            } else if (context.containsBean("SpecDump" + Integer.toString(sdump))) {
                SpecifiedDump sd = (SpecifiedDump) context.getBean("SpecDump" + Integer.toString(sdump));
                sd.run();
                sd = null;
            }
            sdump++;
            log.info("Completed Dumping via Specified Tables, Files, and Attributes @ "
                    + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("specdumpwithreference")) {
            // Specified Dump
            log.info("Dumping via Specified Tables, Files, and Attributes by Reference @ "
                    + Calendar.getInstance().getTime().toString());

            if (context.containsBean("SpecDumpWithReference") && sdump == 0) {
                sdump++;
                SpecDumpWithReference sd = (SpecDumpWithReference) context.getBean("SpecDumpWithReference");
                sd.run();
                sd = null;
            } else if (context.containsBean("SpecDumpWithReference" + Integer.toString(sdump))) {
                SpecDumpWithReference sd = (SpecDumpWithReference) context
                        .getBean("SpecDumpWithReference" + Integer.toString(sdump));
                sd.run();
                sd = null;
            } else {
                log.info("Bean Not Found For " + activity);
            }
            sdump++;
            log.info("Completed Dumping via Specified Tables, Files, and Attributes @ "
                    + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().compareTo("email") == 0) {
            // email completion notice
            log.info("Sending Notice of Completion @ " + Calendar.getInstance().getTime().toString());

            if (context.containsBean("Email") && ems == 0) {
                Send s = (Send) context.getBean("Email");
                s.run();
                s = null;
            } else {
                Send s = (Send) context.getBean("Email" + Integer.toString(ems));
                s.run();
                s = null;
            }
            ems++;
            Runtime.getRuntime().gc();
            System.gc();
            log.info("Completed Email @ " + Calendar.getInstance().getTime().toString());
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().equals("qa")) {
            // perform qa
            log.info("Performing Quality Assurance @ " + Calendar.getInstance().getTime().toString());

            if (context.containsBean("QA")) {
                QualityAssurer qa = (QualityAssurer) context.getBean("QA");
                qa.run();
                qa = null;
            }

            // attempt to hint --> all tasks are really intense so anything
            // is nice
            Runtime.getRuntime().gc();
            System.gc();
            log.info("Completed QA @ " + Calendar.getInstance().getTime().toString());
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
        } else if (activity.toLowerCase().equals("notify")) {
            log.info("Running Notification Tasks");
            Notification nt = null;
            if (context.containsBean("Notify" + Integer.toString(n))) {
                nt = (Notification) context.getBean("Notify" + Integer.toString(n));
            } else {
                nt = (Notification) context.getBean("Notify");
            }

            nt.run();
            nt = null;
            n++;

            if (context.containsBean("Email") && ems == 0) {
                Send s = (Send) context.getBean("Email");
                s.run();
                s = null;
            } else if (context.containsBean("Email" + ems)) {
                Send s = (Send) context.getBean("Email" + Integer.toString(ems));
                s.run();
                s = null;
            }

            ems++;
            Runtime.getRuntime().gc();
            System.gc();
            log.info("Free Memory: " + Runtime.getRuntime().freeMemory());
            log.info("Completed Notification Tasks");
        } else if (activity.toLowerCase().contains("move")) {
            log.info("Moving Files @ " + Calendar.getInstance().getTime().toString());

            MoveFile mf = null;
            if (context.containsBean("Move" + Integer.toString(mv))) {
                mf = (MoveFile) context.getBean("Move" + Integer.toString(mv));
            } else {
                mf = (MoveFile) context.getBean("Move");
            }
            mf.run();
            mv++;
            Runtime.getRuntime().gc();
            log.info("Finished Moving Files @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("numericalcheck")) {
            log.info("Checking Counts");

            NumericalChecker nc = (NumericalChecker) context.getBean("NumericalChecker");
            nc.run();
            Runtime.getRuntime().gc();

            log.info("Finished Checking Counts @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("runscript")) {
            log.info("Running Script @ " + Calendar.getInstance().getTime().toString());
            RunScript runner = null;
            if (context.containsBean("RunScript" + srn)) {
                runner = (RunScript) context.getBean("RunScript" + srn);
            } else {
                runner = (RunScript) context.getBean("RunScript");
            }
            runner.run();
            srn++;
            Runtime.getRuntime().gc();
            log.info("Finished Running SCript @ " + Calendar.getInstance().getTime().toString());
        } else if (activity.toLowerCase().contains("checkexistance")) {
            log.info("Checking Existance @ " + Calendar.getInstance().getTime().toString());
            ExistanceChecker runner = null;
            if (context.containsBean("CheckExistance" + srn)) {
                runner = (ExistanceChecker) context.getBean("CheckExistance" + cen);
            } else {
                runner = (ExistanceChecker) context.getBean("CheckExistance");
            }
            runner.run();
            cen++;
            Runtime.getRuntime().gc();
            log.info("Finished Checking Existance @ " + Calendar.getInstance().getTime().toString());
        } else {
            log.info("Activity " + activity + " does not exist!");
        }

    }

    log.info("Completed Parse @ " + Calendar.getInstance().getTime().toString());
    context.destroy();
    context.close();
}

From source file:org.aksw.dice.eaglet.web.RootConfig.java

@Bean
public EagletDatabaseStatements experimentDAO() {
    LOGGER.debug("Setting up database.");
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/spring/database/database-context.xml");
    EagletDatabaseStatements database = context.getBean(EagletDatabaseStatements.class);
    context.close();
    return database;
}

From source file:org.alfresco.filesys.CIFSServerBean.java

/**
 * Runs the CIFS server directly//from w  w w . j av a2 s .co  m
 * 
 * @param args String[]
 */
public static void main(String[] args) {
    PrintStream out = System.out;

    out.println("CIFS Server Test");
    out.println("----------------");

    ClassPathXmlApplicationContext ctx = null;
    try {
        // Create the configuration service in the same way that Spring creates it

        ctx = new ClassPathXmlApplicationContext("alfresco/application-context.xml");

        // Get the CIFS server bean

        CIFSServerBean server = (CIFSServerBean) ctx.getBean("cifsServer");
        if (server == null) {
            throw new AlfrescoRuntimeException("Server bean 'cifsServer' not defined");
        }

        // Stop the FTP server, if running

        NetworkServer srv = server.getConfiguration().findServer("FTP");
        if (srv != null)
            srv.shutdownServer(true);

        // Stop the NFS server, if running

        srv = server.getConfiguration().findServer("NFS");
        if (srv != null)
            srv.shutdownServer(true);

        // Only wait for shutdown if the SMB/CIFS server is enabled

        if (server.getConfiguration().hasConfigSection(CIFSConfigSection.SectionName)) {

            // SMB/CIFS server should have automatically started
            // Wait for shutdown via the console

            out.println("Enter 'x' to shutdown ...");
            boolean shutdown = false;

            // Wait while the server runs, user may stop the server by typing a key

            while (shutdown == false) {

                // Wait for the user to enter the shutdown key

                int ch = System.in.read();

                if (ch == 'x' || ch == 'X')
                    shutdown = true;

                synchronized (server) {
                    server.wait(20);
                }
            }

            // Stop the server

            server.stopServer();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
    System.exit(1);
}

From source file:org.alfresco.filesys.FTPServerBean.java

/**
 * Runs the FTP server directly/*from   w ww  .ja v a 2s.c  o  m*/
 * 
 * @param args String[]
 */
public static void main(String[] args) {
    PrintStream out = System.out;

    out.println("FTP Server Test");
    out.println("---------------");

    ClassPathXmlApplicationContext ctx = null;
    try {
        // Create the configuration service in the same way that Spring creates it

        ctx = new ClassPathXmlApplicationContext("alfresco/application-context.xml");

        // Get the FTP server bean

        FTPServerBean server = (FTPServerBean) ctx.getBean("ftpServer");
        if (server == null) {
            throw new AlfrescoRuntimeException("Server bean 'ftpServer' not defined");
        }

        // Stop the CIFS server components, if running

        NetworkServer srv = server.getConfiguration().findServer("SMB");
        if (srv != null)
            srv.shutdownServer(true);

        srv = server.getConfiguration().findServer("NetBIOS");
        if (srv != null)
            srv.shutdownServer(true);

        // Only wait for shutdown if the FTP server is enabled

        if (server.getConfiguration().hasConfigSection(FTPConfigSection.SectionName)) {

            // FTP server should have automatically started
            //
            // Wait for shutdown via the console

            out.println("Enter 'x' to shutdown ...");
            boolean shutdown = false;

            // Wait while the server runs, user may stop the server by typing a key

            while (shutdown == false) {

                // Wait for the user to enter the shutdown key

                int ch = System.in.read();

                if (ch == 'x' || ch == 'X')
                    shutdown = true;

                synchronized (server) {
                    server.wait(20);
                }
            }

            // Stop the server

            server.stopServer();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
    System.exit(1);
}

From source file:org.axonframework.quickstart.RunUpcasterWithSpring.java

/**
 * @deprecated Spring XML config support is deprecated
 *///from  w w  w  . j  a v  a  2  s  . c  o  m
@Deprecated
public static void main(String[] args) throws IOException {
    // we want to delete the directory that will store our events
    FileUtils.deleteDirectory(new File(System.getProperty("java.io.tmpdir"), "Events"));

    // we start the application context
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "upcaster-config.xml");

    // we fetch the EventStore from the application context
    EventStore eventStore = applicationContext.getBean(EventStore.class);

    // we append some events. Notice we append a "ToDoItemCreatedEvent".
    eventStore.publish(Arrays.asList(
            new GenericDomainEventMessage<Object>("ToDo", "todo1", 0,
                    new ToDoItemCreatedEvent("todo1", "I need to do this today")),
            new GenericDomainEventMessage<Object>("ToDo", "todo1", 1, new ToDoItemCompletedEvent("todo1"))));
    eventStore.publish(Collections.singletonList(new GenericDomainEventMessage<Object>("ToDo", "todo2", 0,
            new ToDoItemCreatedEvent("todo2", "I also need to do this"))));

    // now, we read the events from the "todo1" stream
    DomainEventStream upcastEvents = eventStore.readEvents("todo1");
    while (upcastEvents.hasNext()) {
        // and print them, so that we can see what we ended up with
        System.out.println(upcastEvents.next().getPayload().toString());
    }
    IOUtils.closeQuietlyIfCloseable(upcastEvents);

    // to see the Upcaster doing the upcasting, see RunUpcaster, inner class ToDoItemUpcaster

    // we close the application context. It's just good habit
    applicationContext.close();
}

From source file:org.easyrec.plugin.container.PluginRegistry.java

@SuppressWarnings({ "unchecked" })
public PluginVO checkPlugin(byte[] file) throws Exception {
    PluginVO plugin;//www.j a v  a  2s . c o m
    FileOutputStream fos = null;
    URLClassLoader ucl;
    ClassPathXmlApplicationContext cax = null;
    File tmpFile = null;

    try {
        if (file == null)
            throw new IllegalArgumentException("Passed file must not be null!");

        tmpFile = File.createTempFile("plugin", null);
        tmpFile.deleteOnExit();

        fos = new FileOutputStream(tmpFile);
        fos.write(file);
        fos.close();

        // check if plugin is valid
        ucl = new URLClassLoader(new URL[] { tmpFile.toURI().toURL() }, this.getClass().getClassLoader());

        if (ucl.getResourceAsStream(DEFAULT_PLUGIN_CONFIG_FILE) != null) {
            cax = new ClassPathXmlApplicationContext(new String[] { DEFAULT_PLUGIN_CONFIG_FILE }, false,
                    appContext);
            cax.setClassLoader(ucl);
            logger.info("Classloader: " + cax.getClassLoader());
            cax.refresh();

            Map<String, GeneratorPluginSupport> beans = cax.getBeansOfType(GeneratorPluginSupport.class);

            if (beans.isEmpty()) {
                logger.debug("No class implementing a generator could be found. Plugin rejected!");
                throw new Exception("No class implementing a generator could be found. Plugin rejected!");
            }

            Generator<GeneratorConfiguration, GeneratorStatistics> generator = beans.values().iterator().next();

            logger.info(String.format("Plugin successfully validated! class: %s name: %s, id: %s",
                    generator.getClass(), generator.getDisplayName(), generator.getId()));

            cax.getAutowireCapableBeanFactory().autowireBeanProperties(generator,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);

            plugin = new PluginVO(generator.getDisplayName(), generator.getId().getUri(),
                    generator.getId().getVersion(), LifecyclePhase.NOT_INSTALLED.toString(), file, null);

            if (tmpFile.delete())
                logger.info("tmpFile deleted successfully");

            return plugin;
        } else { // config file not found
            logger.debug("No valid config file found in the supplied .jar file. Plugin rejected!");
            throw new Exception("No valid config file found in the supplied .jar file. Plugin rejected!");
        }
    } catch (Exception e) {
        logger.error("An Exception occurred while checking the plugin!", e);

        throw e;
    } finally {
        if (fos != null)
            fos.close();

        if ((cax != null) && (!cax.isActive()))
            cax.close();

        if (tmpFile != null)
            try {
                if (!tmpFile.delete())
                    logger.warn("could not delete tmpFile");
            } catch (SecurityException se) {
                logger.error("Could not delete temporary file! Please check permissions!", se);
            }
    }
}

From source file:org.easyrec.plugin.container.PluginRegistry.java

public void deactivatePlugin(URI pluginId, Version version) {
    PluginId key = new PluginId(pluginId, version);
    Generator<GeneratorConfiguration, GeneratorStatistics> generator = generators.get(key);

    if ((generator != null) && (LifecyclePhase.INITIALIZED.equals(generator.getLifecyclePhase()))) {
        String sourceType = generator.getSourceType();

        generator.cleanup();//  www.  j a v  a  2 s.  com
        pluginDAO.updatePluginState(pluginId, version, LifecyclePhase.INSTALLED.toString());
        generators.remove(key);

        ClassPathXmlApplicationContext cax = contexts.get(key);

        generator.uninstall();
        pluginDAO.updatePluginState(pluginId, version, LifecyclePhase.NOT_INSTALLED.toString());

        if (cax != null)
            cax.close();

        contexts.remove(key);

        if (logger.isDebugEnabled())
            logger.debug("Deactivating configurations for " + key.getUri() + "-" + key.getVersion());

        int deactivates = namedConfigurationDAO.deactivateByPlugin(key);

        if (logger.isDebugEnabled())
            logger.debug("Deactivated " + deactivates + " plugins");

        List<TenantVO> tenants = tenantService.getAllTenants();

        for (TenantVO tenant : tenants) {
            Integer sourceTypeId;

            try {
                sourceTypeId = typeMappingService.getIdOfSourceType(tenant.getId(), sourceType);
            } catch (IllegalArgumentException iae) {
                logger.info(
                        String.format("Source type %s not defined for tenant %d", sourceType, tenant.getId()));
                continue;
            }

            int removedRows = itemAssocDAO.removeItemAssocByTenant(tenant.getId(), null, sourceTypeId, null);

            logger.info(String.format(
                    "Removed %d item assocs of source type %d for tenant %d because plugin is deactivating.",
                    removedRows, sourceTypeId, tenant.getId()));
        }
    }
}

From source file:org.easyrec.plugin.container.PluginRegistry.java

@Override
public void destroy() throws Exception {
    for (ClassPathXmlApplicationContext ctx : contexts.values()) {
        ctx.close();
    }//  w  w w . j  av a  2  s.  c o  m
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private ApplicationContext loadContext(String[] configLocations, URLClassLoader cl, String contextDisplayName,
        Properties properties) throws Exception {
    ServletContext servletContext = ((ConfigurableWebApplicationContext) this._applicationContext)
            .getServletContext();//from w  w w  . j ava  2 s .co  m
    //if plugin's classes have been loaded we can go on
    List<ClassPathXmlApplicationContext> ctxList = (List<ClassPathXmlApplicationContext>) servletContext
            .getAttribute("pluginsContextsList");
    if (ctxList == null) {
        ctxList = new ArrayList<ClassPathXmlApplicationContext>();
        servletContext.setAttribute("pluginsContextsList", ctxList);
    }
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    ClassPathXmlApplicationContext newContext = null;
    try {
        //create a new spring context with the classloader and the paths defined as parameter in pluginsInstallerContext.xml.
        //The new context is given the default webapplication context as its parent  
        Thread.currentThread().setContextClassLoader(cl);
        newContext = new ClassPathXmlApplicationContext();
        //ClassPathXmlApplicationContext newContext = new ClassPathXmlApplicationContext(configLocations, applicationContext);    
        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        configurer.setProperties(properties);
        newContext.addBeanFactoryPostProcessor(configurer);
        newContext.setClassLoader(cl);
        newContext.setParent(this._applicationContext);
        String[] configLocs = new String[] { "classpath:spring/restServerConfig.xml",
                "classpath:spring/baseSystemConfig.xml" };
        newContext.setConfigLocations(configLocs);
        newContext.refresh();
        BaseConfigManager baseConfigManager = (BaseConfigManager) ((ConfigurableWebApplicationContext) this._applicationContext)
                .getBean("BaseConfigManager");
        baseConfigManager.init();
        newContext.setConfigLocations(configLocations);
        newContext.refresh();
        newContext.setDisplayName(contextDisplayName);
        ClassPathXmlApplicationContext currentCtx = (ClassPathXmlApplicationContext) this
                .getStoredContext(contextDisplayName);
        if (currentCtx != null) {
            currentCtx.close();
            ctxList.remove(currentCtx);
        }
        ctxList.add(newContext);

    } catch (Exception e) {
        _logger.error("Unexpected error loading application context: " + e.getMessage());
        e.printStackTrace();
        throw e;
    } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
    return newContext;
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentUninstaller.java

@Override
public boolean uninstallComponent(Component component) throws ApsSystemException {
    ServletContext servletContext = ((ConfigurableWebApplicationContext) _applicationContext)
            .getServletContext();//w w  w  . ja  v  a2s  .co  m
    ClassLoader cl = (ClassLoader) servletContext.getAttribute("componentInstallerClassLoader");
    List<ClassPathXmlApplicationContext> ctxList = (List<ClassPathXmlApplicationContext>) servletContext
            .getAttribute("pluginsContextsList");
    ClassPathXmlApplicationContext appCtx = null;
    if (ctxList != null) {
        for (ClassPathXmlApplicationContext ctx : ctxList) {
            if (component.getCode().equals(ctx.getDisplayName())) {
                appCtx = ctx;
            }
        }
    }
    String appRootPath = servletContext.getRealPath("/");
    String backupDirPath = appRootPath + "componentinstaller" + File.separator + component.getArtifactId()
            + "-backup";
    Map<File, File> resourcesMap = new HashMap<File, File>();
    try {
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            if (cl != null) {
                Thread.currentThread().setContextClassLoader(cl);
            }
            if (null == component || null == component.getUninstallerInfo()) {
                return false;
            }
            this.getDatabaseManager().createBackup();//backup database
            SystemInstallationReport report = super.extractReport();
            ComponentUninstallerInfo ui = component.getUninstallerInfo();
            //remove records from db
            String[] dataSourceNames = this.extractBeanNames(DataSource.class);
            for (int j = 0; j < dataSourceNames.length; j++) {
                String dataSourceName = dataSourceNames[j];
                Resource resource = (null != ui) ? ui.getSqlResources(dataSourceName) : null;
                String script = (null != resource) ? this.readFile(resource) : null;
                if (null != script && script.trim().length() > 0) {
                    DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName);
                    String[] queries = QueryExtractor.extractDeleteQueries(script);
                    TableDataUtils.executeQueries(dataSource, queries, true);
                }
            }
            this.executePostProcesses(ui.getPostProcesses());

            //drop tables
            Map<String, List<String>> tableMapping = component.getTableMapping();
            if (tableMapping != null) {
                for (int j = 0; j < dataSourceNames.length; j++) {
                    String dataSourceName = dataSourceNames[j];
                    List<String> tableClasses = tableMapping.get(dataSourceName);
                    if (null != tableClasses && tableClasses.size() > 0) {
                        List<String> newList = new ArrayList<String>();
                        newList.addAll(tableClasses);
                        Collections.reverse(newList);
                        DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName);
                        IDatabaseManager.DatabaseType type = this.getDatabaseManager()
                                .getDatabaseType(dataSource);
                        TableFactory tableFactory = new TableFactory(dataSourceName, dataSource, type);
                        tableFactory.dropTables(newList);
                    }
                }
            }

            //move resources (jar, files and folders) on temp folder  
            List<String> resourcesPaths = ui.getResourcesPaths();
            if (resourcesPaths != null) {
                for (String resourcePath : resourcesPaths) {
                    try {
                        String fullResourcePath = servletContext.getRealPath(resourcePath);
                        File resFile = new File(fullResourcePath);
                        String relResPath = FilenameUtils.getPath(resFile.getAbsolutePath());
                        File newResFile = new File(
                                backupDirPath + File.separator + relResPath + resFile.getName());
                        if (resFile.isDirectory()) {
                            FileUtils.copyDirectory(resFile, newResFile);
                            resourcesMap.put(resFile, newResFile);
                            FileUtils.deleteDirectory(resFile);
                        } else {
                            FileUtils.copyFile(resFile, newResFile);
                            resourcesMap.put(resFile, newResFile);
                            FileUtils.forceDelete(resFile);
                        }
                    } catch (Exception e) {
                    }
                }
            }

            //upgrade report
            ComponentInstallationReport cir = report.getComponentReport(component.getCode(), true);
            cir.getDataSourceReport().upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED);
            cir.getDataReport().upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED);
            this.saveReport(report);

            //remove plugin's xmlapplicationcontext if present
            if (appCtx != null) {
                appCtx.close();
                ctxList.remove(appCtx);
            }
            InitializerManager initializerManager = (InitializerManager) _applicationContext
                    .getBean("InitializerManager");
            initializerManager.reloadCurrentReport();
            ComponentManager componentManager = (ComponentManager) _applicationContext
                    .getBean("ComponentManager");
            componentManager.refresh();
        } catch (Exception e) {
            _logger.error("Unexpected error in component uninstallation process", e);
            throw new ApsSystemException("Unexpected error in component uninstallation process.", e);
        } finally {
            Thread.currentThread().setContextClassLoader(currentClassLoader);
            ApsWebApplicationUtils.executeSystemRefresh(servletContext);
        }
    } catch (Throwable t) {
        //restore files on temp folder
        try {
            for (Object object : resourcesMap.entrySet()) {
                File resFile = ((Map.Entry<File, File>) object).getKey();
                File newResFile = ((Map.Entry<File, File>) object).getValue();
                if (newResFile.isDirectory()) {
                    FileUtils.copyDirectoryToDirectory(newResFile, resFile.getParentFile());
                } else {
                    FileUtils.copyFile(newResFile, resFile.getParentFile());
                }
            }
        } catch (Exception e) {
        }
        _logger.error("Unexpected error in component uninstallation process", t);
        throw new ApsSystemException("Unexpected error in component uninstallation process.", t);
    } finally {
        //clean temp folder
    }
    return true;
}