Example usage for java.io File getAbsoluteFile

List of usage examples for java.io File getAbsoluteFile

Introduction

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

Prototype

public File getAbsoluteFile() 

Source Link

Document

Returns the absolute form of this abstract pathname.

Usage

From source file:abfab3d.shapejs.ShapeJSGlobal.java

/**
 * js function to load image/*w  w  w.  ja  v  a 2s  . c  o m*/
 * returns BufferedImage
 */
public static Object loadImage(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    long t0 = time();
    if (args.length < 1) {
        throw Context.reportRuntimeError("No file provided for loadImage() command");
    }
    String filename = Context.toString(args[0]);

    if (filename == null || filename.length() == 0) {
        throw Context.reportRuntimeError("No file provided for load() command");
    }

    double psize = 0.1 * MM;

    if (args.length > 1) {
        psize = getDouble(args[1]);
    }

    HashMap<String, Object> cparams = new HashMap<String, Object>(2);
    cparams.put("filename", filename);
    cparams.put("psize", psize);
    String vhash = BaseParameterizable.getParamObjString("loadImage", cparams);
    Object co = ParamCache.getInstance().get(vhash);
    if (co != null) {
        Scriptable ret_val = (Scriptable) cx.javaToJS(co, thisObj);
        return ret_val;
    }

    BufferedImage image = null;
    String reason = null;

    // TODO: add caching for local downloads?

    String orig_filename = filename;
    // Download
    if (filename.startsWith("http") || filename.startsWith("https")) {
        try {
            printf("Downloading url: %s\n", filename);
            filename = URIUtils.downloadURI("loadImage", filename);
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
    }

    File f = new File(filename);
    if (!f.exists()) {
        throw Context.reportRuntimeError(fmt("Cannot find image file: %s\n", f.getAbsoluteFile()));
    }

    try {
        image = ImageIO.read(new File(filename));

    } catch (Exception e) {
        reason = e.getMessage();
        e.printStackTrace();
    }
    if (image == null) {
        throw Context.reportRuntimeError(fmt("failed to load image file: %s.  Reason: %s\n", filename, reason));
    }
    int w = image.getWidth();
    int h = image.getHeight();
    if (w * h > MAX_IMAGE_PIXEL_COUNT) {
        throw new IllegalArgumentException(
                fmt("image dimensions [%d x %d] exceed max allowed: %d", w, h, MAX_IMAGE_PIXEL_COUNT));
    }

    printf("Loading image file: %s  vs: %f  time: %d ms\n", filename, psize, time() - t0);
    ImageWrapper wrapper = new ImageWrapper(image, filename, psize);
    ParamCache.getInstance().put(vhash, wrapper);
    Scriptable ret_val = (Scriptable) cx.javaToJS(wrapper, thisObj);
    return ret_val;
}

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

/** Create a new XMLSettingsHandler object.
 *
 * @param orderFile where the order file is located.
 * @throws InvalidAttributeValueException
 *///from  w ww  . j ava 2  s  .  c  om
public XMLSettingsHandler(File orderFile) throws InvalidAttributeValueException {
    super();
    this.orderFile = orderFile.getAbsoluteFile();
}

From source file:edu.scripps.fl.pubchem.xmltool.gui.GUIComponent.java

public void openPDF(boolean isInternalR, File pdf, Component comp) throws FileNotFoundException {
    if (isInternalR) {
        try {//from   www  . j a  v a2s  .  c  o  m
            Desktop.getDesktop().open(pdf);
        } catch (Exception ex) {
            log.info(ex.getMessage());
            String msg = "Unable to open PDF format through java. Would you like to save "
                    + pdf.getAbsoluteFile() + " in a new location?";
            JOptionPane pane = new JOptionPane(msg, JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.YES_NO_CANCEL_OPTION, null, null, JOptionPane.YES_OPTION);
            JDialog dialog = pane.createDialog(comp, "Report PDF");
            dialog.setVisible(true);
            Object choice = pane.getValue();
            if (choice.equals(JOptionPane.YES_OPTION)) {
                jfcFiles = new JFileChooser();
                jfcFiles.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                int state = jfcFiles.showSaveDialog(comp);

                if (state == JFileChooser.APPROVE_OPTION) {
                    File file = checkFileExtension(".pdf");
                    log.info("Opening: " + file.getName() + ".");
                    if (file != null)
                        pdf.renameTo(file);
                } else {
                    log.info("Open command cancelled by user.");
                }
            }
        }
    }
}

From source file:org.openscore.lang.tools.verifier.SlangContentVerifier.java

private Map<String, Executable> transformSlangFilesInDirToModels(String directoryPath) {
    Validate.notEmpty(directoryPath, "You must specify a path");
    Validate.isTrue(new File(directoryPath).isDirectory(),
            "Directory path argument \'" + directoryPath + "\' does not lead to a directory");
    Map<String, Executable> slangModels = new HashMap<>();
    Collection<File> slangFiles = FileUtils.listFiles(new File(directoryPath), SLANG_FILE_EXTENSIONS, true);
    log.info("Start compiling all slang files under: " + directoryPath);
    log.info(slangFiles.size() + " .sl files were found");
    for (File slangFile : slangFiles) {
        Validate.isTrue(slangFile.isFile(),
                "file path \'" + slangFile.getAbsolutePath() + "\' must lead to a file");
        Executable sourceModel;//ww  w  .  j  a va2  s .c  o  m
        try {
            sourceModel = slangCompiler.preCompile(fromFile(slangFile));
        } catch (Exception e) {
            String errorMessage = "Failed creating Slang models for file: \'" + slangFile.getAbsoluteFile()
                    + "\'.\n" + e.getMessage();
            log.error(errorMessage);
            throw new RuntimeException(errorMessage, e);
        }
        if (sourceModel != null) {
            staticSlangFileValidation(slangFile, sourceModel);
            slangModels.put(getUniqueName(sourceModel), sourceModel);
        }
    }
    if (slangFiles.size() != slangModels.size()) {
        throw new RuntimeException("Some Slang files were not pre-compiled.\nFound: " + slangFiles.size()
                + " slang files in path: \'" + directoryPath
                + "\' But managed to create slang models for only: " + slangModels.size());
    }
    return slangModels;
}

From source file:com.abiquo.am.services.filesystem.TemplateFileSystem.java

/**
 * synch to avoid multiple changes on the package folder (before 'clearOVFStatusMarks').
 * /*from w ww . j ava2 s . c  o m*/
 * @throws RepositoryException
 */
public static synchronized void createTemplateStatusMarks(final String enterpriseRepositoryPath,
        final String ovfId, final TemplateStatusEnumType status, final String errorMsg) {
    final String packagePath = getTemplatePath(enterpriseRepositoryPath, ovfId);

    clearTemplateStatusMarks(packagePath);

    File mark = null;
    boolean errorCreate = false;
    try {
        switch (status) {
        case DOWNLOAD:
            // after clean the prev. marks, nothing to do.
            break;

        case NOT_DOWNLOAD: // once the OVF envelope (.ovf) is deleted its NOT_FOUND
            break;

        case DOWNLOADING:
            mark = new File(packagePath + '/' + TEMPLATE_STATUS_DOWNLOADING_MARK);
            errorCreate = !mark.createNewFile();
            break;

        case ERROR:
            mark = new File(packagePath + '/' + TEMPLATE_STATUS_ERROR_MARK);
            errorCreate = !mark.createNewFile();

            if (!errorCreate) {
                FileWriter fileWriter = new FileWriter(mark);
                fileWriter.append(errorMsg);
                fileWriter.close();
            }
            break;

        default:
            throw new AMException(AMError.TEMPLATE_UNKNOW_STATUS, status.name());

        }// switch

    } catch (IOException ioe) {
        throw new AMException(AMError.TEMPLATE_CHANGE_STATUS, mark.getAbsoluteFile().getAbsolutePath());
    }

    if (errorCreate) {
        throw new AMException(AMError.TEMPLATE_CHANGE_STATUS, mark.getAbsoluteFile().getAbsolutePath());
    }
}

From source file:com.galenframework.api.Galen.java

public static void dumpPage(Browser browser, String pageName, PageSpec pageSpec, File reportFolder,
        Integer maxWidth, Integer maxHeight, boolean onlyImages) throws IOException {
    if (!reportFolder.exists()) {
        if (!reportFolder.mkdirs()) {
            throw new RuntimeException("Cannot create dir: " + reportFolder.getAbsolutePath());
        }//from  w  w  w.j av  a  2s . c om
    }

    Set<String> objectNames = pageSpec.getObjects().keySet();
    PageValidation pageValidation = new PageValidation(browser, browser.getPage(), pageSpec, null, null);

    PageDump pageDump = new PageDump();
    pageDump.setTitle(browser.getPage().getTitle());
    for (String objectName : objectNames) {
        PageElement pageElement = pageValidation.findPageElement(objectName);

        if (pageElement.isVisible() && pageElement.getArea() != null) {
            PageDump.Element element = new PageDump.Element(objectName, pageElement.getArea().toIntArray(),
                    pageElement.getText());

            if (pageElement.isPresent() && pageElement.isVisible()
                    && isWithinArea(pageElement, maxWidth, maxHeight)) {
                element.setHasImage(true);
            }
            pageDump.addElement(element);
        }
    }

    if (!onlyImages) {
        pageDump.setPageName(pageName);
        pageDump.exportAsJson(new File(reportFolder.getAbsoluteFile() + File.separator + "page.json"));
        pageDump.exportAsHtml(pageName,
                new File(reportFolder.getAbsoluteFile() + File.separator + "page.html"));
        copyResource("/html-report/jquery-1.11.2.min.js",
                new File(reportFolder.getAbsolutePath() + File.separator + "jquery-1.11.2.min.js"));
        copyResource("/pagedump/galen-pagedump.js",
                new File(reportFolder.getAbsolutePath() + File.separator + "galen-pagedump.js"));
        copyResource("/pagedump/galen-pagedump.css",
                new File(reportFolder.getAbsolutePath() + File.separator + "galen-pagedump.css"));
    }

    pageDump.exportAllScreenshots(browser, reportFolder);
}

From source file:udpserver.UDPui.java

private void receiveUDP() {
    countSeparate = new ArrayList<>();
    background = new Runnable() {
        public void run() {
            try {
                serverSocket = new DatagramSocket(9876);
            } catch (SocketException ex) {
                Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
            }/*from   w  w w.ja v a  2 s.  com*/
            //                while (true) {
            //                    byte[] receiveData = new byte[1024];
            //                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            //<editor-fold defaultstate="collapsed" desc="Start timer after receive a packet">
            //                    try {
            //                        serverSocket.receive(receivePacket);
            //                        series.clear();
            //                        valuePane.setText("");
            available = true;
            //                        System.out.println(available);
            //                    } catch (IOException ex) {
            //                        Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
            //                    }

            //                    Timer timer = new Timer();
            //                    timer.schedule(new TimerTask() {
            //                        @Override
            //                        public void run() {
            //                            available = false;
            //                            System.out.println("Finish Timer");
            //                        }
            //                    }, 1 * 1000);
            //</editor-fold>
            //                    if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) {
            //                        int count = 1;
            //                        while (available) {
            while (true) {
                try {
                    byte[] receiveData = new byte[total_byte];
                    byte[] sendData = new byte[32];
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                    serverSocket.receive(receivePacket);

                    String word = receivePacket.getAddress().getHostAddress();
                    System.out.println(word);

                    String message = new String(receivePacket.getData(), receivePacket.getOffset(),
                            receivePacket.getLength());
                    boolean looprun = true;

                    //                                System.out.println(message);
                    while (looprun) {
                        Integer countt = counting.get(word);
                        if (message.contains("&")) {
                            message = message.substring(message.indexOf("&") + 1);
                            //                                        count++;
                            //                                        Integer countt = counting.get(word);
                            if (countt == null) {
                                counting.put(word, 1);
                            } else {
                                counting.put(word, countt + 1);
                            }
                            //                                        System.out.println(count + ":" + message);
                        } else {
                            if (countt == null) {
                                counting.put(word, 1);
                            } else {
                                counting.put(word, countt + 1);
                            }
                            System.out.println(counting.get(word));
                            looprun = false;
                        }
                    }

                    if (message.contains("start")) {
                        if (counting.get(word) != null) {
                            counting.remove(word);
                        }
                    } else if (message.contains("end")) {
                        message = message.substring(message.indexOf("end") + 3);
                        //                                    valuePane.setCaretPosition(valuePane.getDocument().getLength());
                        //send back to mobile
                        InetAddress IPAddress = receivePacket.getAddress();
                        int port = receivePacket.getPort();
                        //                                    String capitalizedSentence = count + "";

                        String capitalizedSentence = counting.get(word) + "";
                        sendData = capitalizedSentence.getBytes();
                        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
                                port);
                        serverSocket.send(sendPacket);

                        String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss")
                                .format(Calendar.getInstance().getTime());
                        String content = IPAddress.getCanonicalHostName() + "," + timeStamp + ","
                                + (counting.get(word) - 1) + "," + message;
                        saveFile(content);
                        //end send back to mobile
                        //                                    System.out.println(counting.get(word));
                        //                                    count = 1;
                        counting.remove(word);
                        //                                    break;
                    } else if (available) {

                        //<editor-fold defaultstate="collapsed" desc="check hasmap key">
                        //                                    if (hm.size() > 0 && hm.containsKey(serverSocket.getInetAddress().getHostAddress())) {
                        //                                        hm.put(foundKey, new Integer(((int) hm.get(foundKey)) + 1));
                        //                                        hm.put(serverSocket.getInetAddress().getHostAddress(), new Integer(((int) hm.get(serverSocket.getInetAddress().getHostAddress())) + 1));
                        //                                    } else {
                        //                                        hm.put(serverSocket.getInetAddress().getHostAddress(), 1);
                        //                                        hm.entrySet().add(new Map<String, Integer>.Entry<String, Integer>());
                        //                                    }
                        //</editor-fold>
                        //                                    series.add(count, Double.parseDouble(message));
                        //                                    valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n");
                        //                                    valuePane.setCaretPosition(valuePane.getDocument().getLength());
                        //                                    count++;
                    }
                } catch (IOException ex) {
                    Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
                    valuePane.setText(valuePane.getText().toString() + "IOException" + "\n");
                }
            }
            //                        valuePane.setText(valuePane.getText().toString() + "Out of while loop" + "\n");
            //                    }
            //                }
        }

        private void saveFile(String content) {
            try {
                File desktop = new File(System.getProperty("user.home"), "Desktop");
                File file = new File(desktop.getAbsoluteFile() + "/udp.csv");
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fop = new FileOutputStream(file, true);
                fop.write((content + "\n").getBytes());
                fop.flush();
                fop.close();
                //                    String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(Calendar.getInstance().getTime());
                //                    valuePane.setText(valuePane.getText().toString() + timeStamp + "\n");
            } catch (IOException ex) {
                Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
                String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss")
                        .format(Calendar.getInstance().getTime());
                valuePane.setText(valuePane.getText().toString() + timeStamp + "\n");
            }
        }
    };
    backgroundProcess = new Thread(background);
}

From source file:com._17od.upm.gui.OptionsDialog.java

private void getDBToLoadOnStartup() {
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle(Translator.translate("dbToOpenOnStartup"));
    int returnVal = fc.showOpenDialog(parentFrame);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File databaseFile = fc.getSelectedFile();
        dbToLoadOnStartup.setText(databaseFile.getAbsoluteFile().toString());
    }/*from www.  j a  v  a  2 s .  c o  m*/
}

From source file:com.digitalgeneralists.assurance.UnitTestUtils.java

public File createTestFile(String path, String content) throws IOException {
    path = this.testArtifactLocation + File.separator + path;
    File testFile = new File(path);
    File parentDir = new File(testFile.getParent());
    parentDir.mkdirs();/* w w  w . ja  v a  2 s .co m*/
    testFile.createNewFile();

    FileWriter fw = new FileWriter(testFile.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
    bw.close();
    fw.close();

    return testFile;
}

From source file:io.treefarm.plugins.haxe.TestCompileMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    super.execute();

    if (munitCompiler.getHasRequirements()) {

        if (openflIsActive() && testTargets != null && testClasspath != null) {
            String logInfo = "Compiling tests for MassiveUnit using OpenFL ";
            logInfo += (testCoverage ? "WITH code coverage" : "WITHOUT code coverage") + ".";
            if (testDebug) {
                logInfo += "\n *** with debug, so only tests with @TestDebug will be built ***";
            }/*from   w ww.j a  v a 2  s.c  o  m*/
            getLog().info(logInfo);

            Set<String> classPaths = new HashSet<String>();
            String cleanClassPathList = "";
            try {
                List<String> displayHxml = openflCompiler.displayHxml(project, testTargets.iterator().next(),
                        nmml, null, null, null);
                for (String line : displayHxml) {
                    String classPath = StringUtils.substringAfter(line, "-cp ");
                    if (classPath.length() > 0) {
                        classPaths.add(classPath);
                    }
                }
            } catch (Exception e) {
                throw new MojoFailureException("Tests compilation failed", e);
            }

            compilerFlags = new ArrayList<String>();
            compilerFlags.add("-lib munit");
            compilerFlags.add("-lib hamcrest");
            if (testCoverage && classPaths.size() > 0) {
                compilerFlags.add("-lib mcover");
                compilerFlags.add("-D MCOVER");

                /*String mCoverDirective = "--macro mcover.MCover.coverage\\([\\'\\'],[\\'";
                //String mCoverDirective = "--macro mcover.MCover.coverage([''],['";
                Iterator<String> it = classPaths.iterator();
                String classPath;
                while(it.hasNext()) {
                classPath = it.next();
                if (!StringUtils.contains(classPath, ",")
                        && StringUtils.indexOf(classPath, "/") != 0) {
                    if (cleanClassPathList.length() > 0) {
                        cleanClassPathList += ",";
                    }
                    cleanClassPathList += classPath;
                }
                }
                        
                mCoverDirective += cleanClassPathList + "\\']\\)";
                //mCoverDirective += cleanClassPathList + "'],[''])";
                compilerFlags.add(mCoverDirective);
                getLog().info("mcover call: " + mCoverDirective);*/
            }
            compilerFlags.add("-cp " + testClasspath);

            try {
                if (testRunner == null) {
                    testRunner = TEST_RUNNER;
                }
                if (testHxml == null) {
                    testHxml = TEST_HXML;
                }

                List<String> displayHxml = openflCompiler.displayHxml(project, testTargets, nmml, compilerFlags,
                        testMain, testRunner);

                String hxmlDump = "";
                for (String hxmlLine : displayHxml) {
                    hxmlDump += hxmlLine + "\n";
                }

                File hxmlFile = new File(outputDirectory, testHxml);
                if (hxmlFile.exists()) {
                    FileUtils.deleteQuietly(hxmlFile);
                }
                hxmlFile.createNewFile();
                FileWriter fw = new FileWriter(hxmlFile.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(hxmlDump);
                bw.close();

                if (testResources != null) {
                    File resourcesFile = new File(outputDirectory.getParentFile(), testResources);
                    File tmpResourcesFile = new File(outputDirectory, "tmp_resources");
                    tmpResourcesFile.mkdirs();
                    FileUtils.copyDirectory(resourcesFile, new File(tmpResourcesFile, resourcesFile.getName()));
                    testResources = tmpResourcesFile.getAbsolutePath();
                }

                if (testBinPath == null) {
                    testBinPath = TEST_BIN_PATH;
                }
                File testBinFile = new File(outputDirectory, testBinPath);
                testBinPath = testBinFile.getAbsolutePath();

                munitCompiler.config(testClasspath, testBinPath, testBinPath, cleanClassPathList,
                        hxmlFile.getAbsolutePath(), testResources, testTemplates);
                openflCompiler.initialize(debug, verbose, false, false, true, testDebug);
                openflCompiler.compile(project, testTargets, nmml, compilerFlags, testMain, testRunner, true,
                        false, false);
            } catch (Exception e) {
                throw new MojoFailureException("Tests compilation failed", e);
            }
        } else {
            getLog().info("Compiling tests using MassiveUnit.");

            try {
                munitCompiler.initialize(testDebug, false);
                munitCompiler.setOutputDirectory(outputDirectory);
                munitCompiler.compile(project, null);
            } catch (Exception e) {
                throw new MojoFailureException("Tests compilation failed", e);
            }
        }
    } else {
        getLog().info("Compiling tests using standard Haxe unit testing.");

        if (testRunner == null || project.getTestCompileSourceRoots().size() == 0) {
            getLog().info("No test sources to compile");
            return;
        }

        String output = OutputNamesHelper.getTestOutput(project);
        EnumMap<CompileTarget, String> targets = new EnumMap<CompileTarget, String>(CompileTarget.class);
        targets.put(CompileTarget.neko, output);

        try {
            haxeCompiler.compile(project, targets, testRunner, true, true, verbose);
        } catch (Exception e) {
            throw new MojoFailureException("Tests compilation failed", e);
        }
    }
}