Compare two strings like url in android - java

I have two strings:
http://porter.com/request/.*
and
http://porter.com/request/tokenId
I want to check if first parts: http://porter.com/request are the same in both and check if tokenId is not null, because in some cases it could be only http://porter.com/request/.
I use something like that:
override fun validate(pair: Pair<URI, URI>): Boolean {
val uri = pair.first.path.split("/").dropLast(1).filter { it.isNotBlank() }.joinToString("")
val uriIntent = pair.second.path.split("/").dropLast(1).filter { it.isNotBlank() }.joinToString("")
val asd = pair.second.path.split("/").filter { it.isNotBlank() }.last().isNotBlank()
return uri == uriIntent && asd
}
but this is not working for last case: http://porter.com/request/
Any ideas?

final String regex = "(http://porter.com/request/).+";
/**
* Below code will return false
* since, URL doesn't have last path
*/
final String yourUrl = "http://porter.com/request/.*";
final boolean valid = yourUrl.matches(regex)
/**
* Same (will return false), as ex. above
*/
final String yourUrl = "http://porter.com/request/*";
final boolean valid = yourUrl.matches(regex)
/**
* This will return true. Link is Ok.
*/
final String yourUrl = "http://porter.com/request/tokenId";
final boolean valid = yourUrl.matches(regex)

Related

Unit Tests for spring boot application

I have never used JUnit testing before.I need to test my code with JUnit.
I have been searching google for all day but the problem is that I found examples using Mockito but in my code I didn't use dependency injections(#Autowired).
How can i use it for these methods?
Thanks in advance.
public class WordService {
public WordService() {
}
public static String upperCaseFirst(String value) {
char[] listChar = value.toCharArray();
listChar[0] = Character.toUpperCase(listChar[0]);
return new String(listChar);
}
/**
* Find and return the search word
* #param name
* #return the word sought or null if not found
*/
public Word findWordByName(String name){
String nameUpper = upperCaseFirst(name);
WordDao w = new WordDao();
Word found = w.findWord(nameUpper);
List<String> definitions = new ArrayList<>();
if(found != null) {
for(int i=0; i<found.getDefinition().size(); i++) {
StringBuffer defBuffer = new StringBuffer();
String definitionFound = found.getDefinition().get(i);
definitionFound = definitionFound.replace("\n", "");
defBuffer.append(definitionFound);
defBuffer.append("_");
definitions.add(i, defBuffer.toString());
}
found.setDefinition(definitions);
}
return found;
}
/**
*
* #return Return a list of words
*/
public List<Word> findAllWord(){
WordDao w = new WordDao();
return w.findAllWords();
}
}
You can extract WordDao to class level as a field. Create set method.
After that in unit test you can mock WordDao and control what will be result of methods call. For the second method it something like:
WordDao wMocked = Mock(WordDao.class)
Word word1 = new...
Word word2 = new...
List<Word> words = List.of(word1, word2);
when(w.findAllWords()).thenReturn(words);
WordService ws = new WordService();
ws.setWordDao(wMocked);
Assert.equals(words, ws.findAllWords);

convert & delimited String to a java class

Is there a method can convert & delimited String to a java class?
Foo foo = Foo.fromString("name1=a&name2=b");
I am coding the twitter api: https://developer.twitter.com/en/docs/basics/authentication/api-reference/access_token. the response is
I need need a function do the blow things for me.
String respnse = "oauth_token=6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY&oauth_token_secret=2EEfA6BG3ly3sR3RjE0IBSnlQu4ZrUzPiYKmrkVU&user_id=6253282&screen_name=twitterapi";
String [] resParas = respnse.split("&");
for(String respara : resParas){
if(respara.indexOf("oauth_token=")>=0){
int index = "oauth_token=".length();
access_token = respara.substring(index);
}else if(respara.indexOf("oauth_token_secret=")>=0){
int index = "oauth_token_secret=".length();
access_token_secret = respara.substring(index);
}else if(respara.indexOf("user_id=")>=0){
int index = "user_id=".length();
user_id = respara.substring(index);
}else if(respara.indexOf("screen_name=")>=0){
int index = "screen_name=".length();
screen_name = respara.substring(index);
}
}
You can use UriComponentsBuilder for this:
MultiValueMap<String, String> parameters = UriComponentsBuilder
.fromUriString("http://twitter.com/oauth?oauth_token=6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY&oauth_token_secret=2EEfA6BG3ly3sR3RjE0IBSnlQu4ZrUzPiYKmrkVU&user_id=6253282&screen_name=twitterapi")
.build()
.getQueryParams();
Will give you a map with all params:
{oauth_token=[6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY], oauth_token_secret=[2EEfA6BG3ly3sR3RjE0IBSnlQu4ZrUzPiYKmrkVU], user_id=[6253282], screen_name=[twitterapi]}

Java: How to write a generalized function for this?

How to a write a single generalized for these? I mean the function should take parameters and return the desired string.
String fullName = driver.findElement(By.className("full-name")).getText();
String title = driver.findElement(By.className("title")).getText();
String locality = driver.findElement(By.className("locality")).getText();
String industry = driver.findElement(By.className("industry")).getText();
String connections = driver.findElement(By.xpath("//div[#class='member-connections']/strong")).getText();
String profileLink = driver.findElement(By.className("view-public-profile")).getText();
The function should be something like this:
String getInfo(String className, String byType) {
return driver.findElement(By.byType(className)).getText();
}
EDIT:
I have written this function, but I am not sure how to append byType with By.
static String getInfo(WebDriver driver, String byType, String byParam) {
return driver.findElement(By. + byType + (byParam)).getText();
}
Thanks!
This seems way easier than others are answering so I'm going to put my neck on the line. and say, what's wrong with this...
public String get(WebDriver driver, By by) {
return driver.findElement(by).getText();
}
..and using it like...
String a = get(urDriver, By.className(someName));
String b = get(urDriver, By.xpath(somePath));
You may try this:
public String byXpath(String xpath) {
return driver.findElement(By.xpath(xpath)).getText();
}
public String byClass(String $class) {
return driver.findElement(By.className($class)).getText();
}
Edited:
public String by(By by) {
return driver.findElement(by).getText();
}
String x = by(By.className(name));
String y = by(By.xpath(path));

Get string between an symbol

I am extracting a youtube video id from a youtube link. the list looks like this
http://www.youtube.com/watch?v=mmmc&feature=plcp
I want to get the mmmc only.
i used .replaceAll ?
Three ways:
Url parsing:
http://download.oracle.com/javase/6/docs/api/java/net/URL.html
URL url = new URL("http://www.youtube.com/watch?v=mmmc&feature=plcp");
url.getQuery(); // return query string.
Regular Expression
Examples here http://www.vogella.com/articles/JavaRegularExpressions/article.html
Tokenize
String s = "http://www.youtube.com/watch?v=mmmc&feature=plcp";
String arr[] = s.split("=");
String arr1[] = arr[1].split("&");
System.out.println(arr1[0]);
If you'd like to use regular expressions, this could be a solution:
Pattern p = Pattern
.compile("http://www.youtube.com/watch\\?v=([\\s\\S]*?)\\&feature=plcp");
Matcher m = p.matcher(youtubeLink);
if (m.find()) {
return m.group(1);
}
else{
throw new IllegalArgumentException("invalid youtube link");
}
Of course, this will only work if the feature will always be plcp, if not, you could simply remove that part or replace it with a wilcard as I did with mmmc
Edit: now i know what you are looking for i hope:
String url= "http://www.youtube.com/watch?v=mmmc&feature=plcp";
String search = "v=";
int index = url.indexOf(search);
int index2 = url.indexOf("&",index);
String found = url.substring(index+2,index2);
System.out.println(found);
Here's a generic solution (using Guava MapSplitter):
public final class UrlUtil {
/**
* Query string splitter.
*/
private static final MapSplitter PARAMS_SPLITTER = Splitter.on('&').withKeyValueSeparator("=");
/**
* Get param value in provided url for provided param.
*
* #param url Url to use
* #param param Param to use
* #return param value or null.
*/
public static String getParamVal(String url, String param)
{
if (url.contains("?")) {
final String query = url.substring(url.indexOf('?') + 1);
return PARAMS_SPLITTER.split(query).get(param);
}
return null;
}
public static void main(final String[] args)
{
final String url = "http://www.youtube.com/watch?v=mmmc&feature=plcp";
System.out.println(getParamVal(url, "v"));
System.out.println(getParamVal(url, "feature"));
}
}
Outputs:
mmmc
plcp

How to normalize a URL in Java?

URL normalization (or URL canonicalization) is the process by which URLs are modified and standardized in a consistent manner. The goal of the normalization process is to transform a URL into a normalized or canonical URL so it is possible to determine if two syntactically different URLs are equivalent.
Strategies include adding trailing slashes, https => http, etc. The Wikipedia page lists many.
Got a favorite method of doing this in Java? Perhaps a library (Nutch?), but I'm open. Smaller and fewer dependencies is better.
I'll handcode something for now and keep an eye on this question.
EDIT: I want to aggressively normalize to count URLs as the same if they refer to the same content. For example, I ignore the parameters utm_source, utm_medium, utm_campaign. For example, I ignore subdomain if the title is the same.
Have you taken a look at the URI class?
http://docs.oracle.com/javase/7/docs/api/java/net/URI.html#normalize()
I found this question last night, but there wasn't an answer I was looking for so I made my own. Here it is incase somebody in the future wants it:
/**
* - Covert the scheme and host to lowercase (done by java.net.URL)
* - Normalize the path (done by java.net.URI)
* - Add the port number.
* - Remove the fragment (the part after the #).
* - Remove trailing slash.
* - Sort the query string params.
* - Remove some query string params like "utm_*" and "*session*".
*/
public class NormalizeURL
{
public static String normalize(final String taintedURL) throws MalformedURLException
{
final URL url;
try
{
url = new URI(taintedURL).normalize().toURL();
}
catch (URISyntaxException e) {
throw new MalformedURLException(e.getMessage());
}
final String path = url.getPath().replace("/$", "");
final SortedMap<String, String> params = createParameterMap(url.getQuery());
final int port = url.getPort();
final String queryString;
if (params != null)
{
// Some params are only relevant for user tracking, so remove the most commons ones.
for (Iterator<String> i = params.keySet().iterator(); i.hasNext();)
{
final String key = i.next();
if (key.startsWith("utm_") || key.contains("session"))
{
i.remove();
}
}
queryString = "?" + canonicalize(params);
}
else
{
queryString = "";
}
return url.getProtocol() + "://" + url.getHost()
+ (port != -1 && port != 80 ? ":" + port : "")
+ path + queryString;
}
/**
* Takes a query string, separates the constituent name-value pairs, and
* stores them in a SortedMap ordered by lexicographical order.
* #return Null if there is no query string.
*/
private static SortedMap<String, String> createParameterMap(final String queryString)
{
if (queryString == null || queryString.isEmpty())
{
return null;
}
final String[] pairs = queryString.split("&");
final Map<String, String> params = new HashMap<String, String>(pairs.length);
for (final String pair : pairs)
{
if (pair.length() < 1)
{
continue;
}
String[] tokens = pair.split("=", 2);
for (int j = 0; j < tokens.length; j++)
{
try
{
tokens[j] = URLDecoder.decode(tokens[j], "UTF-8");
}
catch (UnsupportedEncodingException ex)
{
ex.printStackTrace();
}
}
switch (tokens.length)
{
case 1:
{
if (pair.charAt(0) == '=')
{
params.put("", tokens[0]);
}
else
{
params.put(tokens[0], "");
}
break;
}
case 2:
{
params.put(tokens[0], tokens[1]);
break;
}
}
}
return new TreeMap<String, String>(params);
}
/**
* Canonicalize the query string.
*
* #param sortedParamMap Parameter name-value pairs in lexicographical order.
* #return Canonical form of query string.
*/
private static String canonicalize(final SortedMap<String, String> sortedParamMap)
{
if (sortedParamMap == null || sortedParamMap.isEmpty())
{
return "";
}
final StringBuffer sb = new StringBuffer(350);
final Iterator<Map.Entry<String, String>> iter = sortedParamMap.entrySet().iterator();
while (iter.hasNext())
{
final Map.Entry<String, String> pair = iter.next();
sb.append(percentEncodeRfc3986(pair.getKey()));
sb.append('=');
sb.append(percentEncodeRfc3986(pair.getValue()));
if (iter.hasNext())
{
sb.append('&');
}
}
return sb.toString();
}
/**
* Percent-encode values according the RFC 3986. The built-in Java URLEncoder does not encode
* according to the RFC, so we make the extra replacements.
*
* #param string Decoded string.
* #return Encoded string per RFC 3986.
*/
private static String percentEncodeRfc3986(final String string)
{
try
{
return URLEncoder.encode(string, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
}
catch (UnsupportedEncodingException e)
{
return string;
}
}
}
Because you also want to identify URLs which refer to the same content, I found this paper from the WWW2007 pretty interesting: Do Not Crawl in the DUST: Different URLs with Similar Text. It provides you with a nice theoretical approach.
No, there is nothing in the standard libraries to do this. Canonicalization includes things like decoding unnecessarily encoded characters, converting hostnames to lowercase, etc.
e.g. http://ACME.com/./foo%26bar becomes:
http://acme.com/foo&bar
URI's normalize() does not do this.
The RL library:
https://github.com/backchatio/rl
goes quite a ways beyond java.net.URL.normalize().
It's in Scala, but I imagine it should be useable from Java.
You can do this with the Restlet framework using Reference.normalize(). You should also be able to remove the elements you don't need quite conveniently with this class.
In Java, normalize parts of a URL
Example of a URL: https://i0.wp.com:55/lplresearch.com/wp-content/feb.png?ssl=1&myvar=2#myfragment
protocol: https
domain name: i0.wp.com
subdomain: i0
port: 55
path: /lplresearch.com/wp-content/uploads/2019/01/feb.png?ssl=1
query: ?ssl=1"
parameters: &myvar=2
fragment: #myfragment
Code to do the URL parsing:
import java.util.*;
import java.util.regex.*;
public class regex {
public static String getProtocol(String the_url){
Pattern p = Pattern.compile("^(http|https|smtp|ftp|file|pop)://.*");
Matcher m = p.matcher(the_url);
return m.group(1);
}
public static String getParameters(String the_url){
Pattern p = Pattern.compile(".*(\\?[-a-zA-Z0-9_.#!$&''()*+,;=]+)(#.*)*$");
Matcher m = p.matcher(the_url);
return m.group(1);
}
public static String getFragment(String the_url){
Pattern p = Pattern.compile(".*(#.*)$");
Matcher m = p.matcher(the_url);
return m.group(1);
}
public static void main(String[] args){
String the_url =
"https://i0.wp.com:55/lplresearch.com/" +
"wp-content/feb.png?ssl=1&myvar=2#myfragment";
System.out.println(getProtocol(the_url));
System.out.println(getFragment(the_url));
System.out.println(getParameters(the_url));
}
}
Prints
https
#myfragment
?ssl=1&myvar=2
You can then push and pull on the parts of the URL until they are up to muster.
Im have a simple way to solve it. Here is my code
public static String normalizeURL(String oldLink)
{
int pos=oldLink.indexOf("://");
String newLink="http"+oldLink.substring(pos);
return newLink;
}

Categories

Resources