Example usage for java.io File getCanonicalFile

List of usage examples for java.io File getCanonicalFile

Introduction

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

Prototype

public File getCanonicalFile() throws IOException 

Source Link

Document

Returns the canonical form of this abstract pathname.

Usage

From source file:org.apache.axis2.deployment.repository.util.ArchiveReader.java

/**
 * Creats AxisService.//  w w  w .ja  v  a 2 s.  co m
 *
 * @param in
 * @return Returns AxisService.
 * @throws DeploymentException
 */
private List<AxisService> processWSDLFile(WSDLToAxisServiceBuilder axisServiceBuilder, File serviceArchiveFile,
        boolean isArchive, InputStream in, String baseURI) throws DeploymentException {
    try {

        if (serviceArchiveFile != null && isArchive) {
            axisServiceBuilder.setCustomResolver(new AARFileBasedURIResolver(serviceArchiveFile));
            if (axisServiceBuilder instanceof WSDL11ToAllAxisServicesBuilder) {

                ((WSDL11ToAllAxisServicesBuilder) axisServiceBuilder)
                        .setCustomWSDLResolver(new AARBasedWSDLLocator(baseURI, serviceArchiveFile, in));

                ((WSDL11ToAllAxisServicesBuilder) axisServiceBuilder)
                        .setDocumentBaseUri(serviceArchiveFile.getCanonicalFile().toURI().toString());

            } else if (axisServiceBuilder instanceof WSDL20ToAllAxisServicesBuilder) {
                ((WSDL20ToAllAxisServicesBuilder) axisServiceBuilder)
                        .setCustomWSDLResolver(new AARBasedWSDLLocator(baseURI, serviceArchiveFile, in));
                // trying to use the jar scheme as the base URI. I think this can be used to handle
                // wsdl 1.1 as well without using a custom URI resolver. Need to look at it later.
                axisServiceBuilder.setBaseUri("jar:file://" + serviceArchiveFile.toURI() + "!/" + baseURI);
            }
        } else {
            if (serviceArchiveFile != null) {
                axisServiceBuilder.setBaseUri(serviceArchiveFile.getParentFile().toURI().toString());

                if (axisServiceBuilder instanceof WSDL11ToAllAxisServicesBuilder) {
                    ((WSDL11ToAllAxisServicesBuilder) axisServiceBuilder)
                            .setDocumentBaseUri(serviceArchiveFile.getCanonicalFile().toURI().toString());
                }
            }
        }
        if (axisServiceBuilder instanceof WSDL11ToAllAxisServicesBuilder) {
            return ((WSDL11ToAllAxisServicesBuilder) axisServiceBuilder).populateAllServices();
        } else if (axisServiceBuilder instanceof WSDL20ToAllAxisServicesBuilder) {
            return ((WSDL20ToAllAxisServicesBuilder) axisServiceBuilder).populateAllServices();
        }
    } catch (AxisFault axisFault) {
        log.info("Trouble processing wsdl file :" + axisFault.getMessage());
        if (log.isDebugEnabled()) {
            log.debug(axisFault);
        }
    } catch (IOException ioex) {
        log.info("Trouble processing wsdl file :" + ioex.getMessage());
        if (log.isDebugEnabled()) {
            log.debug(ioex);
        }
    }
    return null;
}

From source file:com.adito.core.CoreServlet.java

void checkDevEnvironment() throws ServletException {
    devConfig = "true".equalsIgnoreCase(SystemProperties.get("adito.useDevConfig", "false"));
    File defaultDevConfDir = new File(SystemProperties.get("user.dir"), "conf");
    try {//from   w  w w.j a v a  2  s . c  om
        if (devConfig && ContextHolder.getContext().getConfDirectory().getCanonicalFile()
                .equals(defaultDevConfDir.getCanonicalFile())) {
            throw new ServletException("When running in developmenet mode, you may NOT use "
                    + defaultDevConfDir.getAbsolutePath() + " as your 'conf' directory. Please specifiy "
                    + "a different directory using the --conf=<dir> argument when starting the server.");
        }
    } catch (IOException ioe) {
        throw new ServletException("Failed to determine if incorrect conf directory is being used", ioe);
    }
}

From source file:com.sslexplorer.core.CoreServlet.java

void checkDevEnvironment() throws ServletException {
    devConfig = "true".equalsIgnoreCase(SystemProperties.get("sslexplorer.useDevConfig", "false"));
    File defaultDevConfDir = new File(SystemProperties.get("user.dir"), "conf");
    try {//from  w w w .ja v a  2s.c  o  m
        if (devConfig && ContextHolder.getContext().getConfDirectory().getCanonicalFile()
                .equals(defaultDevConfDir.getCanonicalFile())) {
            throw new ServletException("When running in developmenet mode, you may NOT use "
                    + defaultDevConfDir.getAbsolutePath() + " as your 'conf' directory. Please specifiy "
                    + "a different directory using the --conf=<dir> argument when starting the server.");
        }
    } catch (IOException ioe) {
        throw new ServletException("Failed to determine if incorrect conf directory is being used", ioe);
    }
}

From source file:de.adv_online.aaa.katalogtool.KatalogDialog.java

public void initialise(Converter c, Options o, ShapeChangeResult r, String mdl)
        throws ShapeChangeAbortException {

    try {/*from   w  w  w .ja va  2  s  . co m*/
        String msg = "Akzeptieren Sie die in der mit diesem Tool ausgelieferten Datei 'Lizenzbedingungen zur Nutzung von Softwareskripten.doc' beschriebenen Lizenzbedingungen?"; // Meldung
        if (msg != null) {
            Object[] options = { "Ja", "Nein" };
            int val = JOptionPane.showOptionDialog(null, msg, "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
            if (val == 1)
                System.exit(0);
        }
    } catch (Exception e) {
        System.out.println("Fehler in Dialog: " + e.toString());
    }

    options = o;

    File eapFile = new File(mdl);
    try {
        eap = eapFile.getCanonicalFile().getAbsolutePath();
    } catch (IOException e) {
        eap = "ERROR.eap";
    }

    converter = new Converter(options, r);
    result = r;
    modelTransformed = false;
    transformationRunning = false;

    StatusBoard.getStatusBoard().registerStatusReader(this);

    // frame
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    // panel
    newContentPane = new JPanel(new BorderLayout());
    newContentPane.setOpaque(true);
    setContentPane(newContentPane);

    // target elements
    for (String label : targetLabels) {
        try {
            TargetGuiElements t = new TargetGuiElements(this, label);
            targetGuiElems.put(label, t);
        } catch (Exception e) {
            throw new ShapeChangeAbortException("Fatal error while creating dialog elements for target " + label
                    + ".\nMessage: " + eap.toString() + "\nPlease check configuration file.");
        }
    }

    //JTabbedPane tabbedPane = new JTabbedPane();
    //tabbedPane.addTab("Main options", createMainTab());

    newContentPane.add(createMainTab(), BorderLayout.CENTER);

    statusBar = new StatusBar();

    Box fileBox = Box.createVerticalBox();
    fileBox.add(createStartPanel());
    fileBox.add(statusBar);

    newContentPane.add(fileBox, BorderLayout.SOUTH);

    // frame size
    int height = 720;
    int width = 600;

    pack();

    Insets fI = getInsets();
    setSize(width + fI.right + fI.left, height + fI.top + fI.bottom);
    Dimension sD = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((sD.width - width) / 2, (sD.height - height) / 2);
    this.setMinimumSize(new Dimension(width, height));

    // frame closing
    WindowListener listener = new WindowAdapter() {
        public void windowClosing(WindowEvent w) {
            //JOptionPane.showMessageDialog(null, "Nein", "NO", JOptionPane.ERROR_MESSAGE);
            closeDialog();
        }
    };
    addWindowListener(listener);
}

From source file:com.planet57.gshell.internal.FileSystemAccessImpl.java

@Override
public File resolveFile(@Nullable File baseDir, @Nullable final String path) throws IOException {
    File userDir = getUserDir();/*  ww w.ja v  a 2 s. co m*/

    if (baseDir == null) {
        baseDir = userDir;
    }

    File file;
    if (path == null) {
        file = baseDir;
    } else if (path.startsWith("~")) {
        File userHome = getUserHomeDir();
        file = new File(userHome.getPath() + path.substring(1));
    } else {
        file = new File(path);
    }

    // support paths like "<drive>:" and "/" on windows
    if (OperatingSystem.WINDOWS) {
        if (path != null && path.equals("/")) {
            // Get the current canonical path to access drive root
            String tmp = new File(".").getCanonicalPath().substring(0, 2);
            return new File(tmp + "/").getCanonicalFile();
        }

        String tmp = file.getPath();
        if (tmp.length() == 2 && tmp.charAt(1) == ':') {
            // Have to append "/" on windows it seems to get the right root
            return new File(tmp + "/").getCanonicalFile();
        }
    }

    if (!file.isAbsolute()) {
        file = new File(baseDir, file.getPath());
    }

    return file.getCanonicalFile();
}

From source file:org.apache.cordova.plugins.DownloadManager.Downloader.java

public Boolean run() throws InterruptedException, JSONException {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            NotificationManager mNotifyManager;
            NotificationCompat.Builder mBuilder;
            Intent intent;/*from  w  w w .j  av a  2s  .c  o  m*/
            PendingIntent pend;
            int mNotificationId;

            Log.d("PhoneGapLog", "dirName:  " + dirName);
            Log.d("PhoneGapLog", "fileName: " + fileName);
            try {

                File dir = new File(dirName);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                File file = new File(dirName, fileName);
                if (file.exists() && !overwrite) {
                    String temp_filename;
                    int i;
                    for (i = 1;; i++) { // test.txt -> test_1.txt -> test_2.tx -> ... while(file.exists())
                        temp_filename = fileName.substring(0, fileName.lastIndexOf('.')) + "_"
                                + String.valueOf(i) + fileName.substring(fileName.lastIndexOf('.'));
                        file = new File(dirName, temp_filename);
                        if (!file.exists()) {
                            fileName = temp_filename;
                            break;
                        }
                    }
                } else if (file.exists() && overwrite) {
                    file.getCanonicalFile().delete(); //Delete
                    file = new File(dirName, fileName); //Declare the same
                }

                intent = new Intent();
                intent.putExtra("cancel_download", 1);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                pend = PendingIntent.getActivity(cordova.getActivity(), 0, intent,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                mNotifyManager = (NotificationManager) cordova.getActivity()
                        .getSystemService(Activity.NOTIFICATION_SERVICE);
                mBuilder = new NotificationCompat.Builder(cordova.getActivity())
                        /*.setSmallIcon(android.R.drawable.ic_stat_notification)*/
                        .setContentTitle(notificationTitle)
                        /*.setSubText("Tap to CANCEL")*/
                        .setTicker(ticker).setContentIntent(pend).setContentText("0% - " + fileName);

                mNotificationId = new Random().nextInt(10000);

                URL url = new URL(fileUrl);
                HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
                ucon.setRequestMethod("GET");
                ucon.connect();
                InputStream is = ucon.getInputStream();
                byte[] buffer = new byte[1024];
                int readed = 0, progress = 0, totalReaded = 0, fileSize = ucon.getContentLength();

                // First Notification (id to Javascript) (not necessary necessary): 
                informProgress(id, true, fileSize, 0, dirName, fileName, callbackContext);

                FileOutputStream fos = new FileOutputStream(file);
                showToast(startToast, "short");
                int step = 0;
                while ((readed = is.read(buffer)) > 0 && downloading_ids.isId(id)) {
                    fos.write(buffer, 0, readed);
                    totalReaded += readed;
                    int newProgress = (int) (totalReaded * 100 / fileSize);
                    if (newProgress != progress & newProgress > step) {
                        if (useNotificationBar) {
                            mBuilder.setProgress(100, newProgress, false);
                            mBuilder.setContentText(step + "% - " + fileName);
                            mBuilder.setContentIntent(pend);
                            mNotifyManager.notify(mNotificationId, mBuilder.build());
                        }
                        informProgress(id, true, fileSize, step, dirName, fileName, callbackContext);
                        step = step + 1;
                    }
                }
                // Download canceled??
                if (!downloading_ids.isId(id)) {
                    showToast(cancelToast, "short");

                    fos.flush();
                    fos.close();
                    is.close();
                    ucon.disconnect();

                    if (useNotificationBar) {
                        mBuilder.setContentText("Download of \"" + fileName + "\" canceled").setProgress(0, 0,
                                false);
                        mNotifyManager.notify(mNotificationId, mBuilder.build());

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            Log.d("PhoneGapLog", "Downloader Plugin: Thread sleep error: " + e);
                        }

                        mNotifyManager.cancel(mNotificationId);
                    }

                    // Delete file:
                    file.getCanonicalFile().delete();

                    callbackContext.sendPluginResult(
                            new PluginResult(PluginResult.Status.OK, "Download properly canceled"));
                } else {
                    // Download Normal END (continue)
                    if (useNotificationBar) {
                        mBuilder.setContentText("Download of \"" + fileName + "\" completed").setProgress(0, 0,
                                false);
                        mNotifyManager.notify(mNotificationId, mBuilder.build());
                    }
                    showToast(endToast, "short");
                    informProgress(id, false, fileSize, step, dirName, fileName, callbackContext);
                    downloading_ids.del(id);
                }

                fos.flush();
                fos.close();
                is.close();
                ucon.disconnect();

                mNotifyManager.cancel(mNotificationId);

                if (!file.exists()) {
                    showToast("Download went wrong, please try again or contact the developer.", "long");
                    Log.e("PhoneGapLog", "Downloader Plugin: Error: Download went wrong.");
                }
                //callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
            } catch (FileNotFoundException e) {
                showToast(
                        "File does not exists or cannot connect to webserver, please try again or contact the developer.",
                        "long");
                Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.ERROR);
                e.printStackTrace();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
            } catch (IOException e) {
                showToast("Error downloading file, please try again or contact the developer.", "long");
                Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.ERROR);
                e.printStackTrace();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
            } catch (JSONException e) {
                e.printStackTrace();
                callbackContext
                        .sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()));
            } catch (InterruptedException e) {
                e.printStackTrace();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage()));
            }
        }
    });
    return true;
}

From source file:org.eclipse.emf.mwe.utils.StandaloneSetup.java

protected void registerBundle(File file) {
    JarFile jarFile = null;//from  w  ww . j  a  v  a 2 s  .  co m
    try {
        jarFile = new JarFile(file);
        log.debug("Trying to determine project name from Manifest for " + jarFile.getName());
        String name = getBundleNameFromManifest(jarFile);
        if (name == null) {
            log.debug("Trying to determine project name from file name for " + jarFile.getName());
            name = getBundleNameFromJarName(jarFile.getName());
        }
        if (name != null) {
            final int indexOf = name.indexOf(';');
            if (indexOf > 0)
                name = name.substring(0, indexOf);
            String path = "archive:" + file.getCanonicalFile().toURI() + "!/";
            URI uri = URI.createURI(path);
            registerMapping(name, uri);
        } else {
            log.debug("Could not determine project name for " + jarFile.getName()
                    + ". No project mapping will be added.");
        }
    } catch (ZipException e) {
        log.warn("Could not open Jar file " + file.getAbsolutePath() + ".");
    } catch (Exception e) {
        handleException(file, e);
    } finally {
        try {
            if (jarFile != null)
                jarFile.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:org.apereo.portal.io.xml.JaxbPortalDataHandlerService.java

/**
 * Determine directory to log import/export reports to
 *//*from w ww.j a  v a 2 s  .  c om*/
private File determineLogDirectory(final BatchOptions options, String operation) {
    File logDirectoryParent = options != null ? options.getLogDirectoryParent() : null;
    if (logDirectoryParent == null) {
        logDirectoryParent = Files.createTempDir();
    }
    File logDirectory = new File(logDirectoryParent, "data-" + operation + "-reports");
    try {
        logDirectory = logDirectory.getCanonicalFile();
        FileUtils.deleteDirectory(logDirectory);
    } catch (IOException e) {
        throw new RuntimeException("Failed to clean data-" + operation + " log directory: " + logDirectory, e);
    }
    logDirectory.mkdirs();
    return logDirectory;
}

From source file:org.apache.jasper.JspC.java

private void initClassLoader(JspCompilationContext clctxt) throws IOException {

    classPath = getClassPath();//from  ww w  .  j  a v  a 2 s .co m

    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);
    loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
    Thread.currentThread().setContextClassLoader(loader);
}

From source file:org.apache.catalina.startup.HostConfig.java

/**
 * Return a File object representing the "configuration root" directory
 * for our associated Host./*from w ww .  j a va 2s  .  c  om*/
 */
protected File configBase() {

    if (configBase != null) {
        return configBase;
    }

    File file = new File(System.getProperty("catalina.base"), "conf");
    Container parent = host.getParent();
    if ((parent != null) && (parent instanceof Engine)) {
        file = new File(file, parent.getName());
    }
    file = new File(file, host.getName());
    try {
        configBase = file.getCanonicalFile();
    } catch (IOException e) {
        configBase = file;
    }
    return (configBase);

}