Example usage for java.io File toURI

List of usage examples for java.io File toURI

Introduction

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

Prototype

public URI toURI() 

Source Link

Document

Constructs a file: URI that represents this abstract pathname.

Usage

From source file:it.geosolutions.geobatch.figis.intersection.Utilities.java

public static void writeOnShapeFile(File shapeFile, SimpleFeatureCollection collection) {
    if (shapeFile == null || collection == null || !shapeFile.canWrite()) {

        throw new IllegalArgumentException(
                "One or more input parameters are null or the file provided couldn't be read");
    }/*from   w  w w. j  a  v  a 2 s .  com*/

    ShapefileDataStore newDataStore = null;
    Transaction transaction = null;
    SimpleFeatureStore featureStore = null;
    try {
        newDataStore = new ShapefileDataStore(shapeFile.toURI().toURL());
        newDataStore.createSchema(collection.getSchema());
        transaction = new DefaultTransaction("create");
        String typeName = newDataStore.getTypeNames()[0];
        SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
        featureStore = (SimpleFeatureStore) featureSource;
        featureStore.setTransaction(transaction);
        featureStore.addFeatures(collection);
        transaction.commit();
    } catch (IOException e) {

        LOGGER.error(e.getMessage(), e);
    } finally {
        if (newDataStore != null) {

            newDataStore.dispose();
        }
        if (transaction != null) {

            try {

                transaction.close();
            } catch (IOException e) {

                LOGGER.error(e.getMessage(), e);
            }

        }
        if (featureStore != null) {

            newDataStore.dispose();
        }
    }
}

From source file:com.datatorrent.stram.client.StramClientUtils.java

public static URL getDTSiteXmlFile() {
    File cfgResource = new File(StramClientUtils.getConfigDir(), StramClientUtils.DT_SITE_XML_FILE);
    try {//from ww w. j  a v  a  2  s . c o m
        return cfgResource.toURI().toURL();
    } catch (MalformedURLException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:eu.sisob.uma.NPL.Researchers.GateDataExtractorSingle.java

/**
 *
 * @param reader// w  w  w .  j a  v  a  2s  . c o  m
 * @param separator
 * @param data_dir
 * @param verbose
 * @param verbose_dir
 * @param split_by_keyword
 * @param blocks_and_keywords
 * @return
 * @throws IOException
 */
public static RepositoryPreprocessDataMiddleData createPreprocessRepositoryFromCSV(CSVReader reader,
        char separator, File data_dir, boolean verbose, File verbose_dir, boolean split_by_keyword,
        HashMap<String, String[]> blocks_and_keywords, File dest_dir) throws IOException {
    RepositoryPreprocessDataMiddleData preprocessedRep = new RepositoryPreprocessDataMiddleData();

    String[] nextLine;

    int idStaffIdentifier = -1;
    int idName = -1;
    int idFirstName = -1;
    int idLastName = -1;
    int idInitials = -1;
    int idUnitOfAssessment_Description = -1;
    int idInstitutionName = -1;
    int idWebAddress = -1;
    int idResearchGroupDescription = -1;
    int idResearcherWebAddress = -1;
    int idResearcherWebAddressType = -1;
    int idResearcherWebAddressExt = -1;
    if ((nextLine = reader.readNext()) != null) {
        for (int i = 0; i < nextLine.length; i++) {
            String column_name = nextLine[i];
            if (column_name.equals(FileFormatConversor.CSV_COL_ID))
                idStaffIdentifier = i;
            else if (column_name.equals(FileFormatConversor.CSV_COL_NAME))
                idName = i;
            else if (column_name.equals(FileFormatConversor.CSV_COL_FIRSTNAME))
                idFirstName = i;
            else if (column_name.equals(FileFormatConversor.CSV_COL_LASTNAME))
                idLastName = i;
            else if (column_name.equals(FileFormatConversor.CSV_COL_INITIALS))
                idInitials = i;
            else if (column_name.equals(FileFormatConversor.CSV_COL_SUBJECT))
                idUnitOfAssessment_Description = i;
            else if (column_name.equals(FileFormatConversor.CSV_COL_INSTITUTION_NAME))
                idInstitutionName = i;
            else if (column_name.equals(FileFormatConversor.CSV_COL_INSTITUTION_URL))
                idWebAddress = i;
            else if (column_name.equals(FileFormatConversor.CSV_COL_RESEARCHER_PAGE_URL))
                idResearcherWebAddress = i;
            else if (column_name.equals(FileFormatConversor.CSV_COL_RESEARCHER_PAGE_TYPE))
                idResearcherWebAddressType = i;
            else if (column_name.equals(FileFormatConversor.CSV_COL_RESEARCHER_PAGE_EXT))
                idResearcherWebAddressExt = i;
        }
    }

    if (idResearcherWebAddress != -1 && idStaffIdentifier != -1 && idLastName != -1 && idInitials != -1) {
        Pattern p1 = Pattern.compile("([a-zA-Z0-9#._-]+)+");

        int count = 0;
        while ((nextLine = reader.readNext()) != null) {
            String file_reference = nextLine[idResearcherWebAddress];
            String researcher_page_url = nextLine[idResearcherWebAddress];

            if (p1.matcher(researcher_page_url).matches()) {
                File f = new File(data_dir, researcher_page_url);
                if (!f.exists()) {
                    throw new FileNotFoundException(researcher_page_url + " not found in the folder.");
                }
                researcher_page_url = f.toURI().toURL().toString();
            }

            String id = nextLine[idStaffIdentifier];
            String lastname = nextLine[idLastName];
            String initials = nextLine[idInitials];

            String name = idFirstName != -1 ? nextLine[idFirstName] : "";
            String firstname = idName != -1 ? nextLine[idName] : "";

            if (split_by_keyword && blocks_and_keywords != null && blocks_and_keywords != null) {
                DocumentSplitter spliter = new DocumentSplitter(blocks_and_keywords);
                Document doc = null;
                boolean document_loaded = false;
                try {
                    ProjectLogger.LOGGER.info("Opening " + researcher_page_url);
                    doc = gate.Factory.newDocument(new URL(researcher_page_url));
                    document_loaded = true;
                } catch (Exception ex) {
                    ProjectLogger.LOGGER.error("Document not loaded ", ex);
                }

                if (document_loaded) {
                    List<Entry<String, String>> blocks = spliter.SplitDocument(doc.getContent().toString());
                    for (Entry<String, String> block : blocks) {
                        //if(block.getKey().equals(CVBlocks.CVBLOCK_PROFESSIONAL_ACTIVITY.toString()) ||
                        //           block.getKey().equals(CVBlocks.CVBLOCK_UNIVERSITY_STUDIES.toString()) ||
                        //          block.getKey().equals(CVBlocks.CVBLOCK_PERSONAL.toString()) ||
                        //           block.getKey().equals(""))
                        {
                            String desc = "";
                            try {
                                desc = CVBlocks.CVBLOCK_DESCRIPTIONS[Integer.parseInt(block.getKey())];
                            } catch (Exception ex) {
                                desc = CVBlocks.CVBLOCK_DESCRIPTIONS[CVBlocks.CVBLOCK_REST];
                            }

                            String output_filename = file_reference;
                            int index_slash = file_reference.substring(0, file_reference.length() - 1)
                                    .lastIndexOf("/");
                            if (index_slash != -1) {
                                output_filename = file_reference.substring(index_slash);
                            }

                            output_filename = desc + "-" + id + "-"
                                    + output_filename.replaceAll("[^A-Za-z0-9]", "-");
                            File output_file = new File(dest_dir, output_filename);
                            FileUtils.write(output_file, block.getValue(), "UTF-8", false);
                            String output_fileurl = output_file.toURI().toURL().toString();
                            HashMap<String, String> extra_data = new HashMap<String, String>();
                            extra_data.put(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_LASTNAME,
                                    lastname);
                            extra_data.put(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_INITIALS,
                                    initials);
                            extra_data.put(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_NAME, name);
                            extra_data.put(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_FIRSTNAME,
                                    firstname);
                            extra_data.put(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_DOCUMENT_NAME,
                                    desc + "-" + id + "-" + output_filename.replaceAll("[^A-Za-z0-9]", "-"));
                            extra_data.put(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_BLOCK_TYPE,
                                    block.getKey());

                            MiddleData md = new MiddleData(id,
                                    DataExchangeLiterals.ID_TEXTMININGPARSER_GATERESEARCHER,
                                    DataExchangeLiterals.ID_TEXTMININGPARSER_GATERESEARCHER_DEFAULTANNREC,
                                    output_fileurl, //block.getValue(),
                                    extra_data, verbose, verbose_dir);
                            preprocessedRep.addData(md);
                        }
                    }
                }
            } else {
                //extra_data.put("block_type", "WHOLE_CV");
                HashMap<String, String> extra_data = new HashMap<String, String>();
                extra_data.put(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_LASTNAME, lastname);
                extra_data.put(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_INITIALS, initials);
                extra_data.put(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_NAME, name);
                extra_data.put(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_FIRSTNAME, firstname);
                MiddleData md = new MiddleData(id, DataExchangeLiterals.ID_TEXTMININGPARSER_GATERESEARCHER,
                        DataExchangeLiterals.ID_TEXTMININGPARSER_GATERESEARCHER_DEFAULTANNREC,
                        researcher_page_url, extra_data, verbose, verbose_dir);
                preprocessedRep.addData(md);
            }

            count++;
        }

        ProjectLogger.LOGGER.info(count + " documents added");
    } else {
        ProjectLogger.LOGGER.info("Miss some fields in the csv content");
    }

    return preprocessedRep;
}

From source file:com.discovery.darchrow.net.URIUtil.java

/**
 * ?url./*from w  w  w  .ja va2  s .c om*/
 *
 * @param filePathName
 *            
 * @return url
 * @see java.io.File#toURI()
 * @see java.net.URI#toURL()
 */
public static URL getURL(String filePathName) {
    if (Validator.isNullOrEmpty(filePathName)) {
        throw new NullPointerException("filePathName can't be null/empty!");
    }

    File file = new File(filePathName);
    try {
        // file.toURL() ?,? URL ?
        return file.toURI().toURL();
    } catch (MalformedURLException e) {
        LOGGER.error("MalformedURLException:", e);
        throw new URIParseException(e);
    }
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Stop TG server asynchronously. // w  w w.  jav a2 s.c  o  m
 * Return after Admin operation completes but server will take extra time to really stop.
 * 
 * @param tgHome TG admin home
 * @param url Url to connect to TG server
 * @param user User name
 * @param pwd User password
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param waitToCompletion Number of milliseconds to wait for this call to return
 * 
 * @return Output console of stop operation 
 * @throws TGAdminException Admin execution fails 
 */
public static String stopServer(String tgHome, String url, String user, String pwd, String logFile,
        String logLevel, long waitToCompletion) throws TGAdminException {

    String stopCmd = "stop server\ndisconnect\nexit";
    File cmdFile;
    try {
        cmdFile = new File(tgHome + "/stopAdminScript.txt");
        Files.write(Paths.get(cmdFile.toURI()), stopCmd.getBytes(StandardCharsets.UTF_8));
    } catch (IOException ioe) {
        throw new TGAdminException("TGAdmin - " + ioe.getMessage());
    }
    TGAdmin.showOperationBanner = false;
    String output = TGAdmin.invoke(tgHome, url, user, pwd, logFile, logLevel, cmdFile.getAbsolutePath(), -1,
            20000);
    try {
        Thread.sleep(waitToCompletion); // give some sec for tgdb server to die
    } catch (InterruptedException e) {
        ;
    }
    long endProcTime = System.currentTimeMillis();
    long totalProcTime = endProcTime - TGAdmin.startProcTime;
    if (TGAdmin.showStopServerBanner)
        System.out.println("TGAdmin - Server stop completed"
                + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output;
}

From source file:com.netflix.config.WebApplicationProperties.java

protected static void initApplicationProperties() throws ConfigurationException, MalformedURLException {
    File appPropFile = new File(appConfFolder + "/" + baseConfigFileName + ".properties");
    File appEnvPropOverrideFile = new File(
            appConfFolder + "/" + baseConfigFileName + getEnvironment() + ".properties");

    // TODO awang, how do we add this to archaius default config?
    PropertiesConfiguration appConf = new PropertiesConfiguration(appPropFile);
    // apply env overrides
    PropertiesConfiguration overrideConf = new PropertiesConfiguration(appEnvPropOverrideFile);
    Properties overrideprops = ConfigurationUtils.getProperties(overrideConf);
    for (Object prop : overrideprops.keySet()) {
        appConf.setProperty("" + prop, overrideprops.getProperty("" + prop));
    }//from  w  ww  .  j a  v  a  2 s . co m
    String path = appPropFile.toURI().toURL().toString();
    System.setProperty(URLConfigurationSource.CONFIG_URL, path);
    ConfigurationManager.loadPropertiesFromConfiguration(appConf);

}

From source file:eu.udig.catalog.jgrass.utils.JGrassCatalogUtilities.java

/**
 * Remove a mapset from a Location in the catalog.
 *
 * <p>Note: this doesn't remove the file. The file removal has to be done separately</p>
 *      // ww w  . j a v  a  2s . co m
 * @param locationPath path to the location from which the mapset has to be removed.
 * @param mapsetName the name of the mapset to remove
 */
public synchronized static void removeMapsetFromCatalog(String locationPath, String mapsetName) {
    // URL locationId = JGrassService.createId(locationPath);
    try {
        File locationFile = new File(locationPath);
        ID locationId = new ID(locationFile.toURI().toURL());
        JGrassService location = CatalogPlugin.getDefault().getLocalCatalog().getById(JGrassService.class,
                locationId, ProgressManager.instance().get());
        location.removeMapset(mapsetName);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        String message = "An error occurred while removing the mapset to the catalog";
        ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, JGrassPlugin.PLUGIN_ID, e);
    }
}

From source file:edu.uci.ics.hyracks.control.common.deployment.DeploymentUtils.java

/**
 * Download remote Http URLs and return the stored local file URLs
 * //w  w  w  . j  av a 2  s  .c o  m
 * @param urls
 *            the remote Http URLs
 * @param deploymentDir
 *            the deployment jar storage directory
 * @param isNC
 *            true is NC/false is CC
 * @return a list of local file URLs
 * @throws HyracksException
 */
private static List<URL> downloadURLs(List<URL> urls, String deploymentDir, boolean isNC)
        throws HyracksException {
    //retry 10 times at maximum for downloading binaries
    int retryCount = 10;
    int tried = 0;
    Exception trace = null;
    while (tried < retryCount) {
        try {
            tried++;
            List<URL> downloadedFileURLs = new ArrayList<URL>();
            File dir = new File(deploymentDir);
            if (!dir.exists()) {
                FileUtils.forceMkdir(dir);
            }
            for (URL url : urls) {
                String urlString = url.toString();
                int slashIndex = urlString.lastIndexOf('/');
                String fileName = urlString.substring(slashIndex + 1).split("&")[1];
                String filePath = deploymentDir + File.separator + fileName;
                File targetFile = new File(filePath);
                if (isNC) {
                    HttpClient hc = HttpClientBuilder.create().build();
                    HttpGet get = new HttpGet(url.toString());
                    HttpResponse response = hc.execute(get);
                    InputStream is = response.getEntity().getContent();
                    OutputStream os = new FileOutputStream(targetFile);
                    try {
                        IOUtils.copyLarge(is, os);
                    } finally {
                        os.close();
                        is.close();
                    }
                }
                downloadedFileURLs.add(targetFile.toURI().toURL());
            }
            return downloadedFileURLs;
        } catch (Exception e) {
            e.printStackTrace();
            trace = e;
        }
    }
    throw new HyracksException(trace);
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Display server info synchronously. //from ww w  .ja v a2  s  .  c  o m
 * Info operation blocks until it is completed.
 * 
 * @param tgServer TG server to get information from
 * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
 *
 * @return Output console of info operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String infoServer(TGServer tgServer, String tgNetListenerName, String logFile, String logLevel,
        long timeout) throws TGAdminException {

    if (tgServer == null)
        throw new TGAdminException("TGAdmin - tgServer cannot be null");

    String infoCmd = "info\ndisconnect\nexit";
    File cmdFile;
    try {
        cmdFile = new File(tgServer.getHome().getAbsolutePath() + "/infoAdminScript.txt");
        Files.write(Paths.get(cmdFile.toURI()), infoCmd.getBytes(StandardCharsets.UTF_8));
    } catch (IOException ioe) {
        throw new TGAdminException("TGAdmin - " + ioe.getMessage());
    }

    TGServer.NetListener netListener = tgServer.getNetListeners()[0]; // default get the 1st one
    if (tgNetListenerName != null) {
        for (TGServer.NetListener net : tgServer.getNetListeners()) {
            if (net.getName().equals(tgNetListenerName)) {
                netListener = net;
            }
        }
    }

    String host = netListener.getHost();
    int port = netListener.getPort();
    String user = tgServer.getSystemUser();
    String pwd = tgServer.getSystemPwd();
    String url;
    try {
        url = "tcp://" + ((netListener.isIPv6()) ? ("[" + host + ":" + port + "]") : (host + ":" + port));
    } catch (TGGeneralException e) {
        throw new TGAdminException("TGAdmin - " + e.getMessage());
    }

    TGAdmin.showOperationBanner = false;
    String output = TGAdmin.invoke(tgServer.getHome().getAbsolutePath(), url, user, pwd, logFile, logLevel,
            cmdFile.getAbsolutePath(), -1, timeout);
    long endProcTime = System.currentTimeMillis();
    long totalProcTime = endProcTime - TGAdmin.startProcTime;
    System.out.println(
            "TGAdmin - Server info completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));

    return output;
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Kill a connection synchronously. //from   w w w.  j a v a2 s  . c om
 * Operation blocks until it is completed.
 * 
 * @param tgServer TG server to kill connections from
 * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
 * @param sessionID specify session ID to kill
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
 *
 * @return Output console 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String killConnection(TGServer tgServer, String tgNetListenerName, String sessionID,
        String logFile, String logLevel, long timeout) throws TGAdminException {

    if (tgServer == null)
        throw new TGAdminException("TGAdmin - tgServer cannot be null");

    String killCmd = "kill connection " + sessionID + "\ndisconnect\nexit";
    File cmdFile;
    try {
        cmdFile = new File(tgServer.getHome().getAbsolutePath() + "/killConnectionAdminScript.txt");
        Files.write(Paths.get(cmdFile.toURI()), killCmd.getBytes(StandardCharsets.UTF_8));
    } catch (IOException ioe) {
        throw new TGAdminException("TGAdmin - " + ioe.getMessage());
    }

    TGServer.NetListener netListener = tgServer.getNetListeners()[0]; // default get the 1st one
    if (tgNetListenerName != null) {
        for (TGServer.NetListener net : tgServer.getNetListeners()) {
            if (net.getName().equals(tgNetListenerName)) {
                netListener = net;
            }
        }
    }

    String host = netListener.getHost();
    int port = netListener.getPort();
    String user = tgServer.getSystemUser();
    String pwd = tgServer.getSystemPwd();
    String url;
    try {
        url = "tcp://" + ((netListener.isIPv6()) ? ("[" + host + ":" + port + "]") : (host + ":" + port));
    } catch (TGGeneralException e) {
        throw new TGAdminException("TGAdmin - " + e.getMessage());
    }

    TGAdmin.showOperationBanner = false;
    String output = TGAdmin.invoke(tgServer.getHome().getAbsolutePath(), url, user, pwd, logFile, logLevel,
            cmdFile.getAbsolutePath(), -1, timeout);
    long endProcTime = System.currentTimeMillis();
    long totalProcTime = endProcTime - TGAdmin.startProcTime;
    System.out.println("TGAdmin - Kill connection completed"
            + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));

    return output;
}