java boolean from php website - java

i want to create license system in java.
I created function to check if license is true.
My code:
private static boolean isPurchased(String license)
{
try
{
URL url = new URL("http://mineverse.pl/haslicense.php?license=" + license);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = in.readLine();
in.close();
return Boolean.valueOf(str);
} catch (Exception e)
{
e.printStackTrace();
}
return false;
}
and chceck function onenable
if(this.isPurchased(license)){
String license = cfg.getString("Licensing_System.License");
System.out.println("Licencja" + license + " kupiona! Dziekujemy!");
System.out.println(this.isPurchased(license));
}else {
System.out.println("Licencja zostala sfalszowana! Zglaszam to do serwera autoryzacji!");
}
And my link:
http://mineverse.pl/haslicense.php?license=diverse12345
as you can see this link return true, (i did echo 'true';) but java console always return false (i want true because website have true at this link) and it logs:
Licencja zostala sfalszowana! Zglaszam to do serwera autoryzacji!
Whats wrong? How can i return true on my website to allow java learn this boolean?>

That's because your server is not just returning True or False. It is returning this instead:
<html>
</html>
True
and your code is only reading the first line <html> and parsing it as a boolean, which results in false.
To fix it, either read the whole body looking for True/False or return just True/False on your body.
The following code should work with the current html even if it contains the <html> tags:
URL url = new URL("http://mineverse.pl/haslicense.php?license=" + license);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = null;
boolean ret = false;
while ((str = in.readLine()) != null) {
str = str.toLowerCase();
if (str.contains("true")) {
ret = true;
break;
}
}
in.close();
return ret;

I tried your link http://mineverse.pl/haslicense.php?license=diverse12345 and it returns this:
<html>
</html>
True
When you pass that to Boolean.valueOf(...), the result will be false. The method Boolean.valueOf(...) will only return true if the string you pass it consists of exactly four characters: true.
You need to get rid of the HTML tags, the spaces and newlines, and case is also important; True will not work, it must be true.

Related

How do I convert a condition written in string to a Java "if" condition

I have a UI where the user can build a query to then apply those conditions to search in a text file.
Let's assume the string is as follows: A and (B or C) I also have access to each value (A, B, C), logical operators (and, or) and grouping brackets.
So what I need to have is: line.contains(A) && (line.contains(B) || line.contains(C))
boolean found = false;
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = null;
while ((line = reader.readLine()) != null && !contains) {
if (line.contains(A) && (line.contains(B) || line.contains(C))) {
found = true;
}
}
return found;
The above specific conditions might also not work since I'm searching for that in each line and the conditions might be in different lines. But this is another issue I have to deal with :)
Any idea on how to do this?
Based on your comments I was able to resolve my question by using ScriptEngineManager. I'm building the condition I want to evaluate using JavaScript language and doing engine.eval(query).
private boolean containsSearchQuery(InputStream input, String searchQuery) {
boolean match = false;
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String lines = reader.lines().collect(Collectors.joining());
engine.put("lines", lines);
try {
match = (boolean) engine.eval(searchQuery);
} catch (ScriptException e) {
System.out.println("Error: " + e.getMessage());
}
return match;
}

always return false when compare an existing string from a test file to the newly enterer object with parameter

This is my method for checking if the first three elements are the same
carModel is a string
purchasePrice is a double
purchaseDate is a Date
I stored these in a txt file, separating with a comma and a space like ", "
However, this method always returns false,even if i input just the same record. But when I changed the first"&&" into "||", it would return true.
public static boolean exist(Car c) {
String line = "";
File file = new File("Car Records.txt");
try {
BufferedReader fr = new BufferedReader(new FileReader(file));
while ((line = fr.readLine()) != null) {
String[] s = line.split(", ");
if ((s[0].equals(c.carModel)) &&(s[1].equals(c.purchasePrice))&& (s[2].equals(c.purchaseDate))
&& (s[5].equals(false)) ){
return true;
}
}
fr.close();
} catch (IOException e) {
System.out.println("Error reading file");
}
return false;
}
s[0],s[1] and s[2] are Strings, so comparing them to double or to Date will never return true.
You'll have to parse the input Strings into the correct type before making the comparison.
You'll need something like this (I didn't fix the Date comparison, since I don't know how you represent the date in your input file):
if ((s[0].equals(c.carModel)) &&(Double.parseDouble(s[1])==c.purchasePrice)&& (s[2].equals(c.purchaseDate))
&& (s[5].equals("false")) ){
return true;
}

different results for same method call [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
i do have a class CheckPrograminstallation(which is part of a eclipse plugin), with a method check, which checks whether a program is installed. It return true when installed and false otherwise.
public class CheckPrograminstallation{
public static boolean check(String programname, String OsName)
throws Exception {
// Get installation path of programname
String foundpath = "";
String dirName = "";
String line;
String programpath = null;
Process process = null;
boolean IsInstalled = false;
if (OsName.equals("Windows")) {
try {
// get Windows Directory first
process = Runtime.getRuntime().exec("cmd /c echo %windir%");
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
// read from stream
if ((line = reader.readLine()) != null) {
foundpath = line.toString();
// cut off "\Windows" from the found path
int last = foundpath.lastIndexOf("\\");
dirName = foundpath.subSequence(0, last).toString();
process = null;
// get program installation path
process = Runtime.getRuntime().exec(
"cmd /c where /R " + dirName + " " + programname);
reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
if ((line = reader.readLine()) != null) {
programpath = line.toString();
System.out.println(programpath);
IsInstalled = true;
}
}
} catch (Exception e) {
DO SOMETHING);
}
}
When i call the method from a test class, it works.
But when i call the same method while running the Plugin:
...boolean isInstalledPscp;
boolean IsWindows;
...
if (IsWindows == true) {
// for Windows: check if pscp is installed
isInstalledPscp = CheckIfInstalled.check("pscp", "Windows");
if (isInstalledPscp == false) {
do something }
}
...it always returns false.
How can that be?
This has been driving me crazy for a whole day. Using .equals for String comparison, and still getting false as result. So this is not a string comparison problem IMHO.
Change your string comparison from:
if (OsName == "Windows") {
To:
if (OsName.equals("Windows")) {
Since your if doesn't succeed, it never goes into if and hence it returns your false.
You compare strings using the equals() method and not logical equals operator ==
I also recommend that you follow java naming conventions and use variables names starting with lower case letters such as osName instead of OsName.
Print out what are the paths that are returned inside your code (if any), I suspect that from within the plugin the runtime parameters are different.
Also maybe System.getEnv System.getProperties is a better way to find windows dir than starting a new process.

How to read url in correct format?

I am trying to read a url which is throwing a string. I am storing that string in some variable and trying to print that variable on my web page using jsp. When I print my string on my web page it is giving some junk characters. How can I get the original string?
Here is my jsp code:
Market.jsp
<%#page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
URL url;
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
List commodity1 = null;
List price1 = null;
int c, p = 0;
try {
// get URL content
String a = "http://122.160.81.37:8080/mandim/MarketWise?m=agra";
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
// sb.append(inputLine);
String s = inputLine.replace("|", "\n");
s = s.replace("~", " ");
StringTokenizer str = new StringTokenizer(s);
while (str.hasMoreTokens())
{
String mandi = str.nextElement().toString();
String price = str.nextElement().toString();
list1.add(mandi);
list2.add(price);
}
}
commodity1 = list1.subList(0, 10);
// commodity10=list1.subList(90,100);
price1 = list2.subList(0, 10);
int c1 = 0;
int p1 = 0;
for (c1 = 0, p1 = 0; c1 < commodity1.size() && p1 < price1.size(); c1++, p1++) {
String x = (String) commodity1.get(c1);
String y = (String) price1.get(p1);
out.println(x);
out.println(y);
}
br.close();
//System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
%>
</body>
</html>
I am getting the following output
धान 1325 चावल 2050 ज�वर 920 जौ 810 मकई 1280 गेहू� 1420 जो 1050 बेजर - जय 800 उड़द 3600
How can I achieve my desired goal?
Thanks in advance
I think it'a an encoding issue on your system. I don't know JSP enough to tell you what, but when running your code as a pure java application on linux and changing out.println(); into System.out.println(); I can see the output as expected. (side node: the product names are asian names, so don't be as surprised as I was. expected in this case means that the characters are the same as when I do a wget call to the URL).
This means: your code is fine: It loads what you want. The problem is the presentation. HTML pages have their own encoding. I guess JSP makes this transparently (-> here I need external input how to do this), but the result must have one of this three solutions:
your page has a western encoding, and is not able to support asian characters. In this case your strings need to be encoded like this: ℘ or ℘
your page is utf8 or unicode encoded and directly supports this characters
even on utf8 encoded pages you can use encodings like in the first example
Whatever you chose to use: your output must match the format. This also means that your code needs to know the selected character set. And I'm sure JSP does. If you want to use the default implemented encoding, you need to find a function for this. have a look to Escape all strings in JSP/Spring MVC. This cannot be too hard.
Only if you are really crazy but don't know how to do it, use something like this (it's a hack!) function to encode your string:
private String encode(String str) {
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray())
if (ch < 128)
sb.append(ch);
else {
sb.append("&#x");
String hx = Integer.toHexString(ch);
while (hx.length() < 4)
hx = "0" + hx;
sb.append(hx);
sb.append(";");
}
return sb.toString();
}

Java comparing lines in file with String

I'm experiencing an strange issue with a file in Java...
I want to compare every line of this file with a string (host variable), but (I don't know why), the while loop is always comparing the first line of the file and ignores the second line, the third...
Here's the code:
fr = new FileReader (file);
inf = new BufferedReader(fr);
String l;
while ((l=inf.readLine()) != null) {
if (host.contains(l))
return true;
else
return false;
}
Any help would be appreciated...
Two problems:
You are finding the line in the host name - that's like finding a haystack in a needle - reverse the test
No matter the result of the condition, you return after testing it just once, so only the first line is tested
Instead, try this:
String l;
while ((l=inf.readLine()) != null)
if (l.contains(host))
return true;
return false;
It should be host.equals(l), or possibly l.contains(host). It depends what you want to do.
It's only testing the first line in your file because of the if/else statement in the loop. Either branch results in a return thus stopping the rest of the file's contents from being processed.
Maybe you should return false only after you've reached the end of your file?
fr = new FileReader (file);
inf = new BufferedReader(fr);
String l;
while((l=inf.readLine())!=null){
if (host.contains(l))
return true;
}
return false;
Suppose you are looking for the host string in the file. You could possible do it like this.
public boolean contains(Reader in, String word) throws IOException {
BufferedReader inf = new BufferedReader(in);
String l;
boolean found = false;
while((l=inf.readLine())!=null){
if (l.contains(word)) {
found = true;
break;
}
}
return found;
}

Categories

Resources