Enum toString sometimes replacing i with ı - java

I recently got a report that a few Google Analytics event category names were being recorded with an i character with out a dot on top.
Pageviews and events occurring twice, once without dots over the i.
I had to look to believe it. Sure enough, I had an event called favorite and there was a handful called favorıte. Copy and paste that weird character into a terminal or a monospace font just to see how weird it is. favorıte
My first suspicion is my code where I generate the strings for the category names using toString on an enum.
public enum AnalyticsEvent {
SCREEN_VIEW,
FAVORITE,
UN_FAVORITE,
CLICK_EVENT,
... reduced for brevity;
public String val() {
return this.toString().toLowerCase();
}
}
Example of how that enum is used:
#Override
public void logSearchTag(String type, String value) {
...
logGAEvent(AnalyticsEvent.SEARCH_TAG.val(), type, value);
}
private void logGAEvent(String category, String action, String label) {
... // mGATracker = instance of com.google.android.gms.analytics.Tracker;
mGATracker.send(addCustomDimensions(new HitBuilders.EventBuilder()
.setCategory(category)
.setAction(action)
.setLabel(label))
.build());
...
}
I am going to solve this by actually assigning a string to the enums and instead return that in the val() function.
Though, I am curious if anyone knows why on a small handful of devices Enum.toString returns the enum name with that weird character replacing the i. I mean small. 8 out 50,000 is the average. Or is it possible that assumption is wrong and the error is on analytics service end somewhere? Really highly doubt that.

The String#toLowerCase method uses the default locale of the system. This use locale specific characters such as ı instead of i. In order to fix this problem call toLowerCase with a locale:
String test = "testString";
test.toLowerCase(java.util.Locale.ENGLISH) // Or your preferred locale

Related

JAVA How to retrieve text content from custom JLabel without the HTML taggings?

How do I retrieve the text from JLabel without the HTML taggings?
E.g.
CustomJLabel:
public CustomJLabel extends JLabel(){
private String text;
public CustomJLabel(String text) {
super("<html><div style='text-align: center;'>"+text+"</div></html>"),
this.text=text;
}
}
Main method:
testCustomLbl = new CustomJLabel("Testing");
System.out.println(testCustomLbl.getText());
Output I got:
<html><div style='text-align: center;'>Testing</div></html>
Desired output:
Testing
There are three options:
You pick your favorite HTML parser and parse HTML; see here for some inspiration. This is by far the most robust and straight forward solution; but of course: costly.
If you are well aware of the exact HTML content that goes into your labels, then you could turn to regular expressions; or other means of string parsing. The problem is: if you don't control those strings, then coming up with your own custom "parsing" is hard. Because each and any change somewhere to the HTML that goes in ... might break your little parser.
You rework your whole design: if having HTML text is such a core thing in your application, you might consider to really "represent" that in your class. For example by creating your own versions of JLabels that take some HtmlString input ... and simply remember which parts are HTML, and which one "pure text".
And whoops; the code you are showing is already suited for option 3. So if you want that getText() returns that original text, you could add a simple
#Override
public void String getText() {
return this.text;
}
to your CustomLabel class.
Edit: alternatively, you could simply add a new method like
public void String getTextWithoutHtmlTags()
or something alike; as overriding that inherited method somehow changes the "contract" of that method. Which (depending on the context) might be ok, or not so ok.
There's no need for complex code or 3rd party JARS / Libraries.
Here's a simple solution using RegEx:
String htmlStr = "<html><h1>Heading</h1> ...... </html>";
String noHtmlStr = htmlStr.replaceAll("\\<.*?\\>", "");
Works great for me.
Hope this helps.

non-basic characters in java, how to handle the encoding correctly

when I am trying to call method with parameter using my Polish language f.e.
node.call("ąćęasdasdęczć")
I get these characters as input characters.
Ä?Ä?Ä?asdasdÄ?czÄ
I don't know where to set correct encoding in maven pom.xml? or in my IDE? I tried to change UTF-8 to ISO_8859-2 in my IDE setting, but it didn't work. I was searching similiar questions, but I didn't find the answer.
#Edit 1
Sample code:
public void findAndSendKeys(String vToSet , By vLocator){
WebElement element;
element = webDriverWait.until(ExpectedConditions.presenceOfElementLocated(vLocator));
element.sendKeys(vToSet);
}
By nameLoc = By.id("First_Name");
findAndSendKeys("ąćęasdasdęczć" , nameLoc );
Then in input field I got Ä?Ä?Ä?asdasdÄ?czÄ. Converting string to Basic Latin in my IDE helps, but It's not the solution that I needed.
I have also problems with fields in classes f.e. I have class in which I have to convert String to basic Latin
public class Contacts{
private static final By LOC_ADDRESS_BTN = By.xpath("//button[contains(#aria-label,'Wybór adresu')]");
// it doesn't work, I have to use basic latin and replace "ó" with "\u00f3" in my IDE
}
#Edit 2 - Changed encoding, but problem still exists
1:

how to fix a java.lang.NumberFormatException error where the desire input is string?

i'm using Jframe as my front-end for an inventory system i have developed. I'm getting a "java.lang.NumberFormatException: For input string:"6seater"" but the variable is declared as a string so i'm a bit confused as to why this error is coming up
private String Eng_num, Chasis_num, make, model, year_of_car,capacity,description;
private Integer status,Sup_id;
public void actionPerformed(ActionEvent e)
{
Insert I = new Insert();
try
{
Chasis_num = textField_1.getText();
Eng_num = textField_9.getText();
year_of_car = textField_10.getText();
model = textField_11.getText();
make = textField_12.getText();
capacity = textField_14.getText();//error is at this line
description = textField_16.getText();
Sup_id = Integer.parseInt(""+textField_13.getText().toString());
status = Integer.parseInt(""+textField_15.getText().toString());
I.insertVehicle(Eng_num, Chasis_num, make, model, year_of_car, capacity, Sup_id, status, description);
}
I even try to put .toString and still getting the same error
capacity = textField_14.getText();
I don't think this is the cause of your exception.
java.lang.NumberFormatExceptionOnly occur when you try to parse String into any kind of Number.
So, i'm guessing, this exception was thrown somewhere you try to convert 6seater to Int or some other number format.
I'm getting a "java.lang.NumberFormatException: For input string:"6seater"" but the variable is declared as a string so i'm a bit confused as to why this error is coming up.
The error is happening because you have tried to parse the characters 6seater as an integer. It isn't an integer. An integer consists of the characters 0 through 9, possibly with a - character at the front. Any other character, and the value will be rejected ...
(The problem is nothing to do with the type that getText() returns. The problem is the value that you are giving to the parseInt method. It is not clear where the parseInt call is. A stacktrace would answer that ... but you didn't provide one.)
Also, you say:
capacity = textField_14.getText();//error is at this line
Actually, it isn't. That line cannot possibly throw a NumberFormatException. In reality, the error could be happening at one of these lines:
Sup_id = Integer.parseInt(""+textField_13.getText().toString());
status = Integer.parseInt(""+textField_15.getText().toString());
or it could be happening within the the insertVehicle method that you are calling here:
I.insertVehicle(Eng_num, Chasis_num, make, model,
year_of_car, capacity, Sup_id, status, description);
I should also point out that you have made some egregious Java style errors in your code:
Java class, method or variable names should never contain _ as a separator. Use "camel case".
A Java variable name should never start with an uppercase letter.
(If you instructor doesn't deduct "style" marks for this, he/she should. If your code reviewers don't pick this up, they are not doing their job properly. If this code was intended to be delivered to a paying customer, they would have reason to complain about the code quality ...)

How to get iso2code from a country name by locale

I have a form that user enter a country name, then I have to convert it to iso2 or iso3 code.
How is it possible? I prefer not to use map, as it seems not running on my Android app.
This code is for converthing iso2 to an actual name, I want the other way around:
Locale l = new Locale("", "CH");
System.out.println(l.getDisplayCountry());
Have you tried Locale.getISO3Country() ?
To actually do the conversion, you might need to loop through all the available locales and look for the one whose getDisplayCountry() matches your input country name.
It doesn't sound efficient (but you said to not use maps), but you might try something like:
Locale convertCountryNameToIsoCode(String countryName)
for(Locale l : Locale.getAvailableLocales()) {
if (l.getDisplayCountry().equals(countryName)) {
return l;
}
}
return null;
}
http://docs.oracle.com/javase/7/docs/api/java/util/Locale.html#getISO3Country()
However, if the input comes from a web form, than it would be easier to set the country code directly as the web form input value. If the input comes from an Android native App, then I'm not sure but I'd bet you might a similar thing

Python 3.x: Java valueOf() equivalent in Python 3.x

Whilest learning Python 3 and converting some of my code from Java to Python 3.3 I came across a small problem I haven't been able to fix.
In Java I have this code (just dummy code to make it smaller):
public enum Mapping {
C11{public int getMapping(){ return 1;}},
C12{public int getMapping(){ return 2;}},
public abstract int getMapping();
}
String s = "C11";
System.out.println(Mapping.valueOf(s))
Works fine and prints the requisted '1'
Trying to do this in Python doesn't work that easy (yet). I tried to imitate an Enum with:
class Mapping:
C11=1
C12=2
s = 'C11'
print(Mapping.Mapping.(magic should happen here).s)
Unfortunately I have no idea how to convert a string to an attribute to be called like that (or something similar).
I need this because I have a HUGE list in the class Mapping and need to convert seemingly random words read from a text file to an integer mapping.
You are looking for getattr:
>>> getattr(Mapping, s)
1
From the documentation:
getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
Use getattr:
class Mapping:
C11=1
C12=2
print(getattr(Mapping, 'C11')) # prints 1

Categories

Resources