Example usage for java.net URL getPath

List of usage examples for java.net URL getPath

Introduction

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

Prototype

public String getPath() 

Source Link

Document

Gets the path part of this URL .

Usage

From source file:com.t3.persistence.FileUtil.java

/**
 * Given a URL this method tries to figure out what the content type might be based
 * only on the filename extension.// w  w  w  .  ja  v  a2  s .com
 * 
 * @param url the URL to check
 * @return a <code>String</code> representing the content type name
 */
public static String getContentType(URL url) {
    String type = "";
    type = URLConnection.guessContentTypeFromName(url.getPath());
    if (log.isDebugEnabled())
        log.debug("result from guessContentTypeFromName(" + url.getPath() + ") is " + type);
    return type;
}

From source file:com.shengpay.commons.bp.logback.LogbackConfigurer.java

/**
 * Initialize logback from the given file location, with no config file refreshing. Assumes an XML file in case of a ".xml" file extension, and a properties file otherwise.
 * //from   w w  w  .ja v a  2 s. c  o m
 * @param location
 *            the location of the config file: either a "classpath:" location (e.g. "classpath:mylogback.properties"), an absolute file URL (e.g. "file:C:/logback.properties), or a plain absolute path in the file system (e.g. "C:/logback.properties")
 * @throws FileNotFoundException
 *             if the location specifies an invalid file path
 */
public static void initLogging(String location) throws FileNotFoundException {
    String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);
    URL url = ResourceUtils.getURL(resolvedLocation);
    if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION)) {
        //          DOMConfigurator.configure(url);
        configurator.setContext(lc);
        lc.reset();
        try {
            configurator.doConfigure(url);
        } catch (JoranException ex) {
            throw new FileNotFoundException(url.getPath());
        }
        lc.start();
    }
    //      else {
    //          PropertyConfigurator.configure(url);
    //      }
}

From source file:org.unitedinternet.cosmo.dav.caldav.report.MultigetReport.java

private static boolean isDescendentOrEqual(URL collection, URL test) {
    if (collection == null || test == null) {
        return false;
    }/*from   ww  w  . j  av  a2 s  . c o  m*/
    if (collection.toString().equals(test.toString())) {
        return true;
    }

    try {
        String testPathDecoded = UriUtils.decode(test.getPath(), "UTF-8");
        String collectionPathDecoded = UriUtils.decode(collection.getPath(), "UTF-8");

        return testPathDecoded.startsWith(collectionPathDecoded);
    } catch (UnsupportedEncodingException e) {
        return test.getPath().startsWith(collection.getPath());
    }
}

From source file:URLUtil.java

/**
 * Method that tries to get a stream (ideally, optimal one) to write to the
 * resource specified by given URL. Currently it just means creating a simple
 * file output stream if the URL points to a (local) file, and otherwise
 * relying on URL classes input stream creation method.
 *//*from  w  w  w.  j  a  va2 s .co  m*/
public static OutputStream outputStreamFromURL(URL url) throws IOException {
    if ("file".equals(url.getProtocol())) {
        /*
         * As per [WSTX-82], can not do this if the path refers to a network drive
         * on windows.
         */
        String host = url.getHost();
        if (host == null || host.length() == 0) {
            return new FileOutputStream(url.getPath());
        }
    }
    return url.openConnection().getOutputStream();
}

From source file:com.eryansky.common.utils.io.FileUtil.java

@SuppressWarnings("rawtypes")
public static String getAppPath(Class cls) {
    // ??//w w  w.  j a  v a  2  s .  c om
    if (cls == null)
        throw new java.lang.IllegalArgumentException("???");
    ClassLoader loader = cls.getClassLoader();
    // ????
    String clsName = cls.getName() + ".class";
    // ?
    Package pack = cls.getPackage();
    String path = "";
    // ?????
    if (pack != null) {
        String packName = pack.getName();
        // ??JavaJDK
        if (packName.startsWith("java.") || packName.startsWith("javax."))
            throw new java.lang.IllegalArgumentException("????");
        // ??????
        clsName = clsName.substring(packName.length() + 1);
        // ?????????
        if (packName.indexOf(".") < 0)
            path = packName + "/";
        else {// ???????
            int start = 0, end = 0;
            end = packName.indexOf(".");
            while (end != -1) {
                path = path + packName.substring(start, end) + "/";
                start = end + 1;
                end = packName.indexOf(".", start);
            }
            path = path + packName.substring(start) + "/";
        }
    }
    // ClassLoadergetResource????
    java.net.URL url = loader.getResource(path + clsName);
    // URL??
    String realPath = url.getPath();
    // ?????"file:"
    int pos = realPath.indexOf("file:");
    if (pos > -1)
        realPath = realPath.substring(pos + 5);
    // ????
    pos = realPath.indexOf(path + clsName);
    realPath = realPath.substring(0, pos - 1);
    // JARJAR??
    if (realPath.endsWith("!"))
        realPath = realPath.substring(0, realPath.lastIndexOf("/"));
    /*------------------------------------------------------------ 
     ClassLoadergetResourceutf-8?? 
      ??? 
      URLDecoderdecode? 
      ? 
    -------------------------------------------------------------*/
    try {
        realPath = java.net.URLDecoder.decode(realPath, "utf-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    System.out.println("realPath----->" + realPath);
    return realPath;
}

From source file:com.ms.commons.test.common.FileUtil.java

public static File convertURLToFile(URL url) {
    if (url == null) {
        return null;
    }/*from   w  ww .j a va 2 s  .c o  m*/

    try {
        return new File(url.toURI());
    } catch (URISyntaxException e) {
        try {
            return new File(URLDecoder.decode(url.getPath(), "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            return new File(url.getPath());
        }
    }
}

From source file:com.example.aliyundemo.ocr.util.HttpUtil.java

/**
 * ?Header// w w  w .j a v  a2  s  .c  om
 *
 * @param headers              Http
 * @param appKey               APP KEY
 * @param appSecret            APP
 * @param method               Http
 * @param requestAddress       http://host+path+query
 * @param formParam            ??
 * @param signHeaderPrefixList ???Header?
 * @return Header
 * @throws MalformedURLException
 */
private static Map<String, String> initialBasicHeader(Map<String, String> headers, String appKey,
        String appSecret, String method, String requestAddress, Map formParam,
        List<String> signHeaderPrefixList) throws MalformedURLException {
    if (headers == null) {
        headers = new HashMap<String, String>();
    }

    URL url = new URL(requestAddress);
    StringBuilder stringBuilder = new StringBuilder();
    if (StringUtils.isNotBlank(url.getPath())) {
        stringBuilder.append(url.getPath());
    }
    if (StringUtils.isNotBlank(url.getQuery())) {
        stringBuilder.append("?");
        stringBuilder.append(url.getQuery());
    }

    headers.put(HttpHeader.HTTP_HEADER_USER_AGENT, Constants.USER_AGENT);
    headers.put(SystemHeader.X_CA_TIMESTAMP, String.valueOf(new Date().getTime()));
    headers.put(SystemHeader.X_CA_NONCE, UUID.randomUUID().toString());
    headers.put(SystemHeader.X_CA_KEY, appKey);
    headers.put(SystemHeader.X_CA_SIGNATURE, SignUtil.sign(method, stringBuilder.toString(), headers, formParam,
            appSecret, signHeaderPrefixList));

    return headers;
}

From source file:dk.dma.msinm.common.mail.AttachmentMailPart.java

/**
 * Instantiates an attachment mail part from a URL
 * @param urlStr the attachment URL//w w  w.java 2  s  .co  m
 * @param name the name of the attachment.
 */
public static AttachmentMailPart fromUrl(String urlStr, String name) throws MessagingException {
    // Check that the file is valid
    URL url;
    try {
        url = new URL(urlStr);
    } catch (MalformedURLException ex) {
        throw new MessagingException("Invalid url attachment: " + urlStr);
    }

    // If name is not specified, compute it from the file
    if (StringUtils.isBlank(name)) {
        name = url.getPath();
        if (name.contains("/")) {
            name = name.substring(name.lastIndexOf("/") + 1);
        }
        if (StringUtils.isBlank(name)) {
            name = "unknown";
        }
    }

    // Instantiate a mail attachment
    AttachmentMailPart a = new AttachmentMailPart(name);
    a.url = url;
    return a;
}

From source file:heigit.ors.util.FileUtility.java

public static String getFileName(URL extUrl) {
    // URL://w  w  w . j  a  va 2s . c  om
    // "http://photosaaaaa.net/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg"
    String filename = "";
    // PATH:
    // /photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg
    String path = extUrl.getPath();
    // Checks for both forward and/or backslash
    // NOTE:**While backslashes are not supported in URL's
    // most browsers will autoreplace them with forward slashes
    // So technically if you're parsing an html page you could run into
    // a backslash , so i'm accounting for them here;
    String[] pathContents = path.split("[\\\\/]");
    if (pathContents != null) {
        int pathContentsLength = pathContents.length;
        System.out.println("Path Contents Length: " + pathContentsLength);
        for (int i = 0; i < pathContents.length; i++) {
            System.out.println("Path " + i + ": " + pathContents[i]);
        }
        // lastPart: s659629384_752969_4472.jpg
        String lastPart = pathContents[pathContentsLength - 1];
        String[] lastPartContents = lastPart.split("\\.");
        if (lastPartContents != null && lastPartContents.length > 1) {
            int lastPartContentLength = lastPartContents.length;
            System.out.println("Last Part Length: " + lastPartContentLength);
            // filenames can contain . , so we assume everything before
            // the last . is the name, everything after the last . is the
            // extension
            String name = "";
            for (int i = 0; i < lastPartContentLength; i++) {
                System.out.println("Last Part " + i + ": " + lastPartContents[i]);
                if (i < (lastPartContents.length - 1)) {
                    name += lastPartContents[i];
                    if (i < (lastPartContentLength - 2)) {
                        name += ".";
                    }
                }
            }
            String extension = lastPartContents[lastPartContentLength - 1];
            filename = name + "." + extension;
            System.out.println("Name: " + name);
            System.out.println("Extension: " + extension);
            System.out.println("Filename: " + filename);
        }
    }
    return filename;
}

From source file:org.dataconservancy.dcs.integration.main.ManualDepositIT.java

@BeforeClass
public static void loadProperties() throws IOException {
    final URL defaultProps = ManualDepositIT.class.getResource("/default.properties");
    assertNotNull("Could not resolve /default.properties from the classpath.", defaultProps);
    assertTrue("default.properties does not exist.", new File(defaultProps.getPath()).exists());
    props.load(defaultProps.openStream());
}