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.viddu.handlebars.HandlebarsMojoTest.java

protected Scriptable loadHandlebarsLibrary() throws FileNotFoundException {
    ClassLoader ccl = Thread.currentThread().getContextClassLoader();
    Context handlebarContext = Context.enter();
    URL handleBarsUrl = ccl.getResource("handlebars-1.0.rc.1.js");
    Scriptable globalScope = handlebarContext.initStandardObjects();
    Reader handlebarsReader = new FileReader(new File(handleBarsUrl.getPath()));
    try {//from  w ww.j  av a 2  s .  c o m
        handlebarContext.evaluateReader(globalScope, handlebarsReader, "Handlebars 1_0", 0, null);
    } catch (IOException e) {
        throw new RuntimeException("Exception loading handlebars Library");
    } finally {
        Context.exit();
    }
    return globalScope;
}

From source file:jp.igapyon.selecrawler.SeleCrawlerWebContentGetter.java

public File getFileHtml(final String deviceName, final String urlLookup) throws IOException {
    final URL url = new URL(urlLookup);
    final String serverhostname = url.getHost();
    String path = url.getPath();
    if (path.length() == 0 || path.equals("/") || path.endsWith("/")) {
        path = path + "/index.html";
    }/*  w w  w  . j  a v a2 s  .  c o  m*/

    if (url.getQuery() != null) {
        try {
            path += new URLCodec().encode("?" + url.getQuery());
        } catch (EncoderException e) {
            e.printStackTrace();
        }

    }

    return new File(settings.getPathTargetDir() + deviceName + "/" + serverhostname + path);
}

From source file:ch.sdi.core.impl.data.CsvCollectorTest.java

/**
 * @param aFilename/*w w w . ja  v a2s  .  c  om*/
 * @return
 */
private File toFile(String aFilename) {
    URL url = ClassLoader.getSystemResource(aFilename);
    File file = new File(url.getPath());
    return file;
}

From source file:de.thischwa.pmcms.tool.Link.java

public void init(final String link) {
    try {//from  ww  w .  ja  v  a  2s  .  c  o m
        URI uri = new URI(link);
        String schema = uri.getScheme();
        if (schema != null) {
            if (schema.equalsIgnoreCase("file")) {
                isFile = true;
            } else if (schema.equalsIgnoreCase("javascript")) {
                isExternal = true;
            } else if (schema.equalsIgnoreCase("mailto")) {
                isMailto = true;
                isExternal = true;
            } else if (schema.equalsIgnoreCase("http") && uri.getHost() != null
                    && uri.getHost().equalsIgnoreCase(host)) {
                isExternal = false;
            } else if (schema.equalsIgnoreCase("http") || schema.equalsIgnoreCase("https")
                    || schema.equalsIgnoreCase("ftp") || schema.equalsIgnoreCase("ftps"))
                isExternal = true;
        }
        path = uri.getPath();
    } catch (Exception e) {
        logger.warn("While trying to get the URI: " + e.getMessage(), e);
    }

    try {
        URL url = new URL(link);
        if (path == null)
            path = url.getPath();
        String query = url.getQuery();
        if (query != null) {
            String[] parameterPairs = StringUtils.split(query, "&");
            for (String parameterPair : parameterPairs) {
                if (StringUtils.isNotBlank(parameterPair)) {
                    KeyValue kv = new KeyValue(parameterPair);
                    String val = decodeQuietly(kv.val);
                    parameters.put(kv.key, val);
                }
            }
        }
    } catch (Exception e) {
        if (path == null)
            throw new IllegalArgumentException(e);
    }
}

From source file:com.castlemock.web.mock.rest.converter.wadl.WADLRestDefinitionConverter.java

/**
 * The method provides the functionality to extract the resource base from a provided application element
 * @param applicationElement The application element that contains the resource base
 * @return The resource base from the application element
 * @throws MalformedURLException/*w ww.j a  va 2  s .c  o m*/
 */
private String resourceBase(Element applicationElement) throws MalformedURLException {
    final NodeList resourcesNodeList = applicationElement.getElementsByTagName("resources");
    for (int resourcesIndex = 0; resourcesIndex < resourcesNodeList.getLength(); resourcesIndex++) {
        Node resourcesNode = resourcesNodeList.item(resourcesIndex);
        if (resourcesNode.getNodeType() == Node.ELEMENT_NODE) {
            Element resourcesElement = (Element) resourcesNode;
            String resourceBase = resourcesElement.getAttribute("base");
            URL url = new URL(resourceBase);
            return url.getPath();
        }
    }
    return null;
}

From source file:org.apache.xmlgraphics.util.ClasspathResource.java

/**
     * Tests whether the file /sample.txt with mime-type text/plain exists.
     * //from   w w w .  jav a  2  s .  co  m
     * @throws Exception
     *             in case of an error
     */
    public void testSampleResource() throws Exception {
        final List list = ClasspathResource.getInstance().listResourcesOfMimeType("text/plain");
        boolean found = false;
        final Iterator i = list.iterator();
        while (i.hasNext()) {
            final URL u = (URL) i.next();
            if (u.getPath().endsWith("sample.txt")) {
                found = true;
            }
        }
        assertTrue(found);
    }

From source file:org.gvnix.service.roo.addon.addon.util.WsdlParserUtils.java

/**
 * Method makePackageName.//  www.j  av a2 s .  co m
 * 
 * @param namespace
 * @return
 */
public static String makePackageName(String namespace) {

    String hostname = null;
    String path = "";

    // get the target namespace of the document
    try {

        URL u = new URL(namespace);
        hostname = u.getHost();
        path = u.getPath();

    } catch (MalformedURLException e) {

        if (namespace.indexOf(':') > -1) {

            hostname = namespace.substring(namespace.indexOf(':') + 1);
            if (hostname.indexOf('/') > -1) {

                hostname = hostname.substring(0, hostname.indexOf('/'));
            }
        } else {

            hostname = namespace;
        }
    }

    // if we didn't file a hostname, bail
    if (hostname == null) {
        return null;
    }

    // convert illegal java identifier
    hostname = hostname.replace('-', '_');
    path = path.replace('-', '_');

    // chomp off last forward slash in path, if necessary
    if ((path.length() > 0) && (path.charAt(path.length() - 1) == '/')) {
        path = path.substring(0, path.length() - 1);
    }

    // tokenize the hostname and reverse it
    StringTokenizer st = new StringTokenizer(hostname, ".:");
    String[] words = new String[st.countTokens()];

    for (int i = 0; i < words.length; ++i) {
        words[i] = st.nextToken();
    }

    StringBuffer sb = new StringBuffer(namespace.length());

    for (int i = words.length - 1; i >= 0; --i) {
        addWordToPackageBuffer(sb, words[i], (i == words.length - 1));
    }

    // tokenize the path
    StringTokenizer st2 = new StringTokenizer(path, "/");

    while (st2.hasMoreTokens()) {
        addWordToPackageBuffer(sb, st2.nextToken(), false);
    }

    return sb.toString();
}

From source file:org.openmrs.module.openhmis.cashier.web.controller.CashierController.java

@RequestMapping(method = RequestMethod.GET)
public void render(@RequestParam(value = "providerId", required = false) Integer providerId,
        @RequestParam(value = "returnUrl", required = false) String returnUrl, ModelMap modelMap) {
    Provider provider;//from   w  w  w .  jav  a 2 s.  com
    if (providerId != null) {
        provider = providerService.getProvider(providerId);
    } else {
        provider = ProviderUtil.getCurrentProvider(providerService);
    }

    if (provider == null) {
        throw new APIException(
                "ERROR: Could not locate the provider. Please make sure the user is listed as provider "
                        + "(Admin -> Manage providers)");
    }

    String returnTo = returnUrl;
    if (StringUtils.isEmpty(returnTo)) {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        returnTo = req.getHeader("Referer");

        if (!StringUtils.isEmpty(returnTo)) {
            try {
                URL url = new URL(returnTo);

                returnTo = url.getPath();
                if (StringUtils.startsWith(returnTo, req.getContextPath())) {

                    returnTo = returnTo.substring(req.getContextPath().length());
                }
            } catch (MalformedURLException e) {
                LOG.warn("Could not parse referrer url '" + returnTo + "'");
                returnTo = "";
            }
        }
    }

    // Load the current timesheet information
    Timesheet timesheet = timesheetService.getCurrentTimesheet(provider);
    if (timesheet == null) {
        timesheet = new Timesheet();
        timesheet.setCashier(provider);
        timesheet.setClockIn(new Date());
    }

    // load shift report (this must be refactored for the next version)
    loadShiftReport(modelMap);

    addRenderAttributes(modelMap, timesheet, provider, returnTo);
}

From source file:com.scvngr.levelup.core.net.request.factory.ClaimRequestFactoryTest.java

@SmallTest
public void testBuildClaimLegacyLoyaltyRequest() throws BadRequestException, JSONException {
    final String loyaltyId = "2222";
    final LevelUpRequest request = (LevelUpRequest) new ClaimRequestFactory(getContext(),
            new MockAccessTokenRetriever()).buildClaimLegacyLoyaltyRequest(1, loyaltyId);

    assertEquals(HttpMethod.POST, request.getMethod());
    final JSONObject object = new JSONObject(request.getBody(getContext()))
            .getJSONObject(ClaimRequestFactory.OUTER_PARAM_LEGACY_LOYALTY);
    assertTrue(object.has(ClaimRequestFactory.PARAM_LEGACY_ID));
    assertEquals(loyaltyId, object.get(ClaimRequestFactory.PARAM_LEGACY_ID));
    assertFalse(0 == request.getBodyLength(getContext()));

    final URL url = request.getUrl(getContext());
    assertNotNull(url);/* w w w.j  a v  a2s .  c o m*/
    // Make sure we hit the proper API version and url.
    assertEquals("/v15/loyalties/legacy/1/claims", url.getPath());
}

From source file:com.cloudera.nav.sdk.client.NavigatorPluginTest.java

@Before
public void setUp() {
    mockWriter = mock(MetadataWriter.class);
    mockFactory = mock(MetadataWriterFactory.class);
    doReturn(mockWriter).when(mockFactory).newWriter();
    URL url = this.getClass().getClassLoader().getResource("nav_plugin.conf");
    ClientConfigFactory factory = new ClientConfigFactory();
    config = factory.readConfigurations(url.getPath());
    plugin = spy(new NavigatorPlugin(config, mockFactory));
}