Malicious code vulnerability - Field should be package protected - java

Sonar is giving me the message:
Malicious code vulnerability - Field should be package protected for
static array FORMATS.
Why is this code considered malicious? I have a public class to store all the constants.
public class Constants
{
/*
all the public static final constants of primitive datatypes for which
there is no sonar warning.
*/
public static final String[] FORMATS = new String[] {
"yyyy-MM-dd HH:mm:ss.S z",
"yyyy-MM-dd HH:mm:ss.S"
}

Probably because another piece of code could execute:
Constants.FORMATS[0] = "SOME GARBAGE";
And break the rest of your code.
In other words your array is constant but not its content.
Examples of alternatives:
you can store each format as a separate String constant
you can use an immutable list instead: public static final List<String> FORMATS = Collections.unmodifiableList(Arrays.asList("yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S"));
make it a method:
public static String[] formats() {
return new String[] { "yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S" };
}
ignore the warning if you are confident that (i) only your own code will access that class and (ii) there is no way you/your colleagues would even think of reassigning one of the values.

Related

Sort Array object by date of its field

I have an Object MyTimes and in that object there are fields name ,start_date and configuration.
I have an array of this object, MyTimes [] mytimes
I am trying to sort the array by the start time but am struggling how to go about it.
The start_time field is a string, so this needs converting to a datetime.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
for(int i=0; i<mytimes.length; i++) {
Date date = formatter.parse(mytimes[i].getStartTime());
}
I'd then put the date into an array list perhaps and then sort by datetime? But then I wouldnt know which start_time corresponds with which mytimes object...
What is the most efficient way of doing this?
Under the right circumstances this is a one-liner:
Arrays.sort(myTimes, Comparator.comparing(MyTimes::getStartDate));
Let’s see it in action:
MyTimes[] myTimes = {
new MyTimes("Polly", "2019-03-06T17:00:00Z"),
new MyTimes("Margaret", "2019-03-08T09:00:00Z"),
new MyTimes("Jane", "2019-03-01T06:00:00Z")
};
Arrays.sort(myTimes, Comparator.comparing(MyTimes::getStartDate));
Arrays.stream(myTimes).forEach(System.out::println);
Output:
Jane 2019-03-01T06:00:00Z
Polly 2019-03-06T17:00:00Z
Margaret 2019-03-08T09:00:00Z
I am assuming that getStartDate returns an Instant or another type the natural order of which agrees with the chronological order you want. For example:
public class MyTimes {
private String name;
private Instant startDate;
// Constructor, getters, toString, etc.
}
If you are receiving your start dates as strings somehow, you may write a convenient constructor that accepts a string for start date. I am already using such a constructor in the above snippet. One possibility is having two constructors:
public MyTimes(String name, Instant startDate) {
this.name = name;
this.startDate = startDate;
}
public MyTimes(String name, String startDate) {
this(name, Instant.parse(startDate));
}
The Instant class is part of java.time, the modern Java date and time API.
I am exploiting the fact that your strings are in the ISO 8601 format for an instant, the format that Instant.parse accepts and parses.
Avoid SimpleDateFormat and Date
I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. There is also an error in your format pattern string for parsing: Z (pronounced “Zulu”) means UTC, and of you don’t parse it as such, you will get incorrect times (on most JVMs). Instant.parse efficiently avoids any problems here.
Don’t store date-tine as a string
It looks like you are are storing start time in a String field in your object? That would be poor modelling. Use a proper date-time type. Strings are for interfaces. Date-time classes like Instant offer much more functionality, for example define sort order.
You have two main approaches:
Make your class implement Comparable
Use a custom Comparator
Then, you can choose the field to compare from, and transform it.
IE (implementing comparable):
class Example implements Comparable<Example> {
private String stringDate;
public int compareTo(Example e) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date1 = formatter.parse(this.stringDate);
Date date2 = formatter.parse(e.stringDate);
return date1.getTime() - date2.getTime();
}
}
And then using Arrays.sort would use your custom comparison.
Let your class implement Comparable and implement compareTo using modern formatting and date classes. Note that LocalDateTime also implements Comparable so once the string has been parsed you let LocalDateTime do the comparison
public class MyTimes implements Comparable<MyTimes> {
private final DateTimeFormatter dtf = DateTimeFormatter.ISO_INSTANT;
//other code
public int compareTo(MyTimes o) {
LocalDateTime thisDate = LocalDateTime.from(dtf.parse(this.getStartTime()));
LocalDateTime otherDate = LocalDateTime.from(dtf.parse(o.getStartTime()));
return thisDate.compareTo(otherDate);
}
}
You can also create a separate class as a comparator if this comparison is special and what you not always want to use
public class MyTimesComparator implements Comparator<MyTimes> {
#Override
public int compare(MyTimes arg0, MyTimes arg1) {
DateTimeFormatter dtf = DateTimeFormatter.ISO_INSTANT;
LocalDateTime thisDate = LocalDateTime.from(dtf.parse(this.getStartTime()));
LocalDateTime otherDate = LocalDateTime.from(dtf.parse(o.getStartTime()));
return thisDate.compareTo(otherDate);
}
}
and then use it like
someList.sort(new MyTimesComparator());
or use an inline function (I am using Instant here)
someList.sort( (m1, m2) -> {
DateTimeFormatter dtf = DateTimeFormatter.ISO_INSTANT;
Instant instant1 = Instant.from(dtf.parse(m1.getStartTime));
Instant instant2 = Instant.from(dtf.parse(m2.getStartTime));
return intant1.compareTo(instant2);
});
I noticed now that you have an array and not a list so you need to convert to a list or use Arrays.sort instead.

Java 8 best way to parse text date to millisecond timestamp

I want to create a Java class with thread-safe static methods to parse dates. I understand that some of the Java 7 (and earlier) date time classes are not thread-safe. What is the best thread-safe implementation in Java 8 of this functionality:
String text = "5/16/2008";
long timestamp = DateUtil.getTimestamp(text);
In Java 7 and earlier, you would do this:
public class DateUtil {
public static long getTimestamp(String text) {
DateFormat df = new SimpleDateFormat("M/d/yyyy");
df.setTimeZone(TimeZone.getTimeZone("America/New_York"));
long timestamp = df.parse(text).getTime();
return timestamp;
}
}
But instead of creating a new instance of DateFormat for every call, I want to share a single static instance for all calls to this static getTimestamp method. My understanding is that this is not thread-safe.
One key requirement is that the text I want to parse has a short date like "5/16/2008" without HH:mm:ss resolution.
I also don't want to use a third party library like Joda-Time, but rather only standard Java 8 classes.
Here's a version of your code refactored to use the java.time.* package in Java 8. It uses a static final formatter instance, which is thread-safe and immutable, unlike java.text.SimpleDateFormat.
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class DateUtil {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
public static long getTimestamp(String text) {
LocalDate localDate = LocalDate.parse(text, formatter);
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()).getTime();
}
}
You can use joda-time lib. DateTime is immutable - and once created the values do not change, so class can safely be passed around and used in multiple threads without synchronization.
A companion mutable class to DateTime is MutableDateTime, of which the class can be modified and are not thread-safe.
DateTimeFormatter formatter = DateTimeFormat.forPattern("M/d/yyyy'T'HH:mm:ss.SSSZZ")
.withLocale(Locale.ROOT).withChronology(ISOChronology.getInstanceUTC());
DateTime dt = formatter.parseDateTime(text);
Reference of DateTimeFormatt: DatetimeFormat api.
As stated in ck1's answer, usage of java.time API is a better approach than the legacy classes. DateTimeFormatter is immutable and thread-safe, and using a static final instance of it will solve your problem.
The only part where I differ from that answer is in the code , where the Date class is used to get the time. I would like to take the java.time approach here as well. Below is my version :
public class DateUtil {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
public static long getTimestamp(String text) {
LocalDate localDate = LocalDate.parse(text, formatter);
return Instant.from(localDate.atStartOfDay(ZoneId.systemDefault())).toEpochMilli();
}
public static void main(String[] args) {
String text = "5/16/2008";
long timestamp = DateUtil.getTimestamp(text);
System.out.println(timestamp);
}
}

new DecimalFormat(pattern) vs decimalFormat.applyPattern(pattern)?

I was working with DecimalFormat today and found a method inside it applyPattern() so whenever I had to use DecimalFormat or SimpleDateFormat I used to assign them as under:
private static final DecimalFormat dFormat = new DecimalFormat(pattern);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
But now I applied another approach. Instead of creating multiple static final Decimal or Date formats I created just one variable for each of them. And then applied them on the fly as under:
private static final DecimalFormat dFormat = new DecimalFormat();
private static final SimpleDateFormat dateFormat = new SimpleDateFormat();
and whenever I need to apply a new pattern for any one of them I apply it like this:
dFormat.applyPattern(Constants.somePattern);
dFormat.format(SOMETHING);
So during a code review it was commented that this approach is not good for performance. But my point is that I am making my code more flexible as well as I am calling few new's so less objects are being created.
could someone throw some light on this point.

convert mutable variable to immutable in java with less pain

sometime i have no choice to use mutable variable instead of immutable variables i know how many ways can create immutable vars but i wonder this way also correct its really convert mutable to immutable and i dont use concurrency or multithreading in my code just Curious?
public class Config implements FindIt {
....
private final class DateHolder{
private final Date dateContainDateObject;
DateHolder(String date) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateContainDateObject = dateFormat.parse(date);
}
public Date getDate(){
return dateContainDateObject;
}
}
}
this is nested class and i use it like
private DateHolder holder;
and fill the holder variable in Config constructor class so holder variable are ThreadSafe ?
Date is a mutable object. Making it final means you can't change the reference to it, but you can still change what's at the reference (java.util.Date/Calendar nastiness strikes again, switch to the Java 8/Joda Time way if you can).
Don't expose any references to the Date member to the outside world. Instead make a defensive copy and pass that back instead. You might consider saving the time value as a final long instance member and only instantiating a Date when you need it.
can say is safe when you make class private and non-static, when you create form Config class you have only one DateHolder .
http://www.javapractices.com/topic/TopicAction.do?Id=29
why is static inner class singleton thread safe
http://www.javatpoint.com/how-to-create-immutable-class

A method to return 3 formats of data

I have Date in this format 2009-09-17T00:00:00.000-35:00 . As per the business Rules for my Application , i have written 3 Methods which will accept this Date and returns the Date in MM/yyyy , yyyyMM and dd .
For example one method is shown below MM/yyyy
private String getMonthYear(String date) throws Exception {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
String s1 = date;
String s2 = null;
Date d;
try {
d = sdf.parse(s1);
s2 = (new SimpleDateFormat("MM/yyyy")).format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return s2;
}
Similarly i have other two methods which will return data in yyyyMM and dd formats ??
This works fine , but does not look good
My question is can we have only one utility which satisfies my requirement ??
My question is can we have only one utility which satisfies my requirement ??
I think you're going about this the wrong way to start with. Fundamentally the data is just a date. You can apply formats later, when you need to. I suggest you start using Joda Time and make your method return a LocalDate. That captures all the real information, and you can then have three separate DateTimeFormatter objects used to format the value whenever you want.
Wherever you can, represent data using a type which most naturally represents the real information. Get your data into that natural format as early as possible, and keep it in that format until you have to convert it into something else (such as a string).
You could define a single method and receive as a parameter the string with the expected date format, the three strings with the formats could be defined as constants.
Yes, you could group the three methods together, and use an additional argument (an enum, for example) to specify which kind of output format you want. But I would not do that. Your solution is cleaner. Why do you think it doesn't look good?
What I would do, however, is transforming the String to a Date once and for all, and using a Date everywhere rather than the String, and transforming the Date with one of your 3 methods (which would take a Date as argument rather than a String) when needed.
The Apache Commons Lang library already has utility methods to do this for you.
For example:
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
///
// first, convert the string to a date object
Date parsedDate = DateUtils.parseDate("2012-05-25T16:10:30.000",
new String[] {"yyyy-MM-dd'T'HH:mm:ss.SSS"});
// now, format the date object to a string, using different formats
String formattedDate = DateFormatUtils.format(parsedDate, "MM/yyyy");
String formattedDate2 = DateFormatUtils.format(parsedDate, "yyyyMM");
Take a look at DateFormatUtils and DateUtils for more information.
You could just have a Date class which has the three methods. Like below:
public class MyDate {
private String date = null;
public MyDate(String date) {
this.date = date;
}
public String getMonthYear() {
return null;
}
public String getYearMonth() {
return null;
}
public String getDay() {
return null;
}
}
You can format the String into three different Strings in the constructor and just return those strings on method calls. That implementation would be good if you make numberous/repeated calls on the same date string. Or you could format the string in the method call, if you are doing it once but if you are doing it once you may want to make the class/methods static and get rid of the constructor.

Categories