Example usage for java.io File toURL

List of usage examples for java.io File toURL

Introduction

In this page you can find the example usage for java.io File toURL.

Prototype

@Deprecated
public URL toURL() throws MalformedURLException 

Source Link

Document

Converts this abstract pathname into a file: URL.

Usage

From source file:com.naryx.tagfusion.cfm.document.cfDOCUMENT.java

@SuppressWarnings("deprecation")
private String handleDocument(cfSession _Session, InputStream _in, String _charset)
        throws IOException, dataNotSupportedException, cfmRunTimeException {
    String mimeType = getDynamic(_Session, "MIMETYPE").getString().toLowerCase();
    String charset = _charset;//  w  w  w  .j a v  a  2 s.  c om
    if (charset == null) {
        charset = "ISO-8859-1";
    }

    if (mimeType.equals("text/html")) {
        return IOUtils.toString(_in, charset);
    } else if (mimeType.equals("text/plain")) {
        String plainTxt = IOUtils.toString(_in, charset);
        return "<pre>" + escapeHtmlChars(plainTxt) + "</pre>";

    } else if (mimeType.startsWith("image/")) {
        File tmpFile = File.createTempFile("cfdoc", '.' + mimeType.substring(mimeType.indexOf('/') + 1));
        OutputStream fout = cfEngine.thisPlatform.getFileIO().getFileOutputStream(tmpFile);
        StreamUtil.copyTo(_in, fout);
        return "<img src=\"" + tmpFile.toURL() + "\"/>";
    } else {
        throw newRunTimeException(
                "Invalid MIMETYPE value. Supported values include text/html, text/plain, image/jpg, image/gif, image/png and image/bmp");
    }

}

From source file:org.tinygroup.jspengine.JspC.java

/**
 * Initializes the classloader as/if needed for the given
 * compilation context./*from   w  w  w  .  j  a v  a2  s  .  c o  m*/
 *
 * @param clctxt The compilation context
 * @throws IOException If an error occurs
 */
private void initClassLoader(JspCompilationContext clctxt) throws IOException {

    classPath = getClassPath();

    ClassLoader jspcLoader = getClass().getClassLoader();
    if (jspcLoader instanceof AntClassLoader) {
        classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath();
    }

    // Turn the classPath into URLs
    ArrayList urls = new ArrayList();
    StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator);
    while (tokenizer.hasMoreTokens()) {
        String path = tokenizer.nextToken();
        try {
            File libFile = new File(path);
            urls.add(libFile.toURL());
        } catch (IOException ioe) {
            // Failing a toCanonicalPath on a file that
            // exists() should be a JVM regression test,
            // therefore we have permission to freak uot
            throw new RuntimeException(ioe.toString());
        }
    }

    File webappBase = new File(uriRoot);
    if (webappBase.exists()) {
        File classes = new File(webappBase, "/WEB-INF/classes");
        try {
            if (classes.exists()) {
                classPath = classPath + File.pathSeparator + classes.getCanonicalPath();
                urls.add(classes.getCanonicalFile().toURL());
            }
        } catch (IOException ioe) {
            // failing a toCanonicalPath on a file that
            // exists() should be a JVM regression test,
            // therefore we have permission to freak out
            throw new RuntimeException(ioe.toString());
        }
        File lib = new File(webappBase, "/WEB-INF/lib");
        if (lib.exists() && lib.isDirectory()) {
            String[] libs = lib.list();
            for (int i = 0; i < libs.length; i++) {
                if (libs[i].length() < 5)
                    continue;
                String ext = libs[i].substring(libs[i].length() - 4);
                if (!".jar".equalsIgnoreCase(ext)) {
                    if (".tld".equalsIgnoreCase(ext)) {
                        log.warn("TLD files should not be placed in " + "/WEB-INF/lib");
                    }
                    continue;
                }
                try {
                    File libFile = new File(lib, libs[i]);
                    classPath = classPath + File.pathSeparator + libFile.getCanonicalPath();
                    urls.add(libFile.getCanonicalFile().toURL());
                } catch (IOException ioe) {
                    // failing a toCanonicalPath on a file that
                    // exists() should be a JVM regression test,
                    // therefore we have permission to freak out
                    throw new RuntimeException(ioe.toString());
                }
            }
        }
    }

    // What is this ??
    urls.add(new File(clctxt.getRealPath("/")).getCanonicalFile().toURL());

    URL urlsA[] = new URL[urls.size()];
    urls.toArray(urlsA);

    /* SJSAS 6327357
    loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
     */
    // START SJSAS 6327357
    ClassLoader sysClassLoader = initSystemClassLoader();
    if (sysClassLoader != null) {
        loader = new URLClassLoader(urlsA, sysClassLoader);
    } else {
        loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
    }
    // END SJSAS 6327357
}

From source file:com.moss.nomad.core.runner.Runner.java

public void run(String migrationPathName, MigrationHistory history, byte[] env) throws Exception {

    MigrationPath path = findPath(migrationPathName);
    if (path == null) {
        throw new RuntimeException("Cannot find a migration path by the name of '" + migrationPathName + "'");
    }//from  w w  w.  j a  v  a2s  . c om

    Set<MigrationDef> executed = new HashSet<MigrationDef>();
    for (Migration migration : history.migrations()) {
        executed.add(migration.def());
    }

    /*
     * NOTE: How we determine what migrations to perform could be a lot more
     * sophisticated. We aren't checking the history to make sure that
     * migrations are only executed in sequence. This is how schematrax
     * works, but we might want to improve on it.
     */

    List<MigrationPackage> unexecuted = new ArrayList<MigrationPackage>();
    for (MigrationPackage pkg : path.packages()) {

        if (!executed.contains(pkg.def())) {
            unexecuted.add(pkg);
        }
    }

    if (unexecuted.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No migrations remain to be executed, doing nothing.");
        }
        return;
    }

    final byte[] buffer = new byte[1024 * 10]; //10k buffer

    for (MigrationPackage pkg : unexecuted) {

        if (pkg.resources() == null) {
            throw new RuntimeException(
                    "Cannot perform migration, migration resource not available in migration jar: "
                            + pkg.def());
        }

        if (log.isDebugEnabled()) {
            log.debug("Executing migration: " + pkg.def());
        }

        Migration migration = new Migration(new Instant(), pkg.def());
        MigrationResources res = pkg.resources();

        List<URL> urls = new ArrayList<URL>();
        for (String req : res.classpath()) {

            String[] pathSegments = req.split("\\/");

            File copyTarget = workDir;
            for (String s : pathSegments) {
                copyTarget = new File(copyTarget, s);
            }

            if (!copyTarget.getParentFile().exists() && !copyTarget.getParentFile().mkdirs()) {
                throw new RuntimeException("Cannot create directory: " + copyTarget.getParentFile());
            }

            if (!copyTarget.exists()) {

                if (log.isDebugEnabled()) {
                    log.debug("Copying classpath resource " + req + " -> " + copyTarget);
                }

                JarEntry entry = packageJar.getJarEntry(req);

                if (entry == null) {
                    throw new RuntimeException("Expected package jar entry not found: " + req);
                }

                InputStream in = packageJar.getInputStream(entry);
                OutputStream out = new FileOutputStream(copyTarget);
                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                    out.write(buffer, 0, numRead);
                }
                in.close();
                out.close();
            }

            urls.add(copyTarget.toURL());
        }

        ClassLoader cl;
        {
            URL[] cp = urls.toArray(new URL[0]);
            cl = new URLClassLoader(cp, null);
        }

        Class clazz = cl.loadClass("com.moss.nomad.api.v1.ClassLoaderBridge");

        Method method = clazz.getMethod("execute", String.class, byte[].class);

        ClassLoader currentCl = Thread.currentThread().getContextClassLoader();
        try {
            firePreMigration(migration);

            /*
             * NOTE, the reason we're setting the context class loader here
             * is for java 5 compatibility. JAXBContext seems to load its
             * classes from the current thread context class loader. In
             * java 5 this causes problems, in java 6 it doesn't because
             * the JAXB stuff is in the boot classpath. Ah well.
             */

            Thread.currentThread().setContextClassLoader(cl);

            String stacktrace = (String) method.invoke(null, res.className(), env);

            Thread.currentThread().setContextClassLoader(currentCl);

            if (stacktrace != null) {
                throw new MigrationFailureException(stacktrace);
            }

            firePostMigration(migration);
        } catch (Exception ex) {
            Thread.currentThread().setContextClassLoader(currentCl);

            log.error("Failed to complete migration for migration-def " + pkg.def(), ex);
            fireMigrationFailure(migration, ex);
            throw ex;
        }
    }
}

From source file:edu.harvard.i2b2.navigator.CRCNavigator.java

protected Control createContents(Composite parent) {

    // local variable to get system fonts and colors
    Display display = parent.getDisplay();
    // todo dispose of fonts when page is closed?
    final Font headerFont = new Font(display, "Tahoma", 12, SWT.BOLD);
    final Font normalFont = new Font(display, "Tahoma", 12, SWT.NORMAL);
    final Font buttonFont = new Font(display, "Tahoma", 9, SWT.NORMAL);

    // set background color
    if (APP_CURRENT.equals(APP_PROD)) {
        backColor = display.getSystemColor(SWT.COLOR_WHITE);
    } else if (APP_CURRENT.equals(APP_TEST)) {
        backColor = display.getSystemColor(SWT.COLOR_GRAY);
        // default to dev
    } else {/*  ww  w.ja v  a  2s .c om*/
        backColor = display.getSystemColor(SWT.COLOR_DARK_GRAY);

    }

    final Color foreColor = display.getSystemColor(SWT.COLOR_BLACK);
    warningColor = display.getSystemColor(SWT.COLOR_YELLOW);
    // final Color textColor = display.getSystemColor(SWT.COLOR_BLACK);
    goColor = display.getSystemColor(SWT.COLOR_GREEN);
    badColor = display.getSystemColor(SWT.COLOR_RED);

    // create top composite
    Composite top = new Composite(parent, SWT.NONE);
    FormLayout topCompositeLayout = new FormLayout();
    // FormData topData=new FormData();
    top.setLayout(topCompositeLayout);

    // GridLayout topGridLayout = new GridLayout(1, false);
    // topGridLayout.numColumns = 1;
    // topGridLayout.marginWidth = 2;
    // topGridLayout.marginHeight = 2;
    // top.setLayout(topGridLayout);

    // BannerC composite
    banner = new Composite(top, SWT.NONE);

    FormData bannerData = new FormData();
    bannerData.left = new FormAttachment(0);
    bannerData.right = new FormAttachment(100);
    banner.setLayoutData(bannerData);

    // The Banner itself is configured and layout is set
    FormLayout bannerLayout = new FormLayout();
    bannerLayout.marginWidth = 2;
    bannerLayout.marginHeight = 2;
    bannerLayout.spacing = 5;
    banner.setLayout(bannerLayout);

    // banner.setBackground(grayColor);
    banner.setBackground(backColor);
    banner.setForeground(foreColor);

    // add banner components and then configure layout

    // the label on the left is added
    titleLabel = new Label(banner, SWT.NO_FOCUS);
    titleLabel.setBackground(backColor);
    titleLabel.setText(msTitle);
    titleLabel.setFont(headerFont);
    titleLabel.setForeground(foreColor);

    // the general application area toolbar is added
    titleToolBar = new ToolBar(banner, SWT.FLAT);
    titleToolBar.setBackground(backColor);
    titleToolBar.setFont(headerFont);

    // add query mode dropdown tool item
    // set initial text to userLoginMode variable
    titleToolItem = new ToolItem(titleToolBar, SWT.DROP_DOWN);
    titleToolItem.setText(userLoginMode);

    // create menu for dropdown, create menu items, and add listeners for
    // dropdown tool item
    // hard code replace with user detail bean from webservice login values
    // Changed to member variable userModes [] from bean
    // String [] modes={"Exploration Mode","Query Mode", "Ontology Mode"};
    menu = new Menu(banner.getShell(), SWT.POP_UP);

    // wait until after login to create menu items
    // addMenuItems(menu, userModes);

    /*
     * for (int i=0;i<userModes.length;i++){ MenuItem menuItem=new
     * MenuItem(menu,SWT.PUSH); menuItem.setText(userModes[i]);
     * menuItem.addSelectionListener(new SelectionAdapter() {
     * 
     * @Override public void widgetSelected(SelectionEvent event) {
     * Auto-generated method stub //note tabFolderIndex [0] is always on
     * login class MenuItem selected=(MenuItem)event.widget;
     * //System.out.println("titleToolItem="+selected.getText());
     * titleToolItem.setText(selected.getText());
     * //setTabFolderIndex(menu.indexOf(selected));
     * System.out.println("selected.getText="+selected.getText());
     * System.out.println("menu.indexOf(selected)="+menu.indexOf(selected));
     * setTabFolderIndex(menu.indexOf(selected));
     * 
     * //if (userModes[1].equals(selected.getText())){ //
     * setTabFolderIndex(1); //} //if
     * (userModes[2].equals(selected.getText())){ // setTabFolderIndex(2);
     * //} //if (userModes[0].equals(selected.getText())){ //
     * setTabFolderIndex(0); //} }
     * 
     * }); }
     */

    // add listener for toolbaritem
    titleToolItem.addListener(SWT.Selection, new DropDownListener(titleToolBar, menu));
    titleToolItem.setEnabled(false);

    // Authorization label is made
    authorizationLabel = new Label(banner, SWT.NO_FOCUS);
    authorizationLabel.setBackground(backColor);
    authorizationLabel.setText("Awaiting Authorization...");
    authorizationLabel.setAlignment(SWT.RIGHT);
    authorizationLabel.setFont(normalFont);
    authorizationLabel.setForeground(foreColor);

    // the staus indicator is shown
    statusLabel = new Label(banner, SWT.NO_FOCUS);
    statusLabel.setBackground(backColor);
    statusLabel.setText("Status:");
    statusLabel.setAlignment(SWT.RIGHT);
    statusLabel.setFont(normalFont);
    statusLabel.setForeground(foreColor);

    statusOvalLabel = new Label(banner, SWT.NO_FOCUS);
    statusOvalLabel.setBackground(backColor);
    statusOvalLabel.setToolTipText("Click to show error log");
    // statusOvalLabel.setAlignment(SWT.LEFT);
    // statusOvalLabel.setSize(16,16);
    // statusOvalLabel.setFont(normalFont);
    statusOvalLabel.setSize(20, 20);
    statusOvalLabel.setForeground(foreColor);
    statusOvalLabel.redraw();

    statusOvalLabel.addListener(SWT.Resize, new Listener() {

        public void handleEvent(Event arg0) {
            statusOvalLabel.setSize(20, 20);
            statusOvalLabel.redraw();
        }
    });

    // add selection listener so that clicking on status oval label shows
    // error log
    // dialog
    statusOvalLabel.addListener(SWT.MouseDown, new Listener() {

        public void handleEvent(Event arg0) {
            // log.info(getNow() + "Status Listener Clicked");
            Display display = statusOvalLabel.getDisplay();
            final Shell shell = statusOvalLabel.getShell();
            // run asyncExec so that other pending ui events finished first
            display.asyncExec(new Runnable() {

                public void run() {
                    // LoggerD loggerD = new LoggerD(shell);
                    // loggerD.open();
                    // final Shell myShell=shell;
                    File file = new File(logFileName);
                    URL url = null;
                    // Convert the file object to a URL with an absolute
                    // path
                    try {
                        url = file.toURL();
                    } catch (MalformedURLException e) {
                        log.info(e.getMessage());
                    }
                    final URL myurl = url;
                    new HelpBrowser().run(myurl.toString(), shell);
                }
            });
            // shows browser with logger in separate
            // showLoggerBrowser(shell).start();
        }
    });

    // add status label paint listener so that it changes color
    statusLabelPaintListener = new StatusLabelPaintListener();
    // statusLabelPaintListener.setOvalColor(warningColor);
    statusOvalLabel.addPaintListener(statusLabelPaintListener);

    statusLabelPaintListener.setOvalColor(display.getSystemColor(SWT.COLOR_YELLOW));
    statusOvalLabel.setSize(20, 20);
    statusOvalLabel.redraw();

    // Login button is made
    loginButton = new Button(banner, SWT.PUSH | SWT.LEFT);
    loginButton.setFont(buttonFont);
    loginButton.setText(BUTTON_TEXT_LOGIN);

    // add selection listener for login Button for login/logout from banner
    loginButton.addSelectionListener(new SelectionAdapter() {

        @Override
        // loginAction(true) logs in, loginAction(false) logs out
        public void widgetSelected(SelectionEvent event) {
            if (loginButton.getText().equals(BUTTON_TEXT_LOGIN)) {
                loginAction(true);
            } else {
                loginAction(false);
            }
        }
    });

    // right button is made
    final Button rightButton = new Button(banner, SWT.PUSH | SWT.LEFT);
    rightButton.setFont(buttonFont);
    rightButton.setText(" Help ");
    // These don't work on Windows
    // rightButton.setBackground(backColor);
    // rightButton.setForeground(foreColor);
    // add selection listener to show help browser in new window- separate
    // thread
    rightButton.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            // super.widgetSelected(arg0);
            final Button myButton = (Button) event.widget;
            // showHelpBrowser(myButton).start();
            Display display = myButton.getDisplay();
            final Shell myShell = myButton.getShell();
            display.asyncExec(new Runnable() {

                public void run() {
                    // LoggerD loggerD = new LoggerD(shell);
                    // loggerD.open();
                    // final Shell myShell=shell;
                    new HelpBrowser().run(helpURL, myShell);
                }
            });
        }
    });

    // top.pack();
    // int titleLabelHeight = titleLabel.getBounds().height;
    // System.out.println(titleLabelHeight);
    // layout and configure banner components

    // attach titlelabel to left and align vertically with tool bar
    FormData titleLabelFormData = new FormData();
    // titleLabelFormData.top = new FormAttachment(50, -(titleLabelHeight /
    // 2));
    // titleLabelFormData.bottom = new FormAttachment(100);
    titleLabelFormData.top = new FormAttachment(titleToolBar, 0, SWT.CENTER);
    titleLabelFormData.left = new FormAttachment(0, 10);
    titleLabel.setLayoutData(titleLabelFormData);

    // attach left of tool bar to title label, attach top to banner
    // attach right to authorization label so that it will resize and remain
    // visible when tool bar text changes
    FormData titleToolBarFormData = new FormData();
    titleToolBarFormData.left = new FormAttachment(titleLabel);
    titleToolBarFormData.top = new FormAttachment(0);
    titleToolBarFormData.right = new FormAttachment(authorizationLabel, 0, 0);

    // titleToolBarFormData.top = new FormAttachment(titleLabel,
    // -titleLabelHeight - 10);
    titleToolBar.setLayoutData(titleToolBarFormData);

    // attach authorization label on right to status label and center
    // vertically

    FormData authorizationLabelFormData = new FormData();
    authorizationLabelFormData.right = new FormAttachment(statusLabel, -10);
    // authorizationLabelFormData.top = new
    // FormAttachment(topCanvas,-titleLabelHeight-10);
    authorizationLabelFormData.top = new FormAttachment(statusLabel, 0, SWT.CENTER);
    authorizationLabel.setLayoutData(authorizationLabelFormData);

    FormData statusLabelFormData = new FormData();
    // statusLabelFormData.right = new FormAttachment(rightButton,0);
    statusLabelFormData.right = new FormAttachment(statusOvalLabel, 0);
    statusLabelFormData.top = new FormAttachment(statusOvalLabel, 0, SWT.CENTER);
    statusLabel.setLayoutData(statusLabelFormData);

    // attach status label on right to loginbutton and center vertically

    FormData statusOvalLabelFormData = new FormData();
    // statusLabelFormData.right = new FormAttachment(rightButton,0);
    // add offset
    statusOvalLabelFormData.right = new FormAttachment(loginButton, -25);
    statusOvalLabelFormData.top = new FormAttachment(loginButton, 0, SWT.CENTER);
    statusOvalLabel.setLayoutData(statusOvalLabelFormData);

    // attach login button on right to right button and center vertically
    FormData loginButtonFormData = new FormData();
    // loginButtonFormData.right = new FormAttachment(100,-10);
    loginButtonFormData.right = new FormAttachment(rightButton);
    loginButtonFormData.top = new FormAttachment(rightButton, 0, SWT.CENTER);
    // loginButtonFormData.top = new FormAttachment(50,
    // -(titleLabelHeight / 2) - 2);
    loginButton.setLayoutData(loginButtonFormData);

    // attach right button to right of banner and center vertically on
    // toolbar
    FormData rightButtonFormData = new FormData();
    rightButtonFormData.right = new FormAttachment(100, -10);
    rightButtonFormData.top = new FormAttachment(titleToolBar, 0, SWT.CENTER);
    // rightButtonFormData.top = new FormAttachment(50,
    // -(titleLabelHeight / 2) - 2);
    rightButton.setLayoutData(rightButtonFormData);

    // banner.pack();

    // create tab folder underneath but hide tabs
    // don't contruct tab items until after login
    tabFolder = new TabFolder(top, SWT.NONE);

    FormData tabFolderData = new FormData();
    tabFolderData.top = new FormAttachment(banner, tabFolderOffset);
    tabFolderData.left = new FormAttachment(0);
    tabFolderData.right = new FormAttachment(100);
    tabFolderData.bottom = new FormAttachment(100);
    tabFolder.setLayoutData(tabFolderData);

    return top;
}

From source file:be.docarch.odt2braille.PEF.java

/**
 * Determine which symbols to display in list of special symbols
 *//*from  w  w w . j  av a2s  . c o m*/
private void extractSpecialSymbols(File bodyFile, Volume volume, int volumeCount, Configuration settings)
        throws IOException {

    List<SpecialSymbol> specialSymbols = new ArrayList();

    String volumeNode = "dtb:volume";
    String id = volume.getIdentifier();
    if (id != null) {
        volumeNode += "[@id='" + id + "']";
    }

    for (SpecialSymbol symbol : settings.getSpecialSymbolList().values()) {

        switch (symbol.getMode()) {
        case NEVER:
            break;
        case ALWAYS:
            specialSymbols.add(symbol);
            break;
        case FIRST_VOLUME:
            if (volumeCount == 0) {
                specialSymbols.add(symbol);
            }
            break;
        case IF_PRESENT_IN_VOLUME:
            if (!(volume instanceof PreliminaryVolume)) {
                switch (symbol.getType()) {
                case NOTE_REFERENCE_INDICATOR:
                    if (XPathUtils.evaluateBoolean(bodyFile.toURL().openStream(),
                            "//" + volumeNode + "//dtb:note[@class='footnote' or @class='endnote']",
                            namespace)) {
                        specialSymbols.add(symbol);
                    }
                    break;
                case TRANSCRIBERS_NOTE_INDICATOR:
                    if (XPathUtils.evaluateBoolean(bodyFile.toURL().openStream(),
                            "//" + volumeNode + "//dtb:div[@class='tn']/dtb:note", namespace)) {
                        specialSymbols.add(symbol);
                    }
                    break;
                case ITALIC_INDICATOR:
                    if (XPathUtils.evaluateBoolean(bodyFile.toURL().openStream(),
                            "//" + volumeNode + "//dtb:em[not(@class='reset')]", namespace)) {
                        specialSymbols.add(symbol);
                    }
                    break;
                case BOLDFACE_INDICATOR:
                    if (XPathUtils.evaluateBoolean(bodyFile.toURL().openStream(),
                            "//" + volumeNode + "//dtb:strong[not(@class='reset')]", namespace)) {
                        specialSymbols.add(symbol);
                    }
                    break;
                case ELLIPSIS:
                    if (XPathUtils.evaluateBoolean(bodyFile.toURL().openStream(),
                            "//" + volumeNode + "//dtb:flag[@class='ellipsis']", namespace)) {
                        specialSymbols.add(symbol);
                    }
                    break;
                case DOUBLE_DASH:
                    if (XPathUtils.evaluateBoolean(bodyFile.toURL().openStream(),
                            "//" + volumeNode + "//dtb:flag[@class='double-dash']", namespace)) {
                        specialSymbols.add(symbol);
                    }
                    break;
                default:
                }
            }
            break;
        }
    }

    volume.setSpecialSymbols(specialSymbols);
}

From source file:com.cyberway.issue.crawler.settings.XMLSettingsHandler.java

/** Read the CrawlerSettings object from a specific file.
 *
 * @param settings the settings object to be updated with data from the
 *                 persistent storage./* w  w  w .  ja  v a  2  s  . c  o  m*/
 * @param f the file to read from.
 * @return the updated settings object or null if there was no data for this
 *         in the persistent storage.
 */
protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) {
    CrawlerSettings result = null;
    try {
        InputStream is = null;
        if (!f.exists()) {
            // Perhaps the file we're looking for is on the CLASSPATH.
            // DON'T look on the CLASSPATH for 'settings.xml' files.  The
            // look for 'settings.xml' files happens frequently. Not looking
            // on classpath for 'settings.xml' is an optimization based on
            // ASSUMPTION that there will never be a 'settings.xml' saved
            // on classpath.
            if (!f.getName().startsWith(settingsFilename)) {
                is = XMLSettingsHandler.class.getResourceAsStream(f.getPath());
            }
        } else {
            is = new FileInputStream(f);
        }
        if (is != null) {
            XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            InputStream file = new BufferedInputStream(is);
            parser.setContentHandler(new CrawlSettingsSAXHandler(settings));
            InputSource source = new InputSource(file);
            source.setSystemId(f.toURL().toExternalForm());
            parser.parse(source);
            result = settings;
        }
    } catch (SAXParseException e) {
        logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber()
                + ", column: " + e.getColumnNumber());
    } catch (SAXException e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (ParserConfigurationException e) {
        logger.warning(e.getMessage() + ": " + e.getCause().getMessage());
    } catch (FactoryConfigurationError e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (IOException e) {
        logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage());
    }
    return result;
}

From source file:org.archive.crawler.settings.XMLSettingsHandler.java

/** Read the CrawlerSettings object from a specific file.
 *
 * @param settings the settings object to be updated with data from the
 *                 persistent storage./* ww  w  .java 2s. c om*/
 * @param f the file to read from.
 * @return the updated settings object or null if there was no data for this
 *         in the persistent storage.
 */
protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) {
    CrawlerSettings result = null;
    try {
        InputStream is = null;
        if (!f.exists()) {
            // Perhaps the file we're looking for is on the CLASSPATH.
            // DON'T look on the CLASSPATH for 'settings.xml' files.  The
            // look for 'settings.xml' files happens frequently. Not looking
            // on classpath for 'settings.xml' is an optimization based on
            // ASSUMPTION that there will never be a 'settings.xml' saved
            // on classpath.
            if (!f.getName().startsWith(settingsFilename)) {
                is = XMLSettingsHandler.class.getResourceAsStream(toResourcePath(f));
            }
        } else {
            is = new FileInputStream(f);
        }
        if (is != null) {
            XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            InputStream file = new BufferedInputStream(is);
            parser.setContentHandler(new CrawlSettingsSAXHandler(settings));
            InputSource source = new InputSource(file);
            source.setSystemId(f.toURL().toExternalForm());
            parser.parse(source);
            result = settings;
        }
    } catch (SAXParseException e) {
        logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber()
                + ", column: " + e.getColumnNumber());
    } catch (SAXException e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (ParserConfigurationException e) {
        logger.warning(e.getMessage() + ": " + e.getCause().getMessage());
    } catch (FactoryConfigurationError e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (IOException e) {
        logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage());
    }
    return result;
}

From source file:org.ops4j.pax.url.assembly.internal.ResourceAssembly.java

private void scan(final Source source, final MergePolicy policy) throws IOException {
    // try out an url
    LOGGER.trace("Searching for [" + source + "]");
    final String path = source.path();
    URL url = null;/*from ww w  .j  a  va2 s.  com*/
    try {
        url = new URL(path);
    } catch (MalformedURLException ignore) {
        // ignore this as the spec may be resolved other way
        LOGGER.trace(String.format("Path [%s] is not a valid url. Reason: %s. Continue discovery...", path,
                ignore.getMessage()));
    }
    File file = null;
    if (url != null && "file".equals(url.getProtocol()))
    // if we have an url and it's a file url
    {
        try {
            final URI uri = new URI(url.toExternalForm().replaceAll(" ", "%20"));
            file = new File(uri);
        } catch (URISyntaxException ignore) {
            // ignore this as the spec may be resolved other way
            LOGGER.trace(String.format("Path [%s] is not a valid url. Reason: %s. Continue discovery...", path,
                    ignore.getMessage()));
        }
    } else
    // if we don't have an url then let's try out a direct file
    {
        file = new File(path);
    }
    if (file != null && file.exists())
    // if we have a directory
    {
        if (file.isDirectory()) {
            list(file, new DirectoryLister(file, source.includes(), source.excludes()), policy);
            return;
        } else {
            LOGGER.trace(String.format("Path [%s] is not a valid directory. Continue discovery...", path));
        }
    } else {
        LOGGER.trace(String.format("Path [%s] is not a valid file. Continue discovery...", path));
    }
    // on this point we may have a zip
    try {
        ZipFile zip = null;
        URL baseUrl = null;
        if (file != null && file.exists())
        // try out a zip from the file we have
        {
            zip = new ZipFile(file);
            baseUrl = file.toURL();
        } else if (url != null) {
            zip = new ZipFile(url.toExternalForm());
            baseUrl = url;
        }
        if (zip != null && baseUrl != null) {
            list(new ZipLister(baseUrl, zip.entries(), source.includes(), source.excludes()), policy);
            return;
        }
    } catch (IOException ignore) {
        // ignore for the moment
        LOGGER.trace(String.format("Path [%s] is not a valid zip. Reason: %s. Continue discovery...", path,
                ignore.getMessage()));
    }
    // finally try with a zip protocol
    if (url != null && !url.toExternalForm().startsWith("jar")) {
        try {
            final URL jarUrl = new URL("jar:" + url.toURI().toASCIIString() + "!/");
            final JarURLConnection jar = (JarURLConnection) jarUrl.openConnection();
            list(new ZipLister(url, jar.getJarFile().entries(), source.includes(), source.excludes()), policy);
            return;
        } catch (IOException ignore) {
            LOGGER.trace(String.format("Path [%s] is not a valid jar. Reason: %s", path, ignore.getMessage()));
        } catch (URISyntaxException ignore) {
            LOGGER.trace(String.format("Path [%s] is not a valid jar. Reason: %s", path, ignore.getMessage()));
        }
    }
    // if we got to this point then we cannot go further
    LOGGER.trace(String.format("Source [%s] cannot be used. Stopping.", source));
    throw new HierarchicalIOException(String.format("Source [%s] cannot be used. Stopping.", source));
}

From source file:org.talend.librariesmanager.ui.dialogs.ConfigModuleDialog.java

@Override
protected void okPressed() {
    String originalURI = null;/*from ww  w  . j  ava  2 s  .  c om*/
    String customURI = null;
    originalURI = defaultUriTxt.getText().trim();
    defaultURI = originalURI;
    if (useCustomBtn.getSelection()) {
        customURI = MavenUrlHelper.addTypeForMavenUri(customUriText.getText().trim(), moduleName);
    }
    urlToUse = !StringUtils.isEmpty(customURI) ? customURI : originalURI;
    if (repositoryRadioBtn.getSelection()) {
        if (installRadioBtn.getSelection()) {
            final File file = new File(jarPathTxt.getText().trim());
            final IRunnableWithProgress acceptOursProgress = new IRunnableWithProgress() {

                @Override
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    monitor.beginTask("Install module " + file.getName(), 100);
                    monitor.worked(10);
                    DisplayUtils.getDisplay().syncExec(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                LibManagerUiPlugin.getDefault().getLibrariesService()
                                        .deployLibrary(file.toURL(), urlToUse);
                            } catch (IOException e) {
                                ExceptionHandler.process(e);
                            }
                        }
                    });
                    monitor.done();
                }
            };

            ProgressMonitorDialog dialog = new ProgressMonitorDialog(
                    PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
            try {
                dialog.run(true, true, acceptOursProgress);
            } catch (Throwable e) {
                if (!(e instanceof TimeoutException)) {
                    ExceptionHandler.process(e);
                }
            }
        }
    }

    ModuleNeeded testModule = new ModuleNeeded("", "", true, originalURI);
    String oldCustomUri = testModule.getCustomMavenUri();
    boolean saveCustomMap = !StringUtils.equals(customURI, oldCustomUri);
    Set<String> modulesNeededNames = ModulesNeededProvider.getAllManagedModuleNames();
    boolean isCutomJar = !ModulesNeededProvider.getAllModuleNamesFromIndex().contains(moduleName);
    if (isCutomJar && customURI == null) {
        // key and value will be the same for custom jar if without custom uri
        customURI = urlToUse;
    }
    if (!modulesNeededNames.contains(moduleName)) {
        ModulesNeededProvider.addUnknownModules(moduleName, originalURI, false);
        saveCustomMap = true;
    }

    // change the custom uri
    if (saveCustomMap && ModulesNeededProvider.getAllModuleNamesFromIndex().contains(moduleName)) {
        testModule.setCustomMavenUri(customURI);
        ILibraryManagerService libManagerService = (ILibraryManagerService) GlobalServiceRegister.getDefault()
                .getService(ILibraryManagerService.class);
        libManagerService.saveCustomMavenURIMap();
    }

    LibManagerUiPlugin.getDefault().getLibrariesService().checkLibraries();
    setReturnCode(OK);
    close();
}

From source file:org.tranche.util.EmailUtil.java

/**
 * <p>Send an email. A blocking operation.</p>
 * @param subject/*from w  ww  .  j  a v a 2 s .  c  om*/
 * @param recipients
 * @param message
 * @param attachment
 * @throws java.io.IOException
 */
public static void sendEmailHttp(String subject, String[] recipients, String message, File attachment)
        throws IOException {
    InputStream is = null;
    try {
        // dummy check - are there recipients?
        if (recipients == null || recipients.length == 0 || recipients[0] == null || recipients[0].equals("")) {
            throw new RuntimeException("No recipients specified.");
        } // is there a subject?
        else if (subject == null) {
            throw new RuntimeException("No subject specified.");
        } // is there a message?
        else if (message == null) {
            throw new RuntimeException("No message specified.");
        }

        // make a new client
        HttpClient c = new HttpClient();
        PostMethod pm = new PostMethod(
                ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_EMAIL_URL));

        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("network",
                ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_NAME)));

        // put together the recipients
        String toStr = "";
        for (String recipient : recipients) {
            toStr = toStr + recipient + ", ";
        }
        toStr = toStr.substring(0, toStr.length() - 2);
        params.add(new NameValuePair("to", toStr));

        String toSignature = "";
        {
            ByteArrayInputStream bais = null;
            try {
                bais = new ByteArrayInputStream(toStr.getBytes());
                toSignature = String.valueOf(SecurityUtil.sign(bais, SecurityUtil.getEmailKey(),
                        SecurityUtil.getEmailCertificate().getSigAlgName()));
            } catch (Exception e) {
            } finally {
                IOUtil.safeClose(bais);
            }
        }
        params.add(new NameValuePair("toSignature", toSignature));
        String signatureAlgorithm = "";
        try {
            signatureAlgorithm = SecurityUtil.getEmailCertificate().getSigAlgName();
        } catch (Exception e) {
        }
        params.add(new NameValuePair("signatureAlgorithm", signatureAlgorithm));
        params.add(new NameValuePair("subject", subject));
        params.add(new NameValuePair("message", message));
        if (attachment != null) {
            params.add(new NameValuePair("attachment", attachment.getName()));
            is = attachment.toURL().openStream();
            pm.setRequestBody(is);
        }
        pm.setQueryString(params.toArray(new NameValuePair[] {}));

        int code = c.executeMethod(pm);
        if (code != 200) {
            if (code == 506) {
                throw new RuntimeException("Network not found.");
            } else if (code == 507) {
                throw new RuntimeException("Validation failed.");
            } else if (code == 508) {
                throw new RuntimeException("To cannot be blank.");
            } else if (code == 509) {
                throw new RuntimeException("Subject cannot be blank.");
            } else if (code == 510) {
                throw new RuntimeException("Message cannot be blank.");
            } else if (code == 511) {
                throw new RuntimeException("Network cannot be blank.");
            } else if (code == 512) {
                throw new RuntimeException("To Signature cannot be blank.");
            } else if (code == 513) {
                throw new RuntimeException("Invalid signature for To field.");
            } else if (code == 514) {
                throw new RuntimeException("Signature algorithm cannot be blank.");
            } else {
                throw new RuntimeException("Email could not be sent (response code = " + code + ").");
            }
        }
    } finally {
        IOUtil.safeClose(is);
    }
}