I have a URI with path like this :
ftp://test:test#someftp/ready123/users/abc/#0#.
But the method getPath() on the URI returns this:
/ready123/users/abc/.
I need the whole path to be returned like this :
/ready123/users/abc/#0#
... So that I can change the working directory(CWD) to the folder #0#. The code is in a generic method and is jarred up which gets used by many other applications. So I have to be very careful when I make changes. I believe anything after # is considered as a fragment, but in this case it is actually the name of a folder.
How do I get the path /ready123/users/abc/#0# from the URI object ?
From the JavaDoc of URI class:
URI syntax and components At the highest level a URI reference
(hereinafter simply "URI") in string form has the syntax
[scheme:]scheme-specific-part[#fragment]
where square brackets [...] delineate optional components and the
characters : and # stand for themselves.
As such if you want to retrieve everything after the first # you need to use URI.getFragment()
You need to replace the hash character with %23
URI uir = new URI("ftp://test:test#someftp/ready123/users/abc/%230%23");
System.out.println(uir.getPath()); // returns '/ready123/users/abc/#0#'
Related
I have a URL and I want to print in my graphical user interface the ID value after the hashtag.
For example, we have www.site.com/index.php#hello and I want to print hello value on a label in my GUI.
How can I do this using Java in Netbeans?
Simple solution is getRef() in URL class:
URL url = new URL("http://www.anyhost.com/index.php#hello");
jLabel.setText(url.getRef());
EDIT: According to #Henry comment:
I would recommend to use the java.net.URI as it also deals with encoding. The Javadocs say: "Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL()."
and this comment:
Why not just doing uri.getFragment()
URI uri = new URI("http://www.anyhost.com/index.php#hello");
jLabel.setText(uri.getFragment());
Use the String.split() Method.
public static String getId(string url) {
return url.split("#")[1];
}
String.split() returns an array of Strings that are delimited, or "Split," by the value you pass to it, or in this case #.
Because you want only the string after the #, you can just use the second item in the array that it returns by adding [1] to the end of it.
For more on String.split() go to Tutorials Point.
By the way, the part of the URL you are referencing is the Element ID. It is used to jump to an Element on a webpage.
In my web application I'm trying to prevent users from inserting JavaScript in the freeText parameter when they're running a search.
To do this, I've written code in the header Velocity file to check whether the query string contains a parameter called freeText, and if so, use the replace method to replace the characters within the parameter value. However, when you load the page, it still displays the original query string - I'm unsure on how to replace the original query string with my new one which has the replaced characters.
This is my code:
#set($freeTextParameter = "$request.getParameter('freeText')")
freeTextParameter: $freeTextParameter
#if($freeTextParameter)
##Do the replacement:
#set($replacedQueryString = "$freeTextParameter.replace('confirm','replaced')")
replacedQueryString after doing the replace: $replacedQueryString
The query string now: $request.getQueryString()
The freeText parameter now: $request.getParameter('freeText')
#end
In the code above, the replacedQueryString variable has changed as expected (ie the replacement has been carried out as expected), but the $request.getQueryString() and $request.getParameter('freeText') are still the same as before, as if the replacement had never happened.
Seeing as there is a request.getParameter method which works fine for getting the parameters, I assumed there would be a request.setParameter method to do the same thing in reverse, but there isn't.
The Java String is an immutable object, which means that the replace() method will return an altered string, without changing the original one.
Since the parameters map given by the HttpServletRequest object cannot be modified, this approach doesn't work well if your templates rely on $request.getParameter('freeText').
Instead, if you rely on VelocityTools, then you can rather rely on $params.freeText in your templates. Then, you can tune your WEB-INF/tools.xml file to make this parameters map alterable:
<?xml version="1.0">
<tools>
<toolbox scope="request">
<tool key="params" readOnly="false"/>
...
</toolbox>
...
</tools>
(Version 2.0+ of the tools is required).
Then, in your header, you can do:
#set($params.freeText = params.freeText.replace('confirm','replaced'))
I managed to fix the issue myself - it turned out that there was another file (which gets called on every page) in which the $!request.getParameter('freeText')" variable is used. I have updated that file so that it uses the new $!replacedQueryString variable (ie the one with the JavaScript stripped out) instead of the existing "$!request.getParameter('freeText')" variable. This now prevents the JavaScript from being executed on every page.
So, this is the final working code in the header Velocity file:
#set($freeTextParameter = "$!m.request.httpRequest.getParameter('freeText')")
#if($freeTextParameter)
#set($replacedQueryString = "$freeTextParameter.replace('confirm','').replace('<','').replace('>','').replace('(','').replace(')','').replace(';','').replace('/','').replace('\"','').replace('&','').replace('+','').replace('script','').replace('prompt','').replace('*','').replace('.','')")
#end
I'm trying to make a filter that matches the following URL's:
/foo and /foo/*
So anything under /foo/ and also the base case /foo
I have this filter:
Spark.before("/foo/*", (request, response) -> {
String ticket = request.cookie("session");
if (ticket == null) {
Spark.halt(302);
}
});
But of course this does not execute when I enter to /foo
I tried with the following but with no luck:
/foo*
/foo.*
/foo/
Is there anyway to achieve this? Or maybe to use a list of URL? so that I can assign both url to the same filter.
And please don't say to store the function in a variable so that the I use it two times because I think that is not clean at all..
According to https://github.com/perwendel/spark/blob/1ecd428c8e2e5b0d1b8f221e9bf9e82429bd73bb/src/main/java/spark/route/RouteEntry.java#L31 (where the path matching takes place), it does not look like what you want to do is possible.
The RouteEntry code splits the given pattern, and the given url at the '/' character, and then looks for "matches" (equality or wildcard) for each of the components.
Here's a more detailed explanation:
The url /foo/blah has 2 parts (in the terminology of RouteEntry code linked to above), while /foo has 1 part. For a pattern to match the first, it must have 2 parts : /foo/* is the only one that makes sense. But this pattern has 2 parts, which makes /foo fail the if checks on both lines 49 and 78. The only special case is the hack on line 71, which should make the pattern /foo/* match the url /foo/, but not /foo.
I am developing an application a where user need to supply local file location or remote file location. I have to do some validation on this file location.
Below is the requirement to validate the file location.
Path doesn't contain special characters * | " < > ?.
And path like "c:" is also not valid.
Paths like
c:\,
c:\newfolder,
\\casdfhn\share
are valid while
c:
non,
\\casfdhn
are not.
I have implemented the code based on this requirement:
String FILE_LOCATION_PATTERN = "^(?:[\\w]\\:(\\[a-z_\\-\\s0-9\\.]+)*)";
String REMOTE_LOCATION_PATTERN = "\\\\[a-z_\\-\\s0-9\\.]+(\\[a-z_\\-\\s0-9\\.]+)+";
Pattern locationPattern = Pattern.compile(FILE_LOCATION_PATTERN);
Matcher locationMatcher = locationPattern.matcher(iAddress);
if (locationMatcher.matches()) {
return true;
}
locationPattern = Pattern.compile(REMOTE_LOCATION_PATTERN);
locationMatcher = locationPattern.matcher(iAddress);
return locationMatcher.matches();
Test:
worklocation' pass
'C:\dsrasr' didnt pass (but should pass)
'C:\saefase\are' didnt pass (but should pass)
'\\asfd\sadfasf' didnt pass (but should pass)
'\\asfdas' didnt pass (but should not pass)
'\\' didnt pass (but should not pass)
'C:' passed infact should not pass
I tried many regular expression but didn't satisfy the requirement. I am looking for help for this requirement.
The following should work:
([A-Z|a-z]:\\[^*|"<>?\n]*)|(\\\\.*?\\.*)
The lines highlighted in green and red are those that passed. The non-highlighted lines failed.
Bear in mind the regex above is not escaped for java
from your restrictions this seems very simple.
^(C:)?(\\[^\\"|^<>?\\s]*)+$
Starts with C:\ or slash ^(C:)?\\
and can have anything other than those special characters for the rest ([^\\"|^<>?\\s\\\])*
and matches the whole path $
Edit: seems C:/ and / were just examples. to allow anything/anything use this:
^([^\\"|^<>?\\s])*(\\[^\\"|^<>?\\s\\\]*)+$
I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input:
http://google.com/resource?key=value1 & value2
I expect the output:
http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2
Neither java.net.URLEncoder nor java.net.URI will generate the right output. URLEncoder is meant for HTML form encoding which is not the same as RFC 2396. URI has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key.
Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc
Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.
You could also use Spring's UriUtils
I don't have enough reputation to comment on answers, but I just wanted to note that downloading the JSR-311 api by itself will not work. You need to download the reference implementation (jersey).
Only downloading the api from the JSR page will give you a ClassNotFoundException when the api tries to look for an implementation at runtime.
I wrote my own, it's short, super simple, and you can copy it if you like:
http://www.dmurph.com/2011/01/java-uri-encoder/
It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.
I think that the URI class is the one that you are looking for.
Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.
You said:
For example, given an input:
http://google.com/resource?key=value
I expect the output:
http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue
So:
C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;
public class URLEncodeSample {
public static void main( String [] args ) throws Throwable {
System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
}
}
C:\oreyes\samples\java\URL>javac URLEncodeSample.java
C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue
As expected.
What would be the problem with this?