Example usage for java.lang ClassLoader getSystemClassLoader

List of usage examples for java.lang ClassLoader getSystemClassLoader

Introduction

In this page you can find the example usage for java.lang ClassLoader getSystemClassLoader.

Prototype

@CallerSensitive
public static ClassLoader getSystemClassLoader() 

Source Link

Document

Returns the system class loader.

Usage

From source file:org.jetbrains.jet.grammar.GrammarGenerator.java

public static void main(String[] args) throws IOException, TransformerException {

    System.out.println("Checking cmd line arguments.");
    if (args.length < 2)
        throw new IllegalArgumentException("Usage: grammar-parser <path to grm files> <output file name>");

    File grammarDir = new File(args[0]);
    File outputFile = new File(args[1]);

    if (!outputFile.exists()) {
        if (!outputFile.createNewFile())
            throw new IOException("Cannot create output file.");
    }//from   w w w  .  ja  va2s  .com

    Set<File> used = new HashSet<File>();
    List<Token> tokens = getJoinedTokensFromAllFiles(grammarDir, used);
    assertAllFilesAreUsed(grammarDir, used);
    System.out.println("Preparing resources.");
    ClassLoader loader = ClassLoader.getSystemClassLoader();

    StreamSource xml = new StreamSource(new StringReader(generate(tokens)));
    StreamSource xsl = new StreamSource(loader.getResourceAsStream("convert.xsl"));

    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    StreamResult result = new StreamResult(outputFile);

    System.out.println("Processing.");
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(xsl);

    transformer.transform(xml, result);
    result.getOutputStream().close();
    System.out.println("Done.");
}

From source file:org.xwiki.xdomviz.Main.java

/**
 * Entry point//from w  w  w .  ja  v  a2s. c  o  m
 */
public static void main(String[] args) throws Exception {
    // Parse command line
    Options options = new Options();
    options.addOption("n", false, "Normalize the XDOM");
    options.addOption("o", true, "Output file name");
    options.addOption("h", false, "Help");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(String.format("%s [options] [input file]", Main.class.getName()),
                "If no input file is specified, standard input is used", options, "");
        return;
    }

    boolean normalize = false;
    if (cmd.hasOption("n")) {
        normalize = true;
    }

    String outputFileName = null;
    if (cmd.hasOption("o")) {
        outputFileName = cmd.getOptionValue("o");
    }

    String inputFileName = null;
    if (cmd.getArgs().length > 0) {
        inputFileName = cmd.getArgs()[0];
    }

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    if (inputFileName != null) {
        input = new BufferedReader(new FileReader(new File(inputFileName)));
    }

    PrintWriter output = new PrintWriter(new OutputStreamWriter(System.out));
    if (outputFileName != null) {
        output = new PrintWriter(new FileWriter(new File(outputFileName)));
    }

    // Read the text to parse
    String text = readText(input);

    // Initialize Rendering components and allow getting instances
    EmbeddableComponentManager ecm = new EmbeddableComponentManager();
    ecm.initialize(ClassLoader.getSystemClassLoader());

    // Parse XWiki 2.0 Syntax using a Parser.
    Parser xdomParser = ecm.lookup(Parser.class, Syntax.XWIKI_2_0.toIdString());
    XDOM xdom = xdomParser.parse(new StringReader(text));

    // Create the "working" tree
    Node root = createNodeTree(xdom);

    // Normalize it if requested
    if (normalize) {
        root = normalize(root);
    }

    // Write the output
    output.append(generateGraphViz(root));

    // Close everything
    output.close();
    input.close();
}

From source file:edu.usf.cutr.obascs.OBASCSMain.java

public static void main(String[] args) {

    String logLevel = null;//from  www . j  av  a 2s .  co m
    String outputFilePath = null;
    String inputFilePath = null;
    String spreadSheetId = null;
    Logger logger = Logger.getInstance();

    Options options = CommandLineUtil.createCommandLineOptions();
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        logLevel = CommandLineUtil.getLogLevel(cmd);
        logger.setup(logLevel);
        outputFilePath = CommandLineUtil.getOutputPath(cmd);
        spreadSheetId = CommandLineUtil.getSpreadSheetId(cmd);

        inputFilePath = CommandLineUtil.getInputPath(cmd);
    } catch (ParseException e1) {
        logger.logError(e1);
    } catch (FileNotFoundException e) {
        logger.logError(e);
    }

    Map<String, String> agencyMap = null;
    try {
        agencyMap = FileUtil.readAgencyInformantions(inputFilePath);
    } catch (IOException e1) {
        logger.logError(e1);
    }

    logger.log("Consolidation started...");
    logger.log("Trying as public url");

    ListFeed listFeed = null;
    Boolean authRequired = false;
    try {
        listFeed = SpreadSheetReader.readPublicSpreadSheet(spreadSheetId);
    } catch (IOException e) {
        logger.logError(e);
    } catch (ServiceException e) {
        logger.log("Authentication Required");
        authRequired = true;
    }

    if (listFeed == null && authRequired == true) {
        Scanner scanner = new Scanner(System.in);
        String userName, password;
        logger.log("UserName:");
        userName = scanner.nextLine();
        logger.log("Password:");
        password = scanner.nextLine();
        scanner.close();

        try {
            listFeed = SpreadSheetReader.readPrivateSpreadSheet(userName, password, spreadSheetId);
        } catch (IOException e) {
            logger.logError(e);
        } catch (ServiceException e) {
            logger.logError(e);
        }
    }

    if (listFeed != null) {
        //Creating consolidated stops
        String consolidatedString = FileConsolidator.consolidateFile(listFeed, agencyMap);
        try {
            FileUtil.writeToFile(consolidatedString, outputFilePath);
        } catch (FileNotFoundException e) {
            logger.logError(e);
        }

        //Creating sample stop consolidation script config file
        try {
            String path = ClassLoader.getSystemClassLoader()
                    .getResource(GeneralConstants.CONSOLIDATION_SCRIPT_CONFIG_FILE).getPath();
            String configXml = FileUtil.readFile(URLUtil.trimSpace(path));
            configXml = ConfigFileGenerator.generateStopConsolidationScriptConfigFile(configXml, agencyMap);
            path = URLUtil.trimPath(outputFilePath) + "/" + GeneralConstants.CONSOLIDATION_SCRIPT_CONFIG_FILE;
            FileUtil.writeToFile(configXml, path);
        } catch (IOException e) {
            logger.logError(e);
        }

        //Creating sample real-time config file
        try {
            String path = ClassLoader.getSystemClassLoader()
                    .getResource(GeneralConstants.SAMPLE_REALTIME_CONFIG_FILE).getPath();
            String configXml = FileUtil.readFile(URLUtil.trimSpace(path));
            configXml = ConfigFileGenerator.generateSampleRealTimeConfigFile(configXml, agencyMap);
            path = URLUtil.trimPath(outputFilePath) + "/" + GeneralConstants.SAMPLE_REALTIME_CONFIG_FILE;
            FileUtil.writeToFile(configXml, path);
        } catch (IOException e) {
            logger.logError(e);
        }
    } else {
        logger.logError("Cannot write files");
    }

    logger.log("Consolidation finished...");

}

From source file:org.tinymediamanager.TinyMediaManager.java

/**
 * The main method./*from  ww  w  .  j  av  a2s  . c om*/
 * 
 * @param args
 *          the arguments
 */
public static void main(String[] args) {
    // simple parse command line
    if (args != null && args.length > 0) {
        LOGGER.debug("TMM started with: " + Arrays.toString(args));
        TinyMediaManagerCMD.parseParams(args);
        System.setProperty("java.awt.headless", "true");
    } else {
        // no cmd params found, but if we are headless - display syntax
        String head = System.getProperty("java.awt.headless");
        if (head != null && head.equals("true")) {
            LOGGER.info("TMM started 'headless', and without params -> displaying syntax ");
            TinyMediaManagerCMD.printSyntax();
            System.exit(0);
        }
    }

    // check if we have write permissions to this folder
    try {
        RandomAccessFile f = new RandomAccessFile("access.test", "rw");
        f.close();
        Files.deleteIfExists(Paths.get("access.test"));
    } catch (Exception e2) {
        String msg = "Cannot write to TMM directory, have no rights - exiting.";
        if (!GraphicsEnvironment.isHeadless()) {
            JOptionPane.showMessageDialog(null, msg);
        } else {
            System.out.println(msg);
        }
        System.exit(1);
    }

    // HACK for Java 7 and JavaFX not being in boot classpath
    // In Java 8 and on, this is installed inside jre/lib/ext
    // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8003171 and references
    // so we check if it is already existent in "new" directory, and if not, load it via reflection ;o)
    String dir = new File(LaunchUtil.getJVMPath()).getParentFile().getParent(); // bin, one deeper
    File jfx = new File(dir, "lib/ext/jfxrt.jar");
    if (!jfx.exists()) {
        // java 7
        jfx = new File(dir, "lib/jfxrt.jar");
        if (jfx.exists()) {
            try {
                TmmOsUtils.addPath(jfx.getAbsolutePath());
            } catch (Exception e) {
                LOGGER.debug("failed to load JavaFX - using old styles...");
            }
        }
    }

    if (Globals.isDebug()) {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL[] urls = ((URLClassLoader) cl).getURLs();
        LOGGER.info("=== DEBUG CLASS LOADING =============================");
        for (URL url : urls) {
            LOGGER.info(url.getFile());
        }
    }

    LOGGER.info("=====================================================");
    LOGGER.info("=== tinyMediaManager (c) 2012-2016 Manuel Laggner ===");
    LOGGER.info("=====================================================");
    LOGGER.info("tmm.version      : " + ReleaseInfo.getRealVersion());

    if (Globals.isDonator()) {
        LOGGER.info("tmm.supporter    : THANKS FOR DONATING - ALL FEATURES UNLOCKED :)");
    }

    LOGGER.info("os.name          : " + System.getProperty("os.name"));
    LOGGER.info("os.version       : " + System.getProperty("os.version"));
    LOGGER.info("os.arch          : " + System.getProperty("os.arch"));
    LOGGER.trace("network.id       : " + License.getMac());
    LOGGER.info("java.version     : " + System.getProperty("java.version"));

    if (Globals.isRunningJavaWebStart()) {
        LOGGER.info("java.webstart    : true");
    }
    if (Globals.isRunningWebSwing()) {
        LOGGER.info("java.webswing    : true");
    }

    // START character encoding debug
    debugCharacterEncoding("default encoding : ");
    System.setProperty("file.encoding", "UTF-8");
    System.setProperty("sun.jnu.encoding", "UTF-8");
    Field charset;
    try {
        // we cannot (re)set the properties while running inside JVM
        // so we trick it to reread it by setting them to null ;)
        charset = Charset.class.getDeclaredField("defaultCharset");
        charset.setAccessible(true);
        charset.set(null, null);
    } catch (Exception e) {
        LOGGER.warn("Error resetting to UTF-8", e);
    }
    debugCharacterEncoding("set encoding to  : ");
    // END character encoding debug

    // set GUI default language
    Locale.setDefault(Utils.getLocaleFromLanguage(Globals.settings.getLanguage()));
    LOGGER.info("System language  : " + System.getProperty("user.language") + "_"
            + System.getProperty("user.country"));
    LOGGER.info(
            "GUI language     : " + Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry());
    LOGGER.info("Scraper language : " + MovieModuleManager.MOVIE_SETTINGS.getScraperLanguage());
    LOGGER.info("TV Scraper lang  : " + TvShowModuleManager.SETTINGS.getScraperLanguage());

    // start EDT
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            boolean newVersion = !Globals.settings.isCurrentVersion(); // same snapshots/svn considered as "new", for upgrades
            try {
                Thread.setDefaultUncaughtExceptionHandler(new Log4jBackstop());
                if (!GraphicsEnvironment.isHeadless()) {
                    Thread.currentThread().setName("main");
                } else {
                    Thread.currentThread().setName("headless");
                    LOGGER.debug("starting without GUI...");
                }
                Toolkit tk = Toolkit.getDefaultToolkit();
                tk.addAWTEventListener(TmmWindowSaver.getInstance(), AWTEvent.WINDOW_EVENT_MASK);
                if (!GraphicsEnvironment.isHeadless()) {
                    setLookAndFeel();
                }
                doStartupTasks();

                // suppress logging messages from betterbeansbinding
                org.jdesktop.beansbinding.util.logging.Logger.getLogger(ELProperty.class.getName())
                        .setLevel(Level.SEVERE);

                // init ui logger
                TmmUILogCollector.init();

                LOGGER.info("=====================================================");
                // init splash
                SplashScreen splash = null;
                if (!GraphicsEnvironment.isHeadless()) {
                    splash = SplashScreen.getSplashScreen();
                }
                Graphics2D g2 = null;
                if (splash != null) {
                    g2 = splash.createGraphics();
                    if (g2 != null) {
                        Font font = new Font("Dialog", Font.PLAIN, 14);
                        g2.setFont(font);
                    } else {
                        LOGGER.debug("got no graphics from splash");
                    }
                } else {
                    LOGGER.debug("no splash found");
                }

                if (g2 != null) {
                    updateProgress(g2, "starting tinyMediaManager", 0);
                    splash.update();
                }
                LOGGER.info("starting tinyMediaManager");

                // upgrade check
                String oldVersion = Globals.settings.getVersion();
                if (newVersion) {
                    if (g2 != null) {
                        updateProgress(g2, "upgrading to new version", 10);
                        splash.update();
                    }
                    UpgradeTasks.performUpgradeTasksBeforeDatabaseLoading(oldVersion); // do the upgrade tasks for the old version
                    Globals.settings.setCurrentVersion();
                    Globals.settings.saveSettings();
                }

                // proxy settings
                if (Globals.settings.useProxy()) {
                    LOGGER.info("setting proxy");
                    Globals.settings.setProxy();
                }

                // MediaInfo /////////////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading MediaInfo libs", 20);
                    splash.update();
                }
                MediaInfoUtils.loadMediaInfo();

                // load modules //////////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading movie module", 30);
                    splash.update();
                }
                TmmModuleManager.getInstance().startUp();
                TmmModuleManager.getInstance().registerModule(MovieModuleManager.getInstance());
                TmmModuleManager.getInstance().enableModule(MovieModuleManager.getInstance());

                if (g2 != null) {
                    updateProgress(g2, "loading TV show module", 40);
                    splash.update();
                }

                TmmModuleManager.getInstance().registerModule(TvShowModuleManager.getInstance());
                TmmModuleManager.getInstance().enableModule(TvShowModuleManager.getInstance());

                if (g2 != null) {
                    updateProgress(g2, "loading plugins", 50);
                    splash.update();
                }

                // just instantiate static - will block (takes a few secs)
                PluginManager.getInstance();
                if (ReleaseInfo.isSvnBuild()) {
                    PluginManager.loadClasspathPlugins();
                }

                // do upgrade tasks after database loading
                if (newVersion) {
                    if (g2 != null) {
                        updateProgress(g2, "upgrading database to new version", 70);
                        splash.update();
                    }
                    UpgradeTasks.performUpgradeTasksAfterDatabaseLoading(oldVersion);
                }

                // launch application ////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading ui", 80);
                    splash.update();
                }
                if (!GraphicsEnvironment.isHeadless()) {
                    MainWindow window = new MainWindow("tinyMediaManager / " + ReleaseInfo.getRealVersion());

                    // finished ////////////////////////////////////////////////////
                    if (g2 != null) {
                        updateProgress(g2, "finished starting :)", 100);
                        splash.update();
                    }

                    // write a random number to file, to identify this instance (for
                    // updater, tracking, whatsoever)
                    Utils.trackEvent("startup");

                    TmmWindowSaver.getInstance().loadSettings(window);
                    window.setVisible(true);

                    // wizard for new user
                    if (Globals.settings.newConfig) {
                        Globals.settings.writeDefaultSettings(); // now all plugins are resolved - write again defaults!
                        TinyMediaManagerWizard wizard = new TinyMediaManagerWizard();
                        wizard.setVisible(true);
                    }

                    // show changelog
                    if (newVersion && !ReleaseInfo.getVersion().equals(oldVersion)) {
                        // special case nightly/svn: if same snapshot version, do not display changelog
                        Utils.trackEvent("updated");
                        showChangelog();
                    }
                } else {
                    TinyMediaManagerCMD.startCommandLineTasks();
                    // wait for other tmm threads (artwork download et all)
                    while (TmmTaskManager.getInstance().poolRunning()) {
                        Thread.sleep(2000);
                    }

                    LOGGER.info("bye bye");
                    // MainWindows.shutdown()
                    try {
                        // send shutdown signal
                        TmmTaskManager.getInstance().shutdown();
                        // save unsaved settings
                        Globals.settings.saveSettings();
                        // hard kill
                        TmmTaskManager.getInstance().shutdownNow();
                        // close database connection
                        TmmModuleManager.getInstance().shutDown();
                    } catch (Exception ex) {
                        LOGGER.warn(ex.getMessage());
                    }
                    System.exit(0);
                }
            } catch (IllegalStateException e) {
                LOGGER.error("IllegalStateException", e);
                if (!GraphicsEnvironment.isHeadless() && e.getMessage().contains("file is locked")) {
                    // MessageDialog.showExceptionWindow(e);
                    ResourceBundle bundle = ResourceBundle.getBundle("messages", new UTF8Control()); //$NON-NLS-1$
                    MessageDialog dialog = new MessageDialog(MainWindow.getActiveInstance(),
                            bundle.getString("tmm.problemdetected")); //$NON-NLS-1$
                    dialog.setImage(IconManager.ERROR);
                    dialog.setText(bundle.getString("tmm.nostart"));//$NON-NLS-1$
                    dialog.setDescription(bundle.getString("tmm.nostart.instancerunning"));//$NON-NLS-1$
                    dialog.setResizable(true);
                    dialog.pack();
                    dialog.setLocationRelativeTo(MainWindow.getActiveInstance());
                    dialog.setVisible(true);
                }
                System.exit(1);
            } catch (Exception e) {
                LOGGER.error("Exception while start of tmm", e);
                if (!GraphicsEnvironment.isHeadless()) {
                    MessageDialog.showExceptionWindow(e);
                }
                System.exit(1);
            }
        }

        /**
         * Update progress on splash screen.
         * 
         * @param text
         *          the text
         */
        private void updateProgress(Graphics2D g2, String text, int progress) {
            Object oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            g2.setComposite(AlphaComposite.Clear);
            g2.fillRect(20, 200, 480, 305);
            g2.setPaintMode();

            g2.setColor(new Color(51, 153, 255));
            g2.fillRect(22, 272, 452 * progress / 100, 21);

            g2.setColor(Color.black);
            g2.drawString(text + "...", 23, 310);
            int l = g2.getFontMetrics().stringWidth(ReleaseInfo.getRealVersion()); // bound right
            g2.drawString(ReleaseInfo.getRealVersion(), 480 - l, 325);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue);
            LOGGER.debug("Startup (" + progress + "%) " + text);
        }

        /**
         * Sets the look and feel.
         * 
         * @throws Exception
         *           the exception
         */
        private void setLookAndFeel() throws Exception {
            // get font settings
            String fontFamily = Globals.settings.getFontFamily();
            try {
                // sanity check
                fontFamily = Font.decode(fontFamily).getFamily();
            } catch (Exception e) {
                fontFamily = "Dialog";
            }

            int fontSize = Globals.settings.getFontSize();
            if (fontSize < 12) {
                fontSize = 12;
            }

            String fontString = fontFamily + " " + fontSize;

            // Get the native look and feel class name
            // String laf = UIManager.getSystemLookAndFeelClassName();
            Properties props = new Properties();
            props.setProperty("controlTextFont", fontString);
            props.setProperty("systemTextFont", fontString);
            props.setProperty("userTextFont", fontString);
            props.setProperty("menuTextFont", fontString);
            // props.setProperty("windowTitleFont", "Dialog bold 20");

            fontSize = Math.round((float) (fontSize * 0.833));
            fontString = fontFamily + " " + fontSize;

            props.setProperty("subTextFont", fontString);
            props.setProperty("backgroundColor", "237 237 237");
            props.setProperty("menuBackgroundColor", "237 237 237");
            props.setProperty("controlBackgroundColor", "237 237 237");
            props.setProperty("menuColorLight", "237 237 237");
            props.setProperty("menuColorDark", "237 237 237");
            props.setProperty("toolbarColorLight", "237 237 237");
            props.setProperty("toolbarColorDark", "237 237 237");
            props.setProperty("tooltipBackgroundColor", "255 255 255");
            props.put("windowDecoration", "system");
            props.put("logoString", "");

            // Get the look and feel class name
            com.jtattoo.plaf.luna.LunaLookAndFeel.setTheme(props);
            String laf = "com.jtattoo.plaf.luna.LunaLookAndFeel";

            // Install the look and feel
            UIManager.setLookAndFeel(laf);
        }

        /**
         * Does some tasks at startup
         */
        private void doStartupTasks() {
            // rename downloaded files
            UpgradeTasks.renameDownloadedFiles();

            // extract templates, if GD has not already done
            Utils.extractTemplates();

            // check if a .desktop file exists
            if (Platform.isLinux()) {
                File desktop = new File(TmmOsUtils.DESKTOP_FILE);
                if (!desktop.exists()) {
                    TmmOsUtils.createDesktopFileForLinux(desktop);
                }
            }
        }

        private void showChangelog() {
            // read the changelog
            try {
                final String changelog = Utils.readFileToString(Paths.get("changelog.txt"));
                if (StringUtils.isNotBlank(changelog)) {
                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            WhatsNewDialog dialog = new WhatsNewDialog(changelog);
                            dialog.pack();
                            dialog.setLocationRelativeTo(MainWindow.getActiveInstance());
                            dialog.setModalityType(ModalityType.APPLICATION_MODAL);
                            dialog.setVisible(true);
                        }
                    });
                }
            } catch (IOException e) {
                // no file found
                LOGGER.warn(e.getMessage());
            }
        }
    });
}

From source file:de.uniko.west.winter.test.basics.JenaTests.java

public static void main(String[] args) {

    Model newModel = ModelFactory.createDefaultModel();
    //      /*from ww  w  . ja  v  a  2s  .c om*/
    Model newModel2 = ModelFactory.createModelForGraph(ModelFactory.createMemModelMaker().getGraphMaker()
            .createGraph("http://www.defaultgraph.de/graph1"));
    StringBuilder updateString = new StringBuilder();
    updateString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    updateString.append("PREFIX xsd: <http://bla.org/dc/elements/1.1/>");
    updateString.append("INSERT { ");
    updateString.append(
            "<http://example/egbook1> dc:title  <http://example/egbook1/#Title1>, <http://example/egbook1/#Title2>. ");
    //updateString.append("<http://example/egbook1> dc:title  \"Title1.1\". ");
    //updateString.append("<http://example/egbook1> dc:title  \"Title1.2\". ");
    updateString.append("<http://example/egbook21> dc:title  \"Title2\"; ");
    updateString.append("dc:title  \"2.0\"^^xsd:double. ");
    updateString.append("<http://example/egbook3> dc:title  \"Title3\". ");
    updateString.append("<http://example/egbook4> dc:title  \"Title4\". ");
    updateString.append("<http://example/egbook5> dc:title  \"Title5\". ");
    updateString.append("<http://example/egbook6> dc:title  \"Title6\" ");
    updateString.append("}");

    UpdateRequest update = UpdateFactory.create(updateString.toString());
    UpdateAction.execute(update, newModel);

    StmtIterator iter = newModel.listStatements();
    System.out.println("After add");
    while (iter.hasNext()) {
        System.out.println(iter.next().toString());

    }

    StringBuilder constructQueryString = new StringBuilder();
    constructQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    constructQueryString.append("CONSTRUCT {?sub dc:title <http://example/egbook1/#Title1>}");
    constructQueryString.append("WHERE {");
    constructQueryString.append("?sub dc:title <http://example/egbook1/#Title1>");
    constructQueryString.append("}");

    StringBuilder askQueryString = new StringBuilder();
    askQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    askQueryString.append("ASK {");
    askQueryString.append("?sub dc:title <http://example/egbook1/#Title1>");
    askQueryString.append("}");

    StringBuilder selectQueryString = new StringBuilder();
    selectQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    selectQueryString.append("SELECT * ");
    selectQueryString.append("WHERE {");
    selectQueryString.append("?sub ?pred ?obj");
    selectQueryString.append("}");

    Query cquery = QueryFactory.create(constructQueryString.toString());
    System.out.println(cquery.getQueryType());
    Query aquery = QueryFactory.create(askQueryString.toString());
    System.out.println(aquery.getQueryType());
    Query query = QueryFactory.create(selectQueryString.toString());
    System.out.println(query.getQueryType());
    QueryExecution queryExecution = QueryExecutionFactory.create(query, newModel);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    URI test = null;
    try {
        test = new URI("http://bla.org/dc/elements/1.1/double");
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    System.out.println(test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1));
    System.out.println("java.lang."
            + test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1).substring(0, 1)
                    .toUpperCase()
            + test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1).substring(1));

    String typ = "java.lang.Boolean";
    String val = "true";

    try {
        Object typedLiteral = Class.forName(typ, true, ClassLoader.getSystemClassLoader())
                .getConstructor(String.class).newInstance(val);

        System.out.println("Type: " + typedLiteral.getClass().getName() + " Value: " + typedLiteral);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        System.out.println("Query...");
        com.hp.hpl.jena.query.ResultSet results = queryExecution.execSelect();
        System.out.println("RESULT:");
        ResultSetFormatter.output(System.out, results, ResultSetFormat.syntaxJSON);
        //         
        //         
        //         ResultSetFormatter.outputAsJSON(baos, results);
        //         System.out.println(baos.toString());
        //         System.out.println("JsonTest: ");
        //         JSONObject result = new JSONObject(baos.toString("ISO-8859-1"));
        //         for (Iterator key = result.keys(); result.keys().hasNext(); ){
        //            System.out.println(key.next());
        //            
        //            for (Iterator key2 = ((JSONObject)result.getJSONObject("head")).keys(); key2.hasNext(); ){
        //               System.out.println(key2.next());
        //            }
        //         }

        //         Model results = queryExecution.execConstruct();

        //         results.write(System.out, "TURTLE");
        //         for ( ; results.hasNext() ; ){
        //            QuerySolution soln = results.nextSolution() ;
        //            RDFNode x = soln.get("sub") ;   
        //            System.out.println("result: "+soln.get("sub")+" hasTitle "+soln.get("obj"));
        //             Resource r = soln.getResource("VarR") ; 
        //             Literal l = soln.getLiteral("VarL") ; 
        //
        //         }

    } catch (Exception e) {
        // TODO: handle exception
    }

    //      StringBuilder updateString2 = new StringBuilder();
    //      updateString2.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    //      updateString2.append("DELETE DATA { ");
    //      updateString2.append("<http://example/egbook3> dc:title  \"Title3\" ");
    //      updateString2.append("}");
    //
    //      UpdateAction.parseExecute(updateString2.toString(), newModel);
    //      
    //      iter = newModel.listStatements();
    //      System.out.println("After delete");
    //      while (iter.hasNext()) {
    //         System.out.println(iter.next().toString());
    //            
    //      }
    //      
    //      StringBuilder updateString3 = new StringBuilder();
    //      updateString3.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>");
    //      updateString3.append("DELETE DATA { ");
    //      updateString3.append("<http://example/egbook6> dc:title  \"Title6\" ");
    //      updateString3.append("}");
    //      updateString3.append("INSERT { ");
    //      updateString3.append("<http://example/egbook6> dc:title  \"New Title6\" ");
    //      updateString3.append("}");
    //   
    //      UpdateAction.parseExecute(updateString3.toString(), newModel);

    //      UpdateAction.parseExecute(   "prefix exp: <http://www.example.de>"+
    //                           "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"+
    //                           "INSERT { graph <http://www.defaultgraph.de/graph1> {"+
    //                           "   <http://www.test.de#substructure1> <exp:has_relation3> <http://www.test.de#substructure2> ."+ 
    //                           "   <http://www.test.de#substructure1> <rdf:type> <http://www.test.de#substructuretype1> ."+ 
    //                           "   <http://www.test.de#substructure2> <rdf:type> <http://www.test.de#substructuretype2> ."+
    //                           "}}", newModel2);
    //      
    //      iter = newModel.listStatements();
    //      System.out.println("After update");
    //      while (iter.hasNext()) {
    //         System.out.println(iter.next().toString());
    //            
    //      }
}

From source file:org.arsenal.framework.core.loader.ShadowingClassLoader.java

public static void main(String[] args) {
    ClassLoader loader = ClassLoader.getSystemClassLoader();
    ShadowingClassLoader shadowLoader = new ShadowingClassLoader(loader);
    boolean shadow = shadowLoader.isEligibleForShadowing("SegSyncJobTaskMain");
    System.out.println(shadow);//from   w  ww. j  a  va 2 s  .  c o m
    //shadowLoader.loadClass(name);
}

From source file:Main.java

/**
 * @param clzName class name/*from  w w  w  .jav  a2 s  . co  m*/
 * @return the Class object if the class is exists, else null
 */
public static Class loadClass(String clzName) {
    try {
        return ClassLoader.getSystemClassLoader().loadClass(clzName);
    } catch (Exception e) {
    }
    return null;
}

From source file:Main.java

public static DexClassLoader createDexClassLoader(Context context, String dexPath, String optimizedDir,
        String nativeLibDir, boolean isDependent) {
    ClassLoader parentClassLoader;
    if (isDependent) {
        parentClassLoader = ClassLoader.getSystemClassLoader().getParent();
    } else {//  w w w  .  j  a  v a  2s. co m
        parentClassLoader = context.getClassLoader();
    }
    return new DexClassLoader(dexPath, optimizedDir, nativeLibDir, parentClassLoader);
}

From source file:Main.java

private static List<InputStream> loadResources(String name, ClassLoader classLoader) throws IOException {
    final List<InputStream> list = new ArrayList<InputStream>();
    final Enumeration<URL> systemResources = (classLoader == null ? ClassLoader.getSystemClassLoader()
            : classLoader).getResources(name);
    while (systemResources.hasMoreElements()) {
        list.add(systemResources.nextElement().openStream());
    }/*from w  ww  .  j a  v  a 2  s . co m*/
    return list;
}

From source file:PropertyLoader.java

public static Properties loadProperties(String name, ClassLoader loader) throws Exception {
    if (name.startsWith("/"))
        name = name.substring(1);//from   ww w  . ja v a 2 s. co m
    if (name.endsWith(SUFFIX))
        name = name.substring(0, name.length() - SUFFIX.length());
    Properties result = new Properties();
    InputStream in = null;
    if (loader == null)
        loader = ClassLoader.getSystemClassLoader();
    if (LOAD_AS_RESOURCE_BUNDLE) {
        name = name.replace('/', '.');
        ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault(), loader);
        for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
            result.put((String) keys.nextElement(), rb.getString((String) keys.nextElement()));
        }
    } else {
        name = name.replace('.', '/');
        if (!name.endsWith(SUFFIX))
            name = name.concat(SUFFIX);
        in = loader.getResourceAsStream(name);
        if (in != null) {
            result = new Properties();
            result.load(in); // can throw IOException
        }
    }
    in.close();
    return result;
}