Tar archiving in java code

I am using a tar library

https://github.com/kamranzafar/jtar/tree/master/src/main/java/org/kamranzafar/jtar

to archive my files ,but i am not compressing the files
so when i extract the file like of 500mb it takes time to extract is there a way to reduce processing time

String tarFile = "c:/test/test.tar";
  String destFolder = "c:/test/myfiles";

  // Create a TarInputStream
  TarInputStream tis = new TarInputStream(new BufferedInputStream(new FileInputStream(tarFile)));
  TarEntry entry;

  while((entry = tis.getNextEntry()) != null) {
     int count;
     byte data[] = new byte[2048];
     FileOutputStream fos = new FileOutputStream(destFolder + "/" + entry.getName());
     BufferedOutputStream dest = new BufferedOutputStream(fos);

     while((count = tis.read(data)) != -1) {
        dest.write(data, 0, count);
     }

     dest.flush();
     dest.close();
  }
  tis.close()

Java: if .nextline is an integer, return an error

I’m using the scanner class to get user input for a ‘dogs breed’. However, I would like to add a custom error message if the user enters anything else but a string.
Code is below,

void dostuff() {
    Scanner reader = new Scanner(System.in);
    System.out.println("Enter the Dogs Name:");
    name = reader.nextLine();
    if(name.equals("Bob")){
        System.out.println("Your Bob");
    }
    System.out.println("Enter the Dogs Age:");
    age = reader.nextInt();
    System.out.println("Enter the Dogs Breed:");
    breed = reader.nextLine();
            System.out.println("Your Dogs name is: " + name);
            System.out.println("Your Dogs age is: " + age);
            System.out.println("Your Dogs breed is: " + breed);
}

ScreenShot of the Root Layout i.e Scroll View

I am developing a GPA Calculator application. For that purpose, I want to install some features related to capturing the screenshot of the final activity where the user will see the subjects and their marks and GPA etc.
My root view is ScrollView Layout (all the contents i.e subjects their marks) and wants to capture it.
I tried the following code but the code works fine only for the single view

 Bitmap bitmap = Bitmap.createBitmap(text1.getWidth() , text1.getHeight() , Bitmap.Config.ARGB_4444);
                bitmap.setDensity(text1.getResources().getDisplayMetrics().densityDpi);
                Canvas canvas = new Canvas(bitmap) ;
                text1.draw(canvas);
                imageView.setImageBitmap(bitmap);

But if I try the same code for the Parent View i.e Scroll View it gives Exception

Caused by: java.lang.IllegalArgumentException: width and height must be > 0

I want to Capture the whole Scroll View And save it to Internal Drive !! Thanks in Advance

Compare and sort Word entities (starting with vowel symbols) by consonants Java

I have a hierarchy of classes Symbol, Word, Sentence, Text. Each class just contains a field with setters, getters, overridden equals and toString. These classes are kind of nested in each other by lists. It looks like this:

public class Word {
    private List<Symbol> symbols;
    public Word(List<Symbol> symbols) {
        this.symbols = symbols;
    }
    //getters, setters, toString
}

I need to find the words in the text which start from the vowel letter and sort them according to the consonant letter which goes after the vowel. I have been trying to get sentences and words from the text and then defined the words I need to sort. However, I do not know how to change compare in my helper method sort so it could actually compare consonant letters.

public void sortWords(Text text) {
        List<Sentence> sentences = text.getSentences();
        List<Word> words = new ArrayList<>();
        for (Sentence sentence : sentences) {
            words.addAll(sentence.getWords());
        }
        List<Symbol> symbols = new ArrayList<>();
        for (Word word : words) {
            symbols = word.getSymbols();
            Symbol first = symbols.get(0);
            if (first.isVowel()) {
                sort(words);
            }
        }
    }


    private void sort(List<Word> words) {
        Collections.sort(words, new Comparator<Word>() {

            @Override
            public int compare(Word word1, Word word2) {
                List<Symbol> symbols = word1.getSymbols();

                for (Symbol s : symbols) {
                    if (s.isConsonant()){

                    }
                }
            }

I would be grateful for any advice!
        });
    }

IllegalArgumentException on deserialization SetMultiMap

I’m having some trouble when deserializing my SetMultiMap from a json file. The serialization works.

public static <T> T readJSON(String file, TypeToken<T> type) {
    try {
        return GSON.fromJson(new FileReader(INSTANCE.getDataFolder().getAbsolutePath() + File.separator + file + ".json"), type.getType());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public static <T> void writeJSON(String file, T t) {
    try (OutputStream os = new FileOutputStream(INSTANCE.getDataFolder().getAbsolutePath() + File.separator + file + ".json")) {
        os.write(GSON.toJson(t).getBytes());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Im using these methods here.

UPGRADES.putAll(Multimaps.newSetMultimap(Utility.readJSON("upgrades", new TypeToken<Map<String, Collection<Upgrade>>>() {
    }), HashSet::new));

and here:

Utility.writeJSON("upgrades", UPGRADES.asMap());

Im getting this error upon trying to load the data from a json file into the UPGRADES map:

java.lang.IllegalArgumentException
    at com.google.common.base.Preconditions.checkArgument(Preconditions.java:111) ~[spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at com.google.common.collect.AbstractMapBasedMultimap.<init>(AbstractMapBasedMultimap.java:123) ~[spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at com.google.common.collect.AbstractSetMultimap.<init>(AbstractSetMultimap.java:44) ~[spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at com.google.common.collect.Multimaps$CustomSetMultimap.<init>(Multimaps.java:281) ~[spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at com.google.common.collect.Multimaps.newSetMultimap(Multimaps.java:272) ~[spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at com.gb6.factionupgrades.Main.onEnable(Main.java:34) ~[?:?]
    at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340) [spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:357) [spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:317) [spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at net.minecraft.server.v1_8_R3.MinecraftServer.s(MinecraftServer.java:414) [spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at net.minecraft.server.v1_8_R3.MinecraftServer.k(MinecraftServer.java:378) [spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at net.minecraft.server.v1_8_R3.MinecraftServer.a(MinecraftServer.java:333) [spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at net.minecraft.server.v1_8_R3.DedicatedServer.init(DedicatedServer.java:263) [spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:525) [spigot-1.8.8-R0.1-SNAPSHOT.jar:git-Spigot-21fe707-e1ebe52]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_131]

Any help is greatly appreciated.

Confusion in functioning of Lambda expression

I am trying to learn lambda expressions. I am currently referring to OCP study guide.

In one example of lambda expression there is a Animal class and another another interface called CheckTrait. The functioning of lambda expression is very confusing for me. Example code is as shown below:

Without lambda expression.

public interface CheckTrait {
    public boolean test(Animal a);
}


public class Animal  implements CheckTrait{

    private String species;
    private boolean canHop;
    private boolean canSwim;

    public Animal(String species, boolean canHop, boolean canSwim) {
        super();
        this.species = species;
        this.canHop = canHop;
        this.canSwim = canSwim;
    }

    public boolean canHop() {
        return this.canHop;
    }

    public String toString() {
        return species;
    }

    public boolean canSwim() {
        return this.canSwim;
    }

    @Override
    public boolean test(Animal a) {

        return a.canHop();
    }
}

    public class FindMathcingAnimals {

    private static void print(Animal animal, CheckTrait trait) {
        if(trait.test(animal)){
            System.out.println(animal+" can hop" );
        }else {
            System.out.println(animal+" cannot hop");
        }

    }

    public static void main(String[] args) {

        Animal animal2= new Animal("Kangaroo", true, false);    
        print(animal2,animal2);
    }

}

When we run the above class we get the output as Kangaroo can hop

With lambda expression

public interface CheckTrait {
    public boolean test(Animal a);
}


public class Animal  {

    private String species;
    private boolean canHop;
    private boolean canSwim;

    public Animal(String species, boolean canHop, boolean canSwim) {
        super();
        this.species = species;
        this.canHop = canHop;
        this.canSwim = canSwim;
    }

    public boolean canHop() {
        return this.canHop;
    }

    public String toString() {
        return species;
    }

    public boolean canSwim() {
        return this.canSwim;
    }


}


public class FindMathcingAnimals {

    private static void print(Animal animal, CheckTrait trait) {
        if(trait.test(animal)){
            System.out.println(animal+" can hop" );
        }else {
            System.out.println(animal+" cannot hop");
        }

    }

    public static void main(String[] args) {

        Animal animal2= new Animal("Kangaroo", true, false);    
        print(animal2,s->s.canHop());
    }

}

My Question is, In the below line
print(animal2,s->s.canHop());

I am not passing any value to s but just an expression, then how is the program computing the result? I am aware that it is taking the animal object and checking the canhop variable just by intuition,but I am not understanding the logic here. Kindly provide your thoughts.

Edit: from the below answers:

So, can i conclude that.
In the print method I am passing the behavior for CheckTrait, and in the print method can be reduced as:

step1: if(trait.test(animal)){

step2: if(s.canHop())

step3: if(anaimla.canHop)

the above steps are just for my understanding.

Encrypting Strings in Java the same as Swift App – Crypto Swift

I have made and published a Swift App to the iOS App Store. This app uses Crypto Swift to encrypt users personal information and then uploads this to Firebase.

I’m now trying to make the same app on Android using Android Studio. The problem is that I can’t find a way to encrypt and decrypt a String like “hello” the exact same way. Since they both will be connected to the same server and requests for other users information it is vital that the encryption on both platforms yield exactly the same String after encryption.

The code for the Swift encryption:

import CryptoSwift
import RNCryptor

class ViewController: UIViewController {

override func viewDidLoad() {
        super.viewDidLoad()

 let key = "testtesttesttest"
 let iv = "test123ivtest123"

 let stringinput = "test string"         

 let encryptedstringoutput = try! stringinput.aesEncrypt(key: key, iv: iv)
//Upload to Firebase
}

}

I’ve tried code like this but it doesn’t work because I get this error on the import java.util.Base64; line.

Usage of API documentation as @since 1.8+

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.util.Base64;

public class Encryptor {
    public static String encrypt(String key, String initVector, String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            System.out.println("encrypted string: "
                    + Base64.encodeBase64String(encrypted));

            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static String decrypt(String key, String initVector, String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String key = "Bar12345Bar12345"; // 128 bit key
        String initVector = "RandomInitVector"; // 16 bytes IV

        System.out.println(decrypt(key, initVector,
                encrypt(key, initVector, "Hello World")));
    }
}

How can I replicate the exact same output in Java?

Convert Java object to JsonNode with change in SerializationConfig per request

I am trying to convert a Java Object to TreeNode as follows.

mapper.setConfig(mapper.getSerializationConfig().with(contextAttributes));
mapper.valueToTree(object);

There is a single objectMapper instance.
So for each request there is a change in objectMapper serialisation config. This is causing concurrency issues since one thread may overwrite the config of mapper set by the previous one. I can’t create a new ObjectMapper instance for each request. I can’t create even a copy of it as according to ObjectMapper javadoc creating a copy of ObjectMapper is as expensive as creating an new instance.

empty dataTable, Maven JPA JSF

I have a Maven project with JSF framework.I want to extract data from the database to dataTable. But I don’t extract. I will share my codes. But these codes works correctly normal Jsf web application (not maven).

It is jpa controller class

public class usersController {

EntityManager em;
EntityManagerFactory emf;
private List<Users> users = new ArrayList<>();

public usersController() {
    emf = Persistence.createEntityManagerFactory("com.ozgur_MavenJSF_war_1.0-SNAPSHOTPU");
    em = emf.createEntityManager();
    em.getTransaction().begin();
}

public List<Users> getUsers() {
    try {
        users = em.createNamedQuery("Users.findAll", Users.class).getResultList();
        return users;
    } catch (Exception e) {
        return users;
    }
}
}

It is Managed Beans class

@Named(value = "usersBeans")
@SessionScoped
public class usersBeans implements Serializable {

    private List<Users> users = new ArrayList<>();
    private usersController userController = new usersController();

    public usersBeans() {
    }

    public List<Users> getAll() {
        users = userController.getUsers();
        return users;
    }
}

It is xhtml file

<h:form>
    <h:dataTable value="#{usersBeans.getAll()}" var="users">
        <h:column>                  
            <f:facet name = "header">Id</f:facet>                   
                #{users.id}
        </h:column>

        <h:column>
            <f:facet name = "header">Name</f:facet>
                #{users.userName}
        </h:column>

        <h:column>
            <f:facet name = "header">Surname</f:facet>
                #{users.userSurname}
        </h:column>

        <h:column>
            <f:facet name = "header">Address</f:facet>
                #{users.userAddress}
        </h:column>
        <h:column>
            <f:facet name = "header">Phone</f:facet>
                #{users.userPhone}
        </h:column>
    </h:dataTable>
</h:form>

persistence.xml is correct

In xhtml file, <h:dataTable value="#{usersBeans.getAll()}" var="users"> Even If I write something ridiculous in value, it does not give an error. I just see an empty table. But these codes works correctly normal Jsf Web app.

Thank you in advance for your help.