Example usage for java.io File toURL

List of usage examples for java.io File toURL

Introduction

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

Prototype

@Deprecated
public URL toURL() throws MalformedURLException 

Source Link

Document

Converts this abstract pathname into a file: URL.

Usage

From source file:org.deegree.ogcwebservices.wass.wss.operation.WSSOperationTest.java

/**
 * @throws Exception/*from  w  w  w  .  j a va2s .c o  m*/
 */
public void testCloseSession() throws Exception {
    if (skip) {
        LOG.logInfo("Skipping WSS service test (no database available?).");
        return;
    }
    LOG.logInfo("\n\nTesting CloseSession with xml_examplefile");
    assertNotNull("Service not initialized", service);
    SessionOperationsDocument doc = new SessionOperationsDocument();
    assertNotNull("Could not create empty session document", doc);
    File xml = new File(resourceLocation + "requests/CloseSession/CloseSessionExample_1.xml");
    doc.load(xml.toURL());
    CloseSession request = doc.parseCloseSession("1", doc.getRootElement());
    /*
     * Just add the read id, which is of course not a "real" test.
     */
    MemoryBasedSessionManager sessionManager = MemoryBasedSessionManager.getInstance();
    sessionManager.addSession(new Session(new SessionID(request.getSessionID(), 200000)));
    doCloseSession(request);
}

From source file:com.openmeap.admin.web.servlet.WebViewServlet.java

@SuppressWarnings("unchecked")
@Override/*from  w  ww . ja  v  a2s  .c  o m*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    logger.trace("in service");

    ModelManager mgr = getModelManager();
    GlobalSettings settings = mgr.getGlobalSettings();
    String validTempPath = settings.validateTemporaryStoragePath();
    if (validTempPath != null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, validTempPath);
    }

    String pathInfo = request.getPathInfo();
    String[] pathParts = pathInfo.split("[/]");
    if (pathParts.length < 4) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    String remove = pathParts[1] + "/" + pathParts[2] + "/" + pathParts[3];
    String fileRelative = pathInfo.replace(remove, "");

    String applicationNameString = URLDecoder.decode(pathParts[APP_NAME_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    String archiveHash = URLDecoder.decode(pathParts[APP_VER_INDEX], FormConstants.CHAR_ENC_DEFAULT);

    Application app = mgr.getModelService().findApplicationByName(applicationNameString);
    ApplicationArchive arch = mgr.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archiveHash,
            "MD5");

    String authSalt = app.getProxyAuthSalt();
    String authToken = URLDecoder.decode(pathParts[AUTH_TOKEN_INDEX], FormConstants.CHAR_ENC_DEFAULT);

    try {
        if (!AuthTokenProvider.validateAuthToken(authSalt, authToken)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (DigestException e1) {
        throw new GenericRuntimeException(e1);
    }

    File fileFull = new File(
            arch.getExplodedPath(settings.getTemporaryStoragePath()).getAbsolutePath() + "/" + fileRelative);
    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(fileFull.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(fileFull.length()).intValue());

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //response.setStatus(HttpServletResponse.SC_FOUND);
            inputStream = new FileInputStream(fileFull);
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.deegree.ogcwebservices.wass.wss.operation.WSSOperationTest.java

/**
 * @throws Exception/*  w  ww  . j  av  a  2  s  . c o m*/
 */
public void testGetCapabilities() throws Exception {
    if (skip) {
        LOG.logInfo("Skipping WSS service test (no database available?).");
        return;
    }
    LOG.logInfo("\n\nTesting GetCapabilities with xml_examplefile");
    assertNotNull("Service not initialized", service);
    WSSGetCapabilitiesDocument doc = new WSSGetCapabilitiesDocument();
    assertNotNull("Could not create empty GetCapabilities document", doc);
    File xml = new File(resourceLocation + "requests/GetCapabilities/GetCapabilitiesExample_1.xml");
    doc.load(xml.toURL());
    WSSGetCapabilities request = doc.parseCapabilities("2222", doc.getRootElement());
    doGetCapabilities(request);
}

From source file:org.apache.batik.transcoder.image.AbstractImageTranscoderTest.java

/**
 * Resolves the input string as follows.
 * + First, the string is interpreted as a file description.
 *   If the file exists, then the file name is turned into
 *   a URL./*from w  w w  .  ja  v a 2s  .c o  m*/
 * + Otherwise, the string is supposed to be a URL. If it
 *   is an invalid URL, an IllegalArgumentException is thrown.
 */
protected URL resolveURL(String url) {
    // Is url a file?
    File f = (new File(url)).getAbsoluteFile();
    if (f.getParentFile().exists()) {
        try {
            return f.toURL();
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException();
        }
    }

    // url is not a file. It must be a regular URL...
    try {
        return new URL(url);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(url);
    }
}

From source file:org.apache.struts.plugins.DigestingPlugIn.java

/**
 * Given a string, return a URL to a Filesystem resource of that name.
 * @param path a path to a file.//from   w  w w.java 2s .co m
 * @return a URL identifying the resource in the in the file system.
 * @throws MalformedURLException
 * @throws FileNotFoundException
 */
protected URL getFileURL(String path) throws IOException {
    File file = new File(path);
    return file.toURL();
}

From source file:org.kalypso.gml.ParserTest.java

public void ftestload() throws Exception {
    try {/*from   w w  w  . j  av a2  s  . com*/
        final URL resource = getClass().getResource("resources/modell.gml");
        // final URL resource = getClass().getResource( "resources/dictionary.gml" );
        // final URL resource = getClass().getResource( "resources/_timeseriesNoDict.gml" );

        final GMLWorkspace workspace = GmlSerializer.createGMLWorkspace(resource, null);
        final File file = new File("C:/TMP/newParserInAndNewOut.gml");
        final OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        GmlSerializer.serializeWorkspace(writer, workspace);
        IOUtils.closeQuietly(writer);

        // secound pass
        final GMLWorkspace workspace2 = GmlSerializer.createGMLWorkspace(file.toURL(), null);
        final File file2 = new File("C:/TMP/newParserInAndNewOut2.gml");
        final OutputStreamWriter writer2 = new OutputStreamWriter(new FileOutputStream(file2), "UTF-8");
        GmlSerializer.serializeWorkspace(writer2, workspace2);
        IOUtils.closeQuietly(writer2);
    } catch (final Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.basket3.filesystem.FileS3ObjectTest.java

/**
 * Test the output stream method./*  ww w  . ja v a2s.co m*/
 */
public void test_outputStream() {
    File file;
    GAES3Object s3Object;

    try {
        file = File.createTempFile("unitTest", null);

        file.deleteOnExit();

        s3Object = new GAES3Object("bucket", "key", file.toURL());

        OutputStream out = s3Object.getOutputStream();

        out.write("12345".getBytes());

        out.close();

        InputStream in = new FileInputStream(file);

        assertEquals("Unexpected value", '1', in.read());
        assertEquals("Unexpected value", '2', in.read());
        assertEquals("Unexpected value", '3', in.read());
        assertEquals("Unexpected value", '4', in.read());
        assertEquals("Unexpected value", '5', in.read());
        assertEquals("Unexpected value", -1, in.read());
    } catch (IOException e) {
        e.printStackTrace();
        fail("Unexpected exception");
        return;
    }
}

From source file:com.jpeterson.littles3.bo.FileS3ObjectTest.java

/**
 * Test the output stream method./* ww  w. ja v  a  2  s  . c o  m*/
 */
public void test_outputStream() {
    File file;
    FileS3Object s3Object;

    try {
        file = File.createTempFile("unitTest", null);

        file.deleteOnExit();

        s3Object = new FileS3Object("bucket", "key", file.toURL());

        OutputStream out = s3Object.getOutputStream();

        out.write("12345".getBytes());

        out.close();

        InputStream in = new FileInputStream(file);

        assertEquals("Unexpected value", '1', in.read());
        assertEquals("Unexpected value", '2', in.read());
        assertEquals("Unexpected value", '3', in.read());
        assertEquals("Unexpected value", '4', in.read());
        assertEquals("Unexpected value", '5', in.read());
        assertEquals("Unexpected value", -1, in.read());
    } catch (IOException e) {
        e.printStackTrace();
        fail("Unexpected exception");
        return;
    }
}

From source file:io.fabric8.agent.mvn.MavenConfigurationImpl.java

/**
 * Returns the URL of settings file. Will try first to use the url as is. If a malformed url encountered then will
 * try to use the url as a file path. If still not valid will throw the original Malformed URL exception.
 *
 * @see MavenConfiguration#getSettingsFileUrl()
 *///from  w  ww  .ja  va  2 s .co m
public URL getSettingsFileUrl() {
    if (!contains(m_pid + MavenConstants.PROPERTY_SETTINGS_FILE)) {
        String spec = m_propertyResolver.get(m_pid + MavenConstants.PROPERTY_SETTINGS_FILE);
        if (spec != null) {
            try {
                return set(m_pid + MavenConstants.PROPERTY_SETTINGS_FILE, new URL(spec));
            } catch (MalformedURLException e) {
                File file = new File(spec);
                if (file.exists()) {
                    try {
                        return set(m_pid + MavenConstants.PROPERTY_SETTINGS_FILE, file.toURL());
                    } catch (MalformedURLException ignore) {
                        // ignore as it usually should not happen since we already have a file
                    }
                } else {
                    LOGGER.warn("Settings file [" + spec
                            + "] cannot be used and will be skipped (malformed url or file does not exist)");
                    set(m_pid + MavenConstants.PROPERTY_SETTINGS_FILE, null);
                }
            }
        }
    }
    return get(m_pid + MavenConstants.PROPERTY_SETTINGS_FILE);
}

From source file:org.apache.struts2.config.StrutsXmlConfigurationProvider.java

protected URL findInFileSystem(String fileName) throws IOException {
    URL url = null;//from w w w .j  ava2s .com
    File file = new File(fileName);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Trying to load file " + file);
    }

    // Trying relative path to original file
    if (!file.exists()) {
        file = new File(baseDir, fileName);
    }
    if (file.exists()) {
        try {
            url = file.toURL();
        } catch (MalformedURLException e) {
            throw new IOException("Unable to convert " + file + " to a URL");
        }
    }
    return url;
}