Example usage for java.net URL getFile

List of usage examples for java.net URL getFile

Introduction

In this page you can find the example usage for java.net URL getFile.

Prototype

public String getFile() 

Source Link

Document

Gets the file name of this URL .

Usage

From source file:eu.cloud4soa.soa.utils.SemanticAppInitializer.java

public void initialize() throws SOAException {

    try {//  www.j av a  2  s . c  om
        String developerUserDir = "applicationProfiles";
        URL resource = scanPackage(developerUserDir);
        String protocol = resource.getProtocol();
        if (protocol.equals("file")) {
            File file = new File(resource.getFile());
            if (file.isDirectory()) {
                String[] list = file.list();
                for (String fileName : list) {
                    String applicationTurtleProfile = loadTurtleFileIntoString(developerUserDir, fileName);
                    logger.info("Loaded application profile: " + fileName);
                    storeTurtleApplicationProfile(applicationTurtleProfile, developerUriId);
                }
            }
        }
    } catch (IOException ex) {
        logger.error("Error during the creation of the Application profiles", ex);
    }
}

From source file:net.line2soft.preambul.utils.Network.java

/**
 * Downloads a file from the Internet//from  www  .j  av a2s. c  om
 * @param address The URL of the file
 * @param dest The destination directory
 * @return The queried file
 * @throws IOException HTTP connection error, or writing error
 */
public static File download(URL address, File dest) throws IOException {
    File result = null;
    InputStream in = null;
    BufferedOutputStream out = null;
    //Open streams
    try {
        HttpGet httpGet = new HttpGet(address.toExternalForm());
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 4000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        httpClient.setParams(httpParameters);
        HttpResponse response = httpClient.execute(httpGet);

        //Launch streams for download
        in = new BufferedInputStream(response.getEntity().getContent());
        String filename = address.getFile().substring(address.getFile().lastIndexOf("/") + 1);
        File tmp = new File(dest.getPath() + File.separator + filename);
        out = new BufferedOutputStream(new FileOutputStream(tmp));

        //Test if connection is OK
        if (response.getStatusLine().getStatusCode() / 100 == 2) {
            //Download and write
            try {
                int byteRead = in.read();
                while (byteRead >= 0) {
                    out.write(byteRead);
                    byteRead = in.read();
                }
                result = tmp;
            } catch (IOException e) {
                throw new IOException("Error while writing file: " + e.getMessage());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("Error while downloading: " + e.getMessage());
    } finally {
        //Close streams
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
    return result;
}

From source file:com.cognifide.aet.job.common.ArtifactDAOMock.java

public String getArtifactAsUTF8String(DBKey dbKey, String objectID) throws IOException {
    String result;//ww  w . ja  v  a 2  s. c  o  m
    URL filePath = getClass().getClassLoader().getResource(mocksPath + "/" + objectID);
    FileInputStream fsi;
    fsi = new FileInputStream(filePath.getFile());
    result = IOUtils.toString(fsi, StandardCharsets.UTF_8);
    return result;
}

From source file:org.gallery.persist.ImageDaoTest.java

@Before
public void setUp() throws DatabaseUnitException, SQLException, IOException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL url = loader.getResource(jsonfilename);
    file = new File(url.getFile());

    ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:applicationContext-test.xml");
    Connection connection = DataSourceUtils.getConnection((DataSource) ctx.getBean("dataSource"));
    DatabaseConnection dbunitConnection = new DatabaseConnection(connection, null);
    IDataSet expectedDataSet = getDataSet("data-test/full-database.xml");
    DatabaseOperation.CLEAN_INSERT.execute(dbunitConnection, expectedDataSet);
    imageDao = ctx.getBean(ImageDao.class);
}

From source file:edu.indiana.lib.twinpeaks.util.CookieData.java

/**
 * Constructor/*ww w. j a va 2 s . c o m*/
 * @param url URL associated with this cookie
 * @param key Cookie name
 * @param value Cookie value
 */
public CookieData(URL url, String key, String value) {
    int slash = url.getFile().lastIndexOf("/");
    /*
     * Save cookie name and content
     */
    this.key = key;
    this.value = value;
    /*
     * Domain defaults to hostname, path to the "directory" portion of
     * the request, minus all text from the rightmost "/" character to
     * the end of the string...
     */
    this.path = slash < 1 ? "" : url.getFile().substring(0, slash);
    this.domain = url.getHost();

    this.version = null;
    this.expires = null;
    this.maxAge = NULL_AGE;

    this.secure = false;
}

From source file:com.reprezen.swagedit.json.references.JsonDocumentManager.java

/**
 * Returns the JSON representation of the document located at the given URL. If the document is not found or the
 * document is not a valid JSON nor a valid YAML document, this method returns null.
 * //  w  w  w.ja va  2  s  . c om
 * @param url
 *            of the document
 * @return JSON tree
 */
public JsonNode getDocument(URL url) {
    if (documents.containsKey(url)) {
        return documents.get(url);
    }

    JsonNode document;
    if (url.getFile().endsWith("json")) {
        try {
            document = mapper.readTree(url);
        } catch (Exception e) {
            document = null;
        }
    } else if (url.getFile().endsWith("yaml") || url.getFile().endsWith("yml")) {
        try {
            document = yamlMapper.readTree(url);
        } catch (IOException e) {
            document = null;
        }
    } else {
        // cannot decide which format, so we try both parsers
        try {
            document = mapper.readTree(url);
        } catch (Exception e) {
            try {
                document = yamlMapper.readTree(url);
            } catch (IOException ee) {
                document = null;
            }
        }
    }

    if (document != null) {
        documents.put(url, document);
    }
    return document;
}

From source file:com.cubusmail.gwtui.server.services.CubusStartupListener.java

public void contextInitialized(ServletContextEvent servletcontextevent) {

    try {//from www  . j av a 2  s . c o m
        WebApplicationContext context = WebApplicationContextUtils
                .getRequiredWebApplicationContext(servletcontextevent.getServletContext());
        BeanFactory.setContext(context);
    } catch (Throwable e) {
        log.fatal(e.getMessage(), e);
        throw new IllegalStateException("Could not load " + CubusConstants.LOGIN_MODULE_CONFIG_FILE);
    }

    try {
        URL test = CubusStartupListener.class.getClassLoader()
                .getResource(CubusConstants.LOGIN_MODULE_CONFIG_FILE);
        System.setProperty(CubusConstants.JAAS_PROPERTY_NANE, test.getFile());
    } catch (Throwable e) {
        log.fatal(e.getMessage(), e);
        throw new IllegalStateException("Could not load " + CubusConstants.LOGIN_MODULE_CONFIG_FILE);
    }
}

From source file:demo.tomcat.TomcatResources.java

/**
 * Add resources from the classpath//from w ww. j  a v  a2  s. co m
 */
public void addClasspathResources() {
    ClassLoader loader = getClass().getClassLoader();
    if (loader instanceof URLClassLoader) {
        for (URL url : ((URLClassLoader) loader).getURLs()) {
            String file = url.getFile();
            if (file.endsWith(".jar") || file.endsWith(".jar!/")) {
                String jar = url.toString();
                if (!jar.startsWith("jar:")) {
                    // A jar file in the file system. Convert to Jar URL.
                    jar = "jar:" + jar + "!/";
                }
                addJar(jar);
            } else if (url.toString().startsWith("file:")) {
                String dir = url.toString().substring("file:".length());
                if (new File(dir).isDirectory()) {
                    addDir(dir, url);
                }
            }
        }
    }
}

From source file:org.jtalks.poulpe.web.listener.LoggerInitializationListener.java

/**
 * Configures log4j from {@link URL} and checks regular Log4j configure class by extension (like default log4j
 * loader)/*w  w  w  .ja  v  a2  s .co  m*/
 *
 * @param url to configuration file
 * @return {@code true} if one or more appenders was added, {@code false} otherwise
 */
@VisibleForTesting
protected boolean configureLog4j(URL url) {
    if (url.getFile().toLowerCase().endsWith(".xml")) {
        DOMConfigurator.configure(url);
    } else {
        PropertyConfigurator.configure(url);
    }

    // Previous calls doesn't throw any exceptions and doesn't return fail state. 
    // So we check appenders, as most representative error indicator   
    Logger rootLogger = LogManager.getRootLogger();
    if (!rootLogger.getAllAppenders().hasMoreElements()) {
        logToConsole("Log4j error during load configuration file or no appenders presented");
        LogManager.resetConfiguration();
        return false;
    }
    return true;
}

From source file:com.quinsoft.zeidon.standardoe.ApplicationList.java

/**
 * Loads the list of applications from %ZEIDON%/zeidon.app
 *///w  w  w  . j av a  2 s. c  o m
ApplicationList(HomeDirectory home, ZeidonLogger logger) {
    logger.info("Loading application list");

    this.home = home;
    Map<String, ApplicationImpl> apps = new HashMap<String, ApplicationImpl>();

    // First try loading the resources.
    ClassLoader classLoader = getClass().getClassLoader();
    if (classLoader == null)
        classLoader = ClassLoader.getSystemClassLoader();

    try {
        for (Enumeration<URL> element = classLoader.getResources("zeidon.app"); element.hasMoreElements();) {
            URL url = element.nextElement();
            logger.info("Loading applications from resource %s", url.getFile());
            InputStream stream = url.openStream();
            ApplicationHandler appHandler = new ApplicationHandler(apps);
            PortableFileReader.ReadPortableFile(stream, logger, appHandler);
        }
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).appendMessage("Error while attempting to load zeidon.app");
    }

    if (!StringUtils.isBlank(home.getHomeDirectory())) {
        String filename = FilenameUtils.concat(home.getHomeDirectory(), "zeidon.app");
        try {
            InputStream inputStream = JoeUtils.getInputStream(null, filename,
                    logger.getClass().getClassLoader());
            if (inputStream == null)
                logger.info("No zeidon.app found via ZEIDON_HOME.");
            else {
                logger.info("Loading apps using ZEIDON_HOME (%s)/zeidon.app", home.getHomeDirectory());
                ApplicationHandler appHandler = new ApplicationHandler(apps);
                PortableFileReader.ReadPortableFile(inputStream, logger, appHandler);
            }
        } catch (Exception e) {
            throw ZeidonException.wrapException(e).prependFilename(filename);
        }
    }

    if (apps.size() == 0)
        throw new ZeidonException("No resources named zeidon.app found.");

    applications = ImmutableMap.copyOf(apps);
}