How to calculate a new date? – Using one date variable and a int variable

Scenario

User can record their license using the application, they enter the day the license was redeemed and they also input the length of the license(days).

I am trying to figure out if you are able to calculate a new date from both these variables. for example

days = INPUT FROM USER;          days = 7;      
dateRedeemed = new Date();       date = 24/06/2019;      
newDate = dateRedeemed + days;   newDate = 01/07/2019;    
//Getting the values
            String name = txtName.getText();
            String contact = txtContact.getText();
            int years = Integer.parseInt(cboyears.getSelectedItem().toString());
            int months = Integer.parseInt(cboMonths.getSelectedItem().toString());
            int days = Integer.parseInt(cboDays.getSelectedItem().toString());


//Calculation            
            days = (years * 365) + (months * 12) + days;
            SimpleDateFormat format = new SimpleDateFormat("dd/MM/YYYY");
            Date dRedeemed = cboDate.getDate();
            String strRedeemed = format.format(dRedeemed);

If any one could help that would be great

Edit

Some great advice in this thread, Alot of you have been pointing out that the Date class in very bad and outdated i’m now going to start using the LocalDateTime Class as that seems more powerful, Another thing i would like to ask, is there a more efficient date picker. I have been using a swingx date picker is there a more effective choice?

Solution:

Java (any) solution:

Date currentDate = new Date(); // or any date you set
Calendar c = Calendar.getInstance();
c.setTime(currentDate);
c.add(Calendar.DAY_OF_MONTH, 7);
Date currentDatePlusSevenDays = c.getTime();

Java 8+ solution:

Date currentDate = new Date(); // or any date you set
LocalDateTime localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
localDateTime = localDateTime.plusDays(7);
Date currentDatePlusSevenDays = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

Java (any) solution with external library Joda-Time:

DateTime currentDate = DateTime.now(); // or any date you set
DateTime currentDatePlusSevenDays = currentDate.plusDays(7);   

Bouncycastle can't generate private key – Unknown KeySpec type: java.security.spec.X509EncodedKeySpec

I can’t generate private key with bouncycastle due to Unknown KeySpec type: java.security.spec.X509EncodedKeySpec. (However doing same for public key doesn’t throw exception and works – why?)

java.security.spec.InvalidKeySpecException: Unknown KeySpec type:
java.security.spec.X509EncodedKeySpec at
org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePrivate(Unknown
Source) at
java.security.KeyFactory.generatePrivate(KeyFactory.java:366)

        PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream("private_unencrypted.pem")));
        PemObject pemObject = pemReader.readPemObject();
        pemReader.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        byte[] privateKeyBytes = pemObject.getContent();
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(x509KeySpec);

Solution:

For RSA private keys you should be using PKCS8EncodedKeySpec if your key is encoded in PKCS8 format. PKCS8 format usually looks like :

-----BEGIN PRIVATE KEY-----
base64 encoded der key
-----END PRIVATE KEY-----

If your key is in PKCS1 format and looks like :

-----BEGIN RSA RIVATE KEY-----
base64 der encoded key
-----END RSA PRIVATE KEY-----

you should first convert it to PKCS8 format and then use the class mentioned above.

However doing same for public key doesn’t throw exception and works – why?

Because public keys, which are usually part of Certificates, are encoded in X509 format, however private keys are usually encoded in PKCS format.

Test void methods with Autowired classes

I am a begginer in Spring and I need to write test for this class if it calls methods:

class ClassOne {

    @Autowired
    AutowiredClass a1;

    @Autowired
    AutowiredClass a2;

    void methodOne() {
        a1.method1();    
    }

    void methodTwo() {
        a2.method2();
    }
}

I’ve tried to write test, but failed, got NPE:

class ClassOneTest {

    @Autowired
    ClassOneInterface c1i;

    @Test
    public void testMethod1() {
        c1i.methodOne();  // <- NPE appears here..
        Mockito.verify(ClassOne.class, Mockito.times(1));
    }
}

Halp..

Would be great to successfully test void methods.

Solution:

You can verify that using a unit test:

@RunWith(MockitoJUnitRunner.class)
public class MyLauncherTest {

    @InjectMocks
    private ClassOne c1 = new ClassOne();

    @Mock
    private AutowiredClass a1;

    @Mock
    private AutowiredClass a2;

    @Test
    public void methodOne() {
        c1.methodOne(); // call the not mocked method
        Mockito.verify(a1).method1(); //verify if the a1.method() is called inside the methodOne
    }
}

Android Studio Dialog Buttons out of Screen when using Wrap Content as LayoutParams

I Have a Dialog with a Custom layout in my layouts Folder, which Wraps its Content. If I pu tin a large Text into one of the TextFields, the Buttons on the Bottom dissapear. The Text itself is scrollable and everything else works just fine. I want the Buttons to stick to the Bottom of the Dialog and not disappear if the text is Too Large.
Dialog without TextInput, Dialog with large Text. Icannot post Pictures directly, therefore i just included Links.

I have already tried to change the Layout so the Buttons stick to the Bottom of the Layout instead of the TextView above them. Setting a fixed size isnt really an Option.

Layout of the Dialog Layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_layout_rounded_16">

    <EditText
        android:id="@+id/dialog_resource_title"
        style="@style/myEditTextStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:hint="@string/general_title_hint"
        android:inputType="textMultiLine"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/dialog_resource_description"
        style="@style/myEditTextStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="8dp"
        android:hint="@string/general_description_hint"
        android:inputType="textMultiLine"
        app:layout_constraintBottom_toTopOf="@+id/dialog_resource_cancel"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/dialog_resource_title" />

    <Button
        android:id="@+id/dialog_resource_cancel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="4dp"
        android:layout_marginBottom="8dp"
        android:paddingBottom="8dp"
        android:text="@string/general_cancel"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/dialog_resource_middle_line"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/dialog_resource_save"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:text="@string/general_save"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/dialog_resource_middle_line" />

    <android.support.constraint.Guideline
        android:id="@+id/dialog_resource_middle_line"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />

</android.support.constraint.ConstraintLayout>


Initialisation of the Dialog:



        resourceDialog = new Dialog(context);

        View v = LayoutInflater.from(context).inflate(R.layout.dialog_resource, null);

        this.resourceDialogTitle = v.findViewById(R.id.dialog_resource_title);
        this.resourceDialogDescription = v.findViewById(R.id.dialog_resource_description);
        this.resourceDialogCancel = v.findViewById(R.id.dialog_resource_cancel);
        this.resourceDialogSave = v.findViewById(R.id.dialog_resource_save);

        resourceDialog.setContentView(v);
        // Set Color of Root View (Otherwise white Background in the Corners)
        resourceDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        // Getting the Display Metrics to set Size of Dialog
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;

        // Setting the Size
        resourceDialog.getWindow().setLayout((width - 128), ViewGroup.LayoutParams.WRAP_CONTENT);

        resourceDialog.setCanceledOnTouchOutside(false);

Solution:

Put the buttons incide a linear layout and use a constraint option to constrain it to the bottom of the screen. For example

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerInParent="true"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent">

    <Button />

    <Button />
</LinearLayout>

–Edit–
I tried this and worked for me

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">


<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    android:fitsSystemWindows="true"
    android:paddingBottom="120dp"
    android:scrollbars="horizontal"
    app:layout_constraintTop_toBottomOf="@+id/appBarLayout">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/appBarLayout"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="14dp"
        android:layout_marginRight="10dp"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/address"
            android:textColor="@color/black_1"
            android:textSize="20sp"
            android:textStyle="bold" />


    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerInParent="true"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginRight="4dp"
        android:textColor="@android:color/white" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginLeft="4dp"
        android:textColor="@android:color/white" />
</LinearLayout>

</android.support.constraint.ConstraintLayout>

Will SharedPreferences "commit()" be automatically changed to "apply()" in Androids code optimization?

So, I’m facing this weird problem right now. I HAVE to use SharedPreferences.Editor().commit() in my Android app, but, as the documentation here states,

As SharedPreferences instances are singletons within a process, it’s
safe to replace any instance of commit() with apply() if you were
already ignoring the return value.

You don’t need to worry about Android component lifecycles and their
interaction with apply() writing to disk. The framework makes sure
in-flight disk writes from apply() complete before switching states.

Basically it is safe to replace commit() with apply() if you’re not using the return value, BUT, the difference between two as mentioned here, and as warning in Android Studio states, is that commit() immediately writes the data, BUT apply() does that asynchronously.

So my problem here is, I’m changing the language in my app, and I want to restart my app after user chooses the language. But, when user chooses the language, the current chosen language is put in SharedPreferences.

Now, the problem:

Whenever I use apply() instead of commit() and restart my app using the code to restart the app here, the changes are not written on the disk, as, when the app restarts, it does not change the current language, as the value from SharedPreference is not changed, because it is not immediately written on the disk. But, whenever I use commit(), the changes are immediately written, and the language is successfully changed when the app is restarted.

So, the questions:

  1. How can people who wrote the code for commit() and apply() say that it is completely safe to use apply() instead of commit(), if there’s very big difference, as commit() writes the data immediately, but apply() does it in background?

  2. If I build my apk, will the commit() be replaced by apply() in code optimization if I’m not using the return value.(I know I can know this by building the release version of the app, but I still won’t be sure, because when I use apply(), it veeery frequently 1/10 times actually does change the value from SharedPreference)

A note:

  1. I know how I can use Apply() and still make my app work, maybe I’ll have to add some delay before restarting the app? But I’m not sure how it’ll work as it’ll still take some time to actually write the data on disk, and I don’t currently see any method to check if the SharedPreference value was actually changed, so that I can safely restart AFTER the value was changed.

Solution:

The problem is, that with Runtime.getRuntime().exit(0) or System.exit(0) you’ll kill the process and therefore no scheduled async task will execute after.

If you don’t intend to change your restart code, you should keep commit instead of apply for this instance and suppress the warning.

  1. It’s safe to assume that the statement is valid, because calling exit(0) is an edge-case you should not do normally.
  2. There’s no reason to assume that commit will be replaced with apply automatically. If you want to make sure of it, just use the return value.

How Java BigInteger nextProbablePrime method works?

I’m working with Java BigInteger Class and curious about the Algorithm behind nextProbablePrime method. I know about some efficient primality testing algorithm like Miller-Rabin but not sure about which algorithm was implemented here.

Trying the following code for a good time and still no response.

BigInteger number = BigInteger.ZERO;
number = number.setBit(82589933);
number = number.nextProbablePrime();

Solution:

I have gone through with the source code of BigInteger. It is internally using the MillerRabin algorithm for the nextProbablePrime method.

Using Streams filter Map based on a list of keys

I have a particular problem and was wondering whether the Java 8 Streams API could solve it. I know that this can be done outside of using Streams API but I don’t want to add all the boilerplate code associated with trying to achieve that, if it can be done using Streams. I have a map

Map<String, String> greetings = new HashMap<>();
greetings.put("abc", "Hello");
greetings.put("def", "Goodbye");
greetings.put("ghi", "Ciao");
greetings.put("xyz", "Bonsoir");

and a list of keys:

List<String> keys = Arrays.asList("def", "zxy");

and using the above with Streams API, is it possible to filter that down to:

Map<String, String> filteredGreetings = new HashMap<>();
filteredGreetings.put("def", "Goodbye");
filteredGreetings.put("xyz", "Bonsoir");

Hopefully this makes sense what I am trying to achieve.

So far I have got this to work only when specifying the exact key which to filter the map’s keySet on, but then this would only return a single entry set. I am interested in a completely filtered down map and I am struggling to achieve that.

Solution:

Try this:

Map<String, String> result = keys.stream()
        .filter(greetings::containsKey)
        .collect(Collectors.toMap(Function.identity(), greetings::get));

Or the other way round:

Map<String, String> result = greetings.entrySet().stream()
        .filter(e -> keys.contains(e.getKey()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

For the second approach I would recommend using a Set<String> for a larger list of keys because it has a O(1) time complexity for .contains() because it does not contain any duplicates:

Set<String> keys = new HashSet<>(Arrays.asList("def", "zxy"));

Split string only if BOTH the negative lookahead and negative lookbehind are statisfied

Hello i came along this question where the author wanted to convert the String:

exampleString =  "2 Marine Cargo       14,642 10,528  Denver Factory North     16,016 more text 8,609 argA 2,106 argB"

into an array / list that looks similar to this:

String[] resultArray = {"2", "Marine Cargo", "14,642", "10,528", "Denver Factory North", "16,016",
                "more text", "8,609", "argA", "2,106", "argB"};

So numeric parts (with or without a comma) are considered an element
and pure alpha sequences (divided by none, one or multiple spaces) are considered an element.

This can be done by matching the groups
or by splitting on the spaces where both the previous and the next part of the string is no alpha sequence. I am curious if the latter is possible.
I think part should be done with a negative look ahead:

\s+(?![A-Za-z]+)

and part with a negative look behind.

(?<![a-zA-Z])\s+

I am looking to combine both statements in such a way that it only does not match if both the parts before and after the sequence of spaces are alpha, so you can chain multiple words together without splitting in between. I found another question on this topic but i am not able to reverse engineer it for this particular case. Is this possible?

Solution:

You may use

String[] results = exampleString.split("(?<=\\d)\\s+(?=[a-zA-Z])|(?<=[a-zA-Z])\\s+(?=\\d)|(?<=\\d)\\s+(?=\\d)");

See the regex demo

Details

  • (?<=\d)\s+(?=[a-zA-Z]) – 1+ whitespaces that have a digit on the left and a letter on the right
  • | – or
  • (?<=[a-zA-Z])\s+(?=\d) – 1+ whitespaces that have a letter on the left and a digit on the right
  • | – or
  • (?<=\d)\s+(?=\d) – 1+ whitespaces that have a digit on the left and a digit on the right.

Java demo:

String exampleString =  "2 Marine Cargo       14,642 10,528  Denver Factory North     16,016 more text 8,609 argA 2,106 argB";
String results[] = exampleString.split("(?<=\\d)\\s+(?=[a-zA-Z])|(?<=[a-zA-Z])\\s+(?=\\d)|(?<=\\d)\\s+(?=\\d)");
for (String s: results) {
    System.out.println(s);
}

Output:

2
Marine Cargo
14,642
10,528
Denver Factory North
16,016
more text
8,609
argA
2,106
argB

Why is necessary to first catch ArrayIndexOutOfBoundsException and then IndexOutOfBoundsException?

Let’s take as reference the next code:

try{
   /*Code that may throw IndexOutOfBoundsException or ArrayIndexOut......*/
} catch (IndexOutOfBoundsException e){
    /*handle*/
} catch (ArrayIndexOutOfBoundsException e){
    /*handle*/
}
  • Why doesn’t this compile, but if a switch the sequence of catch clauses it does compile?

  • Maybe I must first write a specific exception and then a more general?

Solution:

Because ArrayIndexOutOfBoundsException extends from IndexOutOfBoundsException, which means the first one is more specific than the second one.

So if there is an ArrayIndexOutOfBoundsException it is matched to an IndexOutOfBoundsException: in other words, the catch for ArrayIndexOutOfBoundsException would be unreachable.

For all exceptions declared in your catches to be reachable, you need to order them from the most specific to the most generic ones.

GWT CellTable: Selecting one checkbox selects every checkbox/row in the table

I have a very basic CellTable in GWT right now and use a majority of the code shown here.

However when I toggle a checkbox, every single row gets highlighted.

Preview: gfycat

I did try so far:

  • Multi-/SingleSelectionMode: (I only want to get one row, so I would prefer SingleSelectionMode)

  • CheckBoxCell(true, true): -> This is exactly how I want the CellTable to look, however with these parameters I can’t get an object with “getSelectedObject()”. Other variations of the parameters(false,false/true, false) also didn’t seem to work

    CellTable<Article> ArticleCt = new CellTable<Article>(KEY_PROVIDER); 

    ListHandler<Article> sortHandler = new ListHandler<Article>(Articles);
    ArticleCt.addColumnSortHandler(sortHandler);

    final MultiSelectionModel<Article> selectionModel1 = new MultiSelectionModel<Article>(KEY_PROVIDER);

    ArticleCt.setSelectionModel(selectionModel1, DefaultSelectionEventManager.<Article> createCheckboxManager());

    Column<Article, Boolean> checkColumn = new Column<Article, Boolean>(
                  new CheckboxCell(true, false)) {

      public Boolean getValue(Article object) {

      return selectionModel1.isSelected(object);
    }
    };

I want to have only the row with the checked checkbox selected so I can fetch the peticular row/object with selectionMode.getSelectedObject() or selectionMode.getSelectedSet().

However every single row gets highlighted.

Solution:

Your key provider, KEY_PROVIDER in the question above, must provide unique and consistent keys per row. For example, each row might have an “ID” field.

If more than one row shares a key, then selecting one seems to be the same to the selection model as selecting both. If a row’s key is not consistent, then when a row is selected, it can’t be queried later since its key changed.