Example usage for java.net URL getProtocol

List of usage examples for java.net URL getProtocol

Introduction

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

Prototype

public String getProtocol() 

Source Link

Document

Gets the protocol name of this URL .

Usage

From source file:com.devicehive.application.filter.SwaggerFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    URL requestUrl = new URL(request.getRequestURL().toString());
    logger.debug("Swagger filter triggered by '{}: {}'. Request will be redirected to swagger page",
            request.getMethod(), requestUrl);

    String swaggerJsonUrl = String.format("%s://%s:%s%s%s/swagger.json", requestUrl.getProtocol(),
            requestUrl.getHost(),//from   w  w w.  j  ava  2s.com
            requestUrl.getPort() == -1 ? requestUrl.getDefaultPort() : requestUrl.getPort(),
            request.getContextPath(), JerseyConfig.REST_PATH);
    String url = request.getContextPath() + "/swagger.html?url=" + swaggerJsonUrl;

    logger.debug("Request is being redirected to '{}'", url);
    response.sendRedirect(url);
}

From source file:de.thetaphi.forbiddenapis.cli.CliMain.java

private void printHelp(Options options) {
    final HelpFormatter formatter = new HelpFormatter();
    String clazzName = getClass().getName();
    String cmdline = "java " + clazzName;
    try {/*  ww w.j  av a  2s. c  om*/
        final URLConnection conn = getClass().getClassLoader()
                .getResource(AsmUtils.getClassResourceName(clazzName)).openConnection();
        if (conn instanceof JarURLConnection) {
            final URL jarUrl = ((JarURLConnection) conn).getJarFileURL();
            if ("file".equalsIgnoreCase(jarUrl.getProtocol())) {
                final String cwd = new File(".").getCanonicalPath(),
                        path = new File(jarUrl.toURI()).getCanonicalPath();
                cmdline = "java -jar "
                        + (path.startsWith(cwd) ? path.substring(cwd.length() + File.separator.length())
                                : path);
            }
        }
    } catch (IOException ioe) {
        // ignore, use default cmdline value
    } catch (URISyntaxException use) {
        // ignore, use default cmdline value
    }
    formatter.printHelp(cmdline + " [options]", "Scans a set of class files for forbidden API usage.", options,
            String.format(Locale.ENGLISH,
                    "Exit codes: %d = SUCCESS, %d = forbidden API detected, %d = invalid command line, %d = unsupported JDK version, %d = other error (I/O,...)",
                    EXIT_SUCCESS, EXIT_VIOLATION, EXIT_ERR_CMDLINE, EXIT_UNSUPPORTED_JDK, EXIT_ERR_OTHER));
}

From source file:UnpackedJarFile.java

public static File toTempFile(URL url) throws IOException {
    InputStream in = null;/*w w w  .ja  va 2  s .c  om*/
    OutputStream out = null;
    JarFile jarFile = null;
    try {
        if (url.getProtocol().equalsIgnoreCase("jar")) {
            // url.openStream() locks the jar file and does not release the lock even after the stream is closed.
            // This problem is avoided by using JarFile APIs.
            File file = new File(url.getFile().substring(5, url.getFile().indexOf("!/")));
            String path = url.getFile().substring(url.getFile().indexOf("!/") + 2);
            jarFile = new JarFile(file);
            JarEntry jarEntry = jarFile.getJarEntry(path);
            if (jarEntry != null) {
                in = jarFile.getInputStream(jarEntry);
            } else {
                throw new FileNotFoundException("JarEntry " + path + " not found in " + file);
            }
        } else {
            in = url.openStream();
        }
        int index = url.getPath().lastIndexOf(".");
        String extension = null;
        if (index > 0) {
            extension = url.getPath().substring(index);
        }
        File tempFile = createTempFile(extension);

        out = new FileOutputStream(tempFile);

        writeAll(in, out);
        return tempFile;
    } finally {
        close(out);
        close(in);
        close(jarFile);
    }
}

From source file:com.boundlessgeo.geoserver.api.controllers.IO.java

private static String source(URL url, GeoServerDataDirectory dataDir) {
    File baseDirectory = dataDir.getResourceLoader().getBaseDirectory();

    if (url.getProtocol().equals("file")) {
        File file = Files.url(baseDirectory, url.toExternalForm());
        if (file != null && !file.isAbsolute()) {
            return Paths.convert(baseDirectory, file);
        }/*w w  w .  j  a  v a2s .c  om*/
    }
    return url.toExternalForm();
}

From source file:com.xtructure.xutil.AbstractRunTests.java

/**
 * Processes the given resources./*  w w  w. jav a  2  s.co  m*/
 * 
 * @param packageName
 *            the name of the package currently being processed
 */
private final void processResources(final String packageName) {
    for (final URL resourceUrl : getResourceURLs(packageName)) {
        if (resourceUrl.getProtocol().equalsIgnoreCase("jar")) {
            processJarResource(packageName, resourceUrl);
        } else if (resourceUrl.getProtocol().equalsIgnoreCase("file")) {
            processFileResource(packageName, resourceUrl);
        }
    }
}

From source file:gov.nih.nci.caintegrator.web.action.analysis.GenePatternAnalysisForm.java

/**
 * Returns the URL where information on the currently selected analysis method may be found.
 *
 * @return the method information URL.//from w  w w.  j av a  2  s.co  m
 */
public String getAnalysisMethodInformationUrl() {
    try {
        URL serviceUrl = new URL(server.getUrl());
        URL infoUrl = new URL(serviceUrl.getProtocol(), serviceUrl.getHost(), serviceUrl.getPort(),
                "/gp/getTaskDoc.jsp");
        return infoUrl.toExternalForm();
    } catch (MalformedURLException e) {
        throw new IllegalStateException("Server URL should already have been validated.", e);
    }
}

From source file:fr.gael.dhus.server.http.webapp.symmetricDS.SymmetricDSWebapp.java

@Override
public void configure(String dest_folder) throws IOException {
    String configurationFolder = "fr/gael/dhus/server/http/webapp/symmetricDS/web";
    URL u = Thread.currentThread().getContextClassLoader().getResource(configurationFolder);
    if (u != null && "jar".equals(u.getProtocol())) {
        extractJarFolder(u, configurationFolder, dest_folder);
    } else if (u != null) {
        File webAppFolder = new File(dest_folder);
        copyFolder(new File(u.getFile()), webAppFolder);
    }//from  w w  w  . j a  v a 2 s  . co m

    String properties = "fr/gael/dhus/server/http/webapp/symmetricDS/"
            + (scalabilityManager.isMaster() ? "master" : "replica") + ".properties";
    u = Thread.currentThread().getContextClassLoader().getResource(properties);

    String propFile = dest_folder + "/WEB-INF/classes/symmetric.properties";
    if (u != null && "jar".equals(u.getProtocol())) {
        extractJarFile(u, properties, propFile);
    } else if (u != null) {
        File webAppFolder = new File(propFile);
        Files.copy(new File(u.getFile()), webAppFolder);
    }

    Path path = Paths.get(propFile);
    Charset charset = StandardCharsets.UTF_8;

    String content = new String(java.nio.file.Files.readAllBytes(path), charset);
    content = content.replaceAll("%id%", String.format("%03d", scalabilityManager.getReplicaId()));
    content = content.replaceAll("%masterUrl%", scalabilityManager.getMasterUrl());
    content = content.replaceAll("%localUrl%", scalabilityManager.getLocalUrl());

    content = content.replaceAll("%dbDriver%", dataSource.getDriverClass());
    content = content.replaceAll("%dbUrl%", dataSource.getJdbcUrl());
    content = content.replaceAll("%dbUser%", dataSource.getUsername());
    content = content.replaceAll("%dbPassword%", dataSource.getPassword());
    java.nio.file.Files.write(path, content.getBytes(charset));
}

From source file:android.databinding.compilationTest.BaseCompilationTest.java

protected void copyResourceDirectory(String name, String targetPath) throws URISyntaxException, IOException {
    URL dir = getClass().getResource(name);
    assertNotNull(dir);/*from   w  w  w.  jav  a 2  s. c o  m*/
    assertEquals("file", dir.getProtocol());
    File folder = new File(dir.toURI());
    assertTrue(folder.isDirectory());
    File target = new File(testFolder, targetPath);
    int len = folder.getAbsolutePath().length() + 1;
    for (File item : FileUtils.listFiles(folder, null, true)) {
        if (item.getAbsolutePath().equals(folder.getAbsolutePath())) {
            continue;
        }
        String resourcePath = item.getAbsolutePath().substring(len);

        copyResourceTo(name + "/" + resourcePath, new File(target, resourcePath));
    }
}

From source file:com.afis.jx.ckfinder.connector.utils.FileUtils.java

/**
 * Gets absolute path to FileUtils.java file. This path is later used to calculate absolute path to other resources inside application.
 *
 * @return absolute path to FileUtils.java file.
 *///from  w  ww.  ja va2s. com
private static String getClassPath() throws ConnectorException {
    if (fuClassPath == null || fuClassPath.equals("")) {
        java.net.URL url = FileUtils.class.getResource("FileUtils.class");
        String finalPath = null;
        String filePathPrefix = "file:/";

        if ("vfs".equalsIgnoreCase(url.getProtocol())) {
            try {
                org.jboss.vfs.VirtualFile vFile = org.jboss.vfs.VFS.getChild(url.getPath());
                finalPath = org.jboss.vfs.VFSUtils.getPhysicalURI(vFile).getPath();
            } catch (IOException ioex) {
                throw new ConnectorException(ioex);
            }
        } else {
            try {
                finalPath = url.toURI().getSchemeSpecificPart();
            } catch (URISyntaxException ueex) {
                throw new ConnectorException(ueex);
            }
        }

        if (finalPath != null && finalPath.startsWith(filePathPrefix)) {
            finalPath = finalPath.substring(filePathPrefix.length());
        }

        if (finalPath != null && finalPath.startsWith("/")) {
            //Check if this isn't Windows Path.
            String temporary = PathUtils.removeSlashFromBeginning(finalPath);
            if (isStartsWithPattern(drivePatt, temporary)) {
                finalPath = temporary;
            }
        }
        fuClassPath = finalPath;
    }
    return fuClassPath;
}

From source file:com.moviejukebox.tools.FileTools.java

/**
 * Download the image for the specified URL into the specified file. Utilises the WebBrowser downloadImage function to allow for
 * proxy connections.//w  w w . j av a  2s  . c  om
 *
 * @param imageFile
 * @param imageURL
 * @return
 * @throws IOException
 */
public static boolean downloadImage(File imageFile, String imageURL) throws IOException {
    URL url;
    if (imageURL.contains(" ")) {
        url = new URL(imageURL.replaceAll(" ", "%20"));
    } else {
        url = new URL(imageURL);
    }

    if ("file".equals(url.getProtocol())) {
        LOG.debug("Copy from url: '{}'", url);
        try (InputStream in = url.openStream(); OutputStream out = new FileOutputStream(imageFile)) {
            copy(in, out);
        }
        return true;
    }

    // download image
    return YamjHttpClientBuilder.getHttpClient().downloadImage(imageFile, url);
}