Example usage for java.io File getParent

List of usage examples for java.io File getParent

Introduction

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

Prototype

public String getParent() 

Source Link

Document

Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

Usage

From source file:net.sf.webphotos.tools.Thumbnail.java

/**
 * Cria thumbs para as imagens. Testa se j existem valores setados para o
 * thumb, se no existir chama o mtodo/*from w w w. j  a  v a2s .  c o  m*/
 * {@link net.sf.webphotos.Thumbnail#inicializar() inicializar} para setar
 * seus valores. Abre o arquivo de imagem passado como parmetro e checa se
 *  uma foto vlida. Obtm o tamanho original da imagem, checa se est no
 * formato paisagem ou retrato e utiliza o mtodo
 * {@link java.awt.Image#getScaledInstance(int,int,int) getScaledInstance}
 * para calcular os thumbs. Ao final, salva as imagens.
 *
 * @param caminhoCompletoImagem Caminho da imagem.
 */
public static void makeThumbs(String caminhoCompletoImagem) {

    String diretorio, arquivo;
    if (t1 == 0) {
        inicializar();
    }

    try {
        File f = new File(caminhoCompletoImagem);
        if (!f.isFile() || !f.canRead()) {
            Util.err.println("[Thumbnail.makeThumbs]/ERRO: Erro no caminho do arquivo " + caminhoCompletoImagem
                    + " incorreto");
            return;
        }

        // Foto em alta corrompida 
        if (getFormatName(f) == null) {
            Util.err.println("[Thumbnail.makeThumbs]/ERRO: Foto Corrompida");
            return;
        } else {
            Util.out.println("[Thumbnail.makeThumbs]/INFO: Foto Ok!");
        }

        diretorio = f.getParent();
        arquivo = f.getName();

        ImageIcon ii = new ImageIcon(f.getCanonicalPath());
        Image i = ii.getImage();

        Image tumb1, tumb2, tumb3, tumb4;

        // obtm o tamanho da imagem original
        int iWidth = i.getWidth(null);
        int iHeight = i.getHeight(null);
        //int w, h;

        if (iWidth > iHeight) {
            tumb1 = i.getScaledInstance(t1, (t1 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            tumb2 = i.getScaledInstance(t2, (t2 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            tumb3 = i.getScaledInstance(t3, (t3 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            tumb4 = i.getScaledInstance(t4, (t4 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            //w = t4;
            //h = (t4 * iHeight) / iWidth;
        } else {
            tumb1 = i.getScaledInstance((t1 * iWidth) / iHeight, t1, Image.SCALE_SMOOTH);
            tumb2 = i.getScaledInstance((t2 * iWidth) / iHeight, t2, Image.SCALE_SMOOTH);
            tumb3 = i.getScaledInstance((t3 * iWidth) / iHeight, t3, Image.SCALE_SMOOTH);
            tumb4 = i.getScaledInstance((t4 * iWidth) / iHeight, t4, Image.SCALE_SMOOTH);
            //w = (t4 * iWidth) / iHeight;
            //h = t4;
        }

        tumb4 = estampar(tumb4);

        Util.log("Salvando Imagens");

        save(tumb1, diretorio + File.separator + "_a" + arquivo);
        save(tumb2, diretorio + File.separator + "_b" + arquivo);
        save(tumb3, diretorio + File.separator + "_c" + arquivo);
        save(tumb4, diretorio + File.separator + "_d" + arquivo);

    } catch (Exception e) {
        Util.err.println("[Thumbnail.makeThumbs]/ERRO: Inesperado - " + e.getMessage());
        e.printStackTrace(Util.err);
    }
}

From source file:org.apache.hadoop.gateway.AmbariServiceDefinitionTest.java

public static void setupGateway() throws Exception {
    File targetDir = new File(System.getProperty("user.dir"), "target");
    File gatewayDir = new File(targetDir, "gateway-home-" + UUID.randomUUID());
    gatewayDir.mkdirs();//from w ww  .j a v a2  s.  c  om

    config = new GatewayTestConfig();
    config.setGatewayHomeDir(gatewayDir.getAbsolutePath());

    URL svcsFileUrl = TestUtils.getResourceUrl(DAT, "test-svcs/readme.txt");
    File svcsFile = new File(svcsFileUrl.getFile());
    File svcsDir = svcsFile.getParentFile();
    config.setGatewayServicesDir(svcsDir.getAbsolutePath());

    String pathToStacksSource = "gateway-service-definitions/src/main/resources/services";
    File stacksSourceDir = new File(targetDir.getParent(), pathToStacksSource);
    if (!stacksSourceDir.exists()) {
        stacksSourceDir = new File(targetDir.getParentFile().getParent(), pathToStacksSource);
    }
    if (stacksSourceDir.exists()) {
        FileUtils.copyDirectoryToDirectory(stacksSourceDir, svcsDir);
    }

    File topoDir = new File(config.getGatewayTopologyDir());
    topoDir.mkdirs();

    File deployDir = new File(config.getGatewayDeploymentDir());
    deployDir.mkdirs();

    setupMockServers();
    startGatewayServer();
}

From source file:elh.eus.absa.NLPpipelineWrapper.java

public static int eustaggerCall(String taggerCommand, String string, String fname) {

    try {// ww w .  j a  v  a  2s  . c om
        File temp = new File(fname);
        //System.err.println("eustaggerCall: created temp file: "+temp.getAbsolutePath());
        BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
        bw.write(string + "\n");
        bw.close();

        String[] command = { taggerCommand, temp.getName() };
        System.err.println("Eustagger agindua: " + Arrays.toString(command));

        ProcessBuilder eustBuilder = new ProcessBuilder().command(command);
        eustBuilder.directory(new File(temp.getParent()));
        //.redirectErrorStream(true);
        Process eustagger = eustBuilder.start();
        int success = eustagger.waitFor();
        //System.err.println("eustagger succesful? "+success);
        if (success != 0) {
            System.err.println("eustaggerCall: eustagger error");
        } else {
            String tagged = fname + ".kaf";
            BufferedReader reader = new BufferedReader(new InputStreamReader(eustagger.getInputStream()));
            //new Eustagger_lite outputs to stdout. Also called ixa-pipe-pos-eu
            if (taggerCommand.contains("eustagger") || taggerCommand.contains("ixa-pipe")) {
                Files.copy(eustagger.getInputStream(), Paths.get(tagged));
            }
            // old eustagger (euslem)
            else {
                FileUtilsElh.renameFile(temp.getAbsolutePath() + ".etiketatua3", tagged);
            }
        }
        //
        // delete all temporal files used in the process.
        temp.delete();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return -1;
    }

    return 0;
}

From source file:ddf.catalog.source.solr.SolrServerFactory.java

/**
 * Provides an already instantiated {@link SolrServer} object. If an instance has not already
 * been instantiated, then the single instance will be instantiated with the provided
 * configuration file. If an instance already exists, it cannot be overwritten with a new
 * configuration.//from   www . j a  va2s  .c o m
 * 
 * @param solrConfigXml
 *            the name of the solr configuration filename such as solrconfig.xml
 * @param schemaXml
 *            filename of the schema such as schema.xml
 * @param givenConfigFileProxy
 *            a ConfigurationFileProxy instance. If instance is <code>null</code>, a new
 *            {@link ConfigurationFileProxy} is used instead.
 * @return {@link SolrServer} instance
 */
public static EmbeddedSolrServer getEmbeddedSolrServer(String solrConfigXml, String schemaXml,
        ConfigurationFileProxy givenConfigFileProxy) {

    LOGGER.info("Retrieving embedded solr with the following properties: [" + solrConfigXml + "," + schemaXml
            + "," + givenConfigFileProxy + "]");

    String solrConfigFileName = DEFAULT_SOLRCONFIG_XML;

    String schemaFileName = DEFAULT_SCHEMA_XML;

    if (isNotBlank(solrConfigXml)) {
        solrConfigFileName = solrConfigXml;
    }

    if (isNotBlank(schemaXml)) {
        schemaFileName = schemaXml;
    }

    File solrConfigFile = null;
    File solrConfigHome = null;
    File solrSchemaFile = null;

    ConfigurationFileProxy configProxy = givenConfigFileProxy;

    if (givenConfigFileProxy == null) {
        configProxy = new ConfigurationFileProxy(null, ConfigurationStore.getInstance());
    }

    File configurationDir = new File(ConfigurationFileProxy.DEFAULT_SOLR_CONFIG_PARENT_DIR,
            ConfigurationFileProxy.SOLR_CONFIG_LOCATION_IN_BUNDLE);
    configProxy.writeBundleFilesTo(configurationDir);

    try {
        URL url = configProxy.getResource(solrConfigFileName);

        LOGGER.info("Solr config url: " + url);

        solrConfigFile = new File(new URI(url.toString()).getPath());

        solrConfigHome = new File(solrConfigFile.getParent());
    } catch (URISyntaxException e) {
        LOGGER.warn(e);
    }

    try {
        URL url = configProxy.getResource(schemaFileName);

        LOGGER.info("Solr schema url: " + url);

        solrSchemaFile = new File(new URI(url.toString()).getPath());

    } catch (URISyntaxException e) {
        LOGGER.warn(e);
    }

    SolrConfig solrConfig = null;
    IndexSchema indexSchema = null;
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(SolrServerFactory.class.getClassLoader());

        // NamedSPILoader uses the thread context classloader to lookup
        // codecs, posting formats, and analyzers
        solrConfig = new SolrConfig(solrConfigHome.getParent(), solrConfigFileName,
                new InputSource(FileUtils.openInputStream(solrConfigFile)));
        indexSchema = new IndexSchema(solrConfig, schemaFileName,
                new InputSource(FileUtils.openInputStream(solrSchemaFile)));
    } catch (ParserConfigurationException e) {
        LOGGER.warn(e);
    } catch (IOException e) {
        LOGGER.warn(e);
    } catch (SAXException e) {
        LOGGER.warn(e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }

    CoreContainer container = new CoreContainer(solrConfigHome.getAbsolutePath());
    container.load();
    CoreDescriptor dcore = new CoreDescriptor(container, "core1",
            solrConfig.getResourceLoader().getInstanceDir());

    File dataDir = configProxy.getDataDirectory();
    LOGGER.info("Using data directory [" + dataDir + "]");
    SolrCore core = new SolrCore("core1", dataDir.getAbsolutePath(), solrConfig, indexSchema, dcore);
    container.register("core1", core, false);

    return new EmbeddedSolrServer(container, "core1");
}

From source file:com.microsoft.tfs.util.FileHelpers.java

/**
 * Like {@link File#renameTo(File)}, but on Windows it can overwrite
 * existing files. The algorithm doesn't provide atomicity, it fails fast,
 * and it tries to leave the files in their original states in the case of a
 * failure.//from ww  w .j a v  a 2  s.  c o  m
 * <p>
 * This method exists mainly because {@link File#renameTo(File)} behaves
 * very differently depending on platform. On Unix, it's mostly like
 * rename(2) (atomic transaction, obeys only directory permissions during
 * the operation, clobbers existing files). On Windows it won't overwrite
 * existing files no-matter the permissions involved. Deleting the
 * destination file first opens up a short race that complicates the
 * algorithm.
 * <p>
 * This method is <b>not</b> guaranteed to work across filesystems.
 *
 * @param source
 *        the existing file that will be renamed to the given target file.
 *        Not null.
 * @param target
 *        the file that the existing file will be renamed to. If this file
 *        exists it will be overwritten. Not null.
 */
public static void rename(final File source, final File target) throws IOException {
    Check.notNull(source, "source"); //$NON-NLS-1$
    Check.notNull(target, "target"); //$NON-NLS-1$

    if (source.exists() == false) {
        throw new FileNotFoundException(MessageFormat.format("Source file {0} does not exist", source)); //$NON-NLS-1$
    }

    File tempFile = null;

    if (target.getParent() != null) {
        createDirectoryIfNecessary(target.getParent());
    }

    if (target.exists()) {
        /*
         * The target exists, so we'll need to move it to a temp name.
         */
        tempFile = new File(target.getAbsolutePath() + "-" + System.currentTimeMillis() + ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$

        if (tempFile.exists()) {
            /*
             * This is highly improbable.
             */
            final String messageFormat = "Temp file {0} already exists before rename"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, tempFile);
            log.warn(message);
            throw new IOException(message);
        }

        if (target.renameTo(tempFile) == false) {
            final String messageFormat = "Could not rename target {0} to temp file for rename"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, target);
            log.warn(message);
            throw new IOException(message);
        }
    }

    /*
     * Do the main rename.
     */
    if (source.renameTo(target)) {
        /*
         * The main rename succeeded, so failing to delete the temp file is
         * not a fatal error (but annoying).
         */
        if (tempFile != null && tempFile.delete() == false) {
            final String messageFormat = "Error deleting temp file {0} after successful rename, leaving"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, tempFile);
            log.warn(message);
        }
    } else {
        log.warn("Main rename failed (source permissions problem?), trying to rename temp file back"); //$NON-NLS-1$

        /*
         * Target shouldn't exist (we renamed it to a temp file) unless some
         * other process put it there.
         */
        if (target.exists()) {
            final String messageFormat = "Target {0} exists when it should not, lost race to some other process?"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, target);
            log.warn(message);
            throw new IOException(message);
        }

        if (tempFile != null && tempFile.renameTo(target) == false) {
            final String messageFormat = "Error renaming temp file {0} back to target {1} after failed main rename"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, tempFile, target);
            log.warn(message);
            throw new IOException(message);
        }

        final String messageFormat = Messages.getString("FileHelpers.FailedToRenameFormat"); //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, source, target);
        log.warn(message);
        throw new IOException(message);
    }
}

From source file:com.facebook.config.ExpandedConfFileJSONProvider.java

@Override
protected String resolve(String parent, String config) {
    File file = new File(config);
    if (file.isAbsolute() || parent == null) {
        return file.getAbsolutePath();
    }//from  w  ww .jav a2 s .  c  o m

    // relative path
    File parentFile = new File(parent);
    file = new File(parentFile.getParent(), config);

    return file.getAbsolutePath();
}

From source file:myLexTo.ReadConfig.java

public Hashtable read() {
    Hashtable config = new Hashtable();

    try {/*from w  w  w  . ja  v a  2 s . co  m*/
        File f = new File(System.getProperty("java.class.path"));
        File dir = f.getAbsoluteFile().getParentFile();

        String path = dir.getParent().toString();
        String configFile = path + "/config.json";

        JSONTokener jsonTokener = new JSONTokener(new FileReader(path + "/config.json"));
        JSONArray arrobj = new JSONArray(jsonTokener);

        for (int i = 0; i < arrobj.length(); i++) {
            JSONObject item = arrobj.getJSONObject(i);
            String lexitron = item.getString("lexitron");
            String herblist = item.getString("herblist");
            String properties = item.getString("properties");
            String stopwords = item.getString("stopwords");
            String symptoms = item.getString("symptoms");

            config.put("lexitron", lexitron);
            config.put("herblist", herblist);
            config.put("properties", properties);
            config.put("stopwords", stopwords);
            config.put("symptoms", symptoms);
        }
    } catch (FileNotFoundException | JSONException ex) {
        Logger.getLogger(ReadConfig.class.getName()).log(Level.SEVERE, null, ex);
    }

    return config;
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToLaTeXConverter.java

/**
 * Write the LateX generated PDF into the output stream. In case the file
 * could not be generated, write the debug info file.
 *
 * @param os/*  ww  w.j a  v  a2 s .  c  om*/
 *            the output stream to write the file to
 * @param pdfFile
 *            the PDF file to write to the output stream
 */
public static void streamPdf(OutputStream os, File pdfFile) {
    if (pdfFile.length() < 2) {
        pdfFile = new File(pdfFile.getParent() + "/errors.pdf");
    }
    try {
        InputStream is = new FileInputStream(pdfFile);
        IOUtils.copy(is, os);
        is.close();
    } catch (FileNotFoundException e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:CreatingTreeModel.java

public FileSystemModel() {

    root = System.getProperty("user.home");
    File tempFile = new File(root);
    root = tempFile.getParent();

    listeners = new Vector();
}

From source file:com.arcbees.gwtpolymer.fs.CopyPolymerFilter.java

private boolean isWebAnimationJsHtmlFile(File file) {
    return "web-animations.html".equals(file.getName()) && file.getParent().endsWith("web-animations-js");
}