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:DummyAppletContext.java

private String filenameFromURL(URL url) {
    String filename = url.getFile();
    if (filename.charAt(1) == '|') {
        StringBuffer buf = new StringBuffer(filename);
        buf.setCharAt(1, ':');
        filename = buf.toString();/*from   w w w  . ja  v a  2 s. c om*/
    } else if (filename.charAt(2) == '|') {
        StringBuffer buf = new StringBuffer(filename);
        buf.setCharAt(2, ':');
        filename = buf.toString();
    }
    return filename;
}

From source file:org.argouml.application.Main.java

private static void openProject(SimpleTimer st, SplashScreen splash, ProjectBrowser pb, URL urlToOpen) {
    if (splash != null) {
        splash.updateProgress(40);/*from w  w  w . j a  v  a  2  s  . c o  m*/
    }

    st.mark("open project");
    Designer.disableCritiquing();
    Designer.clearCritiquing();

    Project project = null;
    if (urlToOpen != null) {
        if (splash != null) {
            Object[] msgArgs = { projectName };
            splash.showStatus(Translator.messageFormat("statusmsg.bar.readingproject", msgArgs));
        }
        String filename = urlToOpen.getFile();
        File file = new File(filename);
        System.err.println("The url of the file to open is " + urlToOpen);
        System.err.println("The filename is " + filename);
        System.err.println("The file is " + file);
        System.err.println("File.exists = " + file.exists());
        project = pb.loadProject2(file, true, null);
    } else {
        if (splash != null) {
            splash.showStatus(Translator.localize("statusmsg.bar.defaultproject"));
        }
    }

    // We MUST have a project open before continuing. Create if necessary
    if (project == null) {
        project = ProjectManager.getManager().makeEmptyProject(true);
    }
    ProjectManager.getManager().setCurrentProject(project);
    project.setDirty(false);

    st.mark("set project");
    Designer.enableCritiquing();
}

From source file:haven.Utils.java

public static URL urlparam(URL base, String... pars) {
    /* Why is Java so horribly bad? */
    String file = base.getFile();
    int p = file.indexOf('?');
    StringBuilder buf = new StringBuilder();
    if (p >= 0) {
        /* For now, only add; don't augment. Since Java sucks. */
        buf.append('&');
    } else {/*w  w  w.  j  a  v a2  s  .  com*/
        buf.append('?');
    }
    for (int i = 0; i < pars.length; i += 2) {
        if (i > 0)
            buf.append('&');
        buf.append(urlencode(pars[i]));
        buf.append('=');
        buf.append(urlencode(pars[i + 1]));
    }
    try {
        return (new URL(base.getProtocol(), base.getHost(), base.getPort(), file + buf.toString()));
    } catch (java.net.MalformedURLException e) {
        throw (new RuntimeException(e));
    }
}

From source file:com.francetelecom.clara.cloud.paas.it.services.helper.PaasServicesEnvApplicationAccessHelper.java

/**
 * Check if a string appear in the html page
 *
 * @param url/* w  w w.j  a v a  2s .c  om*/
 *            URL to test
 * @param token
 *            String that must be in html page
 * @return Cookie that identifies the was or null if the test failed. An
 *         empty string means that no cookie was found in the request, but
 *         the check succeeded.
 */
private static String checkStringAndReturnCookie(URL url, String token, String httpProxyHost,
        int httpProxyPort) {
    InputStream is = null;
    String cookie = null;
    try {
        HttpURLConnection connection;
        if (httpProxyHost != null) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort));
            connection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }
        connection.setRequestMethod("GET");

        is = connection.getInputStream();
        // check http status code
        if (connection.getResponseCode() == 200) {
            DataInputStream dis = new DataInputStream(new BufferedInputStream(is));
            StringWriter writer = new StringWriter();
            IOUtils.copy(dis, writer, "UTF-8");
            if (writer.toString().contains(token)) {
                cookie = connection.getHeaderField("Set-Cookie");
                if (cookie == null)
                    cookie = "";
            } else {
                logger.info("URL " + url.getFile() + " returned code 200 but does not contain keyword '" + token
                        + "'");
                logger.debug("1000 first chars of response body: " + writer.toString().substring(0, 1000));
            }
        } else {
            logger.error("URL " + url.getFile() + " returned code " + connection.getResponseCode() + " : "
                    + connection.getResponseMessage());
            if (System.getProperty("http.proxyHost") != null) {
                logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":"
                        + System.getProperty("http.proxyPort"));
            }
        }
    } catch (IOException e) {
        logger.error("URL test failed: " + url.getFile() + " => " + e.getMessage() + " ("
                + e.getClass().getName() + ")");
        if (System.getProperty("http.proxyHost") != null) {
            logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":"
                    + System.getProperty("http.proxyPort"));
        }
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            // just going to ignore this one
        }
    }
    return cookie;

}

From source file:com.ibm.wala.cast.js.html.DomLessSourceExtractor.java

private File createOutputFile(URL url, boolean delete, boolean useTempName) throws IOException {
    File outputFile;/* ww  w.jav  a2  s  .com*/
    String fileName = new File(url.getFile()).getName();
    if (fileName.length() < 5) {
        fileName = "xxxx" + fileName;
    }
    if (useTempName) {
        outputFile = File.createTempFile(fileName, ".js");
    } else {
        outputFile = new File(fileName);
    }
    if (outputFile.exists()) {
        outputFile.delete();
    }
    if (delete) {
        outputFile.deleteOnExit();
    }
    return outputFile;
}

From source file:eu.scape_project.pt.mapred.input.ControlFileInputFormatTest.java

@Before
public void setUp() throws IOException {
    URL res = this.getClass().getClassLoader().getResource("toolspecs");
    // use the file toolspec xml as the input file too (for this test)
    repo = new LocalToolRepository(res.getFile());
}

From source file:jp.vmi.selenium.selenese.command.AttachFile.java

@Override
protected Result executeImpl(Context context, String... curArgs) {
    String name = curArgs[ARG_FILENAME];
    File outputTo = null;//from   w ww  .j  a  v a 2  s . c  o m
    if (name.contains("://")) {
        // process (remote) url
        URL url;
        try {
            url = new URL(name);
        } catch (MalformedURLException e) {
            return new Error("Malformed URL: " + name);
        }
        File dir = TemporaryFilesystem.getDefaultTmpFS().createTempDir("attachFile", "dir");
        outputTo = new File(dir, new File(url.getFile()).getName());
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(outputTo);
            Resources.copy(url, fos);
        } catch (IOException e) {
            return new Error("Can't access file to upload: " + url, e);
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                return new Warning("Unable to close stream used for reading file: " + name, e);
            }
        }
    } else {
        // process file besides testcase file
        outputTo = new File(FilenameUtils.getPath(context.getCurrentTestCase().getFilename()), name);
        if (!outputTo.exists()) {
            return new Error("Can't access file: " + outputTo);
        }
    }

    WebElement element = context.findElement(curArgs[ARG_LOCATOR]);
    try {
        element.clear();
    } catch (Exception e) {
        // ignore exceptions from some drivers when file-input cannot be cleared;
    }
    element.sendKeys(outputTo.getAbsolutePath());
    return SUCCESS;
}

From source file:com.sastix.cms.server.services.content.ResourceServiceTest.java

@Test
public void shouldCreateResourceFromExternalUri() throws Exception {
    URL localFile = getClass().getClassLoader().getResource("./logo.png");
    CreateResourceDTO createResourceDTO = new CreateResourceDTO();
    createResourceDTO.setResourceAuthor("Demo Author");
    createResourceDTO.setResourceExternalURI(localFile.getProtocol() + "://" + localFile.getFile());
    createResourceDTO.setResourceMediaType("image/png");
    createResourceDTO.setResourceName("logo.png");
    createResourceDTO.setResourceTenantId("zaq12345");
    ResourceDTO resourceDTO = resourceService.createResource(createResourceDTO);

    String resourceUri = resourceDTO.getResourceURI();

    //Extract TenantID
    final String tenantID = resourceUri.substring(resourceUri.lastIndexOf('-') + 1, resourceUri.indexOf("/"));

    final Path responseFile = hashedDirectoryService.getDataByURI(resourceUri, tenantID);
    File file = responseFile.toFile();

    byte[] actualBytes = Files.readAllBytes(file.toPath());
    byte[] expectedBytes = Files.readAllBytes(Paths.get(localFile.getPath()));
    Assert.assertArrayEquals(expectedBytes, actualBytes);
}

From source file:idgs.client.TcpClientPool.java

public void loadClientConfig(String clientCfgFile) throws IOException {
    log.info("Load client config file " + clientCfgFile);
    File file = new File(clientCfgFile);
    do {/*  ww w.  jav a 2s .co  m*/
        if (file.exists()) {
            break;
        }

        String temppath;
        // IDGS_HOME env
        if ((temppath = System.getenv("IDGS_HOME")) != null) {
            temppath = temppath + "/" + clientCfgFile;
            file = new File(temppath);
            if (file.exists()) {
                break;
            }
        }

        URL url = TcpClientPool.class.getClassLoader().getResource(clientCfgFile);
        if (url != null) {
            file = new File(url.getFile());
            break;
        }

        log.error("Client config file " + clientCfgFile + " is not found.");
        try {
            throw new IOException("Client config file " + clientCfgFile + " is not found.");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    } while (false);

    ClientConfig.Builder builder = ClientConfig.newBuilder();
    try {
        log.info("Load client config file " + file);
        JsonUtil.jsonFileToPb(builder, file);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
    cfg = builder.build();
    loadClientConfig();
}

From source file:com.hpe.application.automation.tools.run.RunLoadRunnerScript.java

private FilePath copyXsltToNode(@Nonnull FilePath workspace) throws IOException, InterruptedException {
    final URL xsltPath = jenkinsInstance.pluginManager.uberClassLoader.getResource(LR_SCRIPT_HTML_XSLT);
    logger.println("loading XSLT from " + xsltPath.getFile());
    FilePath xsltOnNode = workspace.child("resultsHtml.xslt");
    if (!xsltOnNode.exists()) {
        xsltOnNode.copyFrom(xsltPath);//from  w ww .j  a v  a  2 s  .  co m
    }
    return xsltOnNode;
}