AS: Avoid the physical back button Android

I want to avoid that the android users play my game and get gameover, that they simply click the back button and come back to the game.

This is my code from jumping of my GameActivity to jump into the new GameOver Activity. What a command could I use? I simply want to come back to the main activity not the gameActivity.

private void checkFails(){
    TextView failsleft = (TextView) findViewById(R.id.fails);
    if(fails < 1){
        failsleft.setText("Fails left: "+fails);
        Intent intent = new Intent(this, GameOverActivity.class);
        startActivity(intent);

    }else{
        failsleft.setText("Fails left: "+fails);
        fails--;
    }
}

Scanner class’ hasNext() on infinite loop

I’m trying to write code that uses the Scanner class to get input from the user. But hasNext(), hasNextInt(), and hasNextLine() all run into infinite loops every time.

public static void getInput(ArrayList<Double> arr){

       Scanner input = new Scanner(System.in);
       String data = "";
       String init;
       while(input.hasNextLine()){
           init = input.nextLine();
           data += init;
       }
       .
       .
       .
   }

apache camel file2 removes file while java stream is reading the file

I have a camel file2 dropbox listener to detect a file and then read other files in the same directory. Apache Camel will add a .camelLock marker when the file is detected and removes it withing few seconds.
Now the problem is, in very occasional cases my code detects the .camelLock file (as it is not deleted by camel yet) and before it finishes the following method, camel removes the file. So my method returns java.io.UncheckedIOException: java.nio.file.NoSuchFileException

Here is the documentation to camel file2: http://camel.apache.org/file2.html

private List<String> getFileNames(String fullPath) throws IOException {
        try (Stream<Path> pathStream = Files.walk(Paths.get(fullPath))) {

            return pathStream.filter(Files::isRegularFile)
                    .filter(f -> !f.toString().toLowerCase()
                            .endsWith("camellock"))
                    .map(Path::toString)
                    .map(f -> f.substring(f.lastIndexOf(File.separator) + 1, f.length()))
                    .collect(Collectors.toList());
        }

}

Any idea?

Running jar through .bat works in downloading files but not if running it directly by the .jar

I’ve written a .jar application to auto update it from my site. It works when I execute the .jar through a .bat , but when running the .jar directly, its unable to download the file from my site?

My code is:

try {
String location = getDir() + fileName;
dest = new BufferedOutputStream(new FileOutputStream(location)); 

download = url.openConnection();
readFileToDownload = download.getInputStream();
byte[] data = new byte[1024];
int numRead;
long numWritten = 0;
int length = download.getContentLength();

while ((numRead = readFileToDownload.read(data)) != -1) {
dest.write(data, 0, numRead);
numWritten += numRead;
int percent = (int)(((double)numWritten / (double)length) * 100D);
System.out.println(percent);
}

} catch (Exception exception) {
System.out.println("Download failed!");
}

I’m totally lost how the .jar works completely but just doesn’t do this function, unless I run it with a .bat (which executes the .jar)

How to make a spring boot app with tomcat embeded be able to run at weblogic?

I am trying to run my spring boot app (made through Jhipster) on a web logic server.

It works great with its embeded tomcat, but once I remove the tomcat dependency I start to see more errors.

Currently this one:

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:repackage (default) on project myproject: Execution default of goal org.springframework.boot:spr
ing-boot-maven-plugin:1.5.9.RELEASE:repackage failed: Unable to find main class -> [Help 1]

This happens after I removed

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

Is there any way I can package my app to make it run on weblogic? I am novice when talking about WL.

Any idea?

Why isn’t it prohibited to access static methods in a non-static way?

Is there any possible case that calling static method in a non-static way is useful and more desirable than calling it in a static way? What is the purpose of not forbidding that practise as it might generate more confusing code? I’m aware that compiler generates warning when calling static method in an instance method way, but wouldn’t it be more clear to simply not allow that kind of situations and generate error by compiler? See these simple two examples:

public class MyClass {
    public static void test() {
        System.out.println("test");
    }

    public static void main(String[] args) {
        MyClass mc = new MyClass();
        mc.test(); // prints "test"
    }
}

Calling MyClass.test() instead of mc.test() is clear and doesn’t need any further explanations as you immediately notice that you deal with static method, when mc.test() generates a bit of confusion.

Another example is a little bit more tricky as inheritance come into play.

class Parent {
    public void test() {
        System.out.println("test in Parent");
    }
}

class Child extends Parent {
    public void test() {
        System.out.println("test in Child");
    }
}

public class MyClass {
    public static void main(String[] args) {
        Child child = new Child();
        child.test();  // prints "test in Child"

        Parent parent = new Child();
        parent.test(); // prints "test in Child"
    }
}

Due to dynamic method binding, in both cases „test in Child” is printed. But when changing test() methods to make them static, results look different (due to static method binding):

public static void main(String[] args) {
    Child child = new Child();
    child.test();  // prints "test in Child"

    Parent parent = new Child();
    parent.test(); // prints "test in Parent"
}

As we see, calling static method in a non-static way might be really confusing and be source of potential error when developer expects that the child method will be called due to polymorphism but the parent one is being called.

So, maybe a bit of curiosity:

Are there any possible situations when calling static method in a non-static way is desirable and is better than calling it in a static way?

Handler randomly stops updating setText

I made a runnable stopwatch, it works and updates the time correctly most of the time. But sometimes when I switch to another fragment and then switch back it will run for a random amount of seconds (anywhere from 2-15) and then stop. The handler is still running but the text is not being updated. When I switch fragments again and back and it skips to the correct time and then resumes ticking. It’s very strange because it doesn’t do this every time I switch fragments, but it’s happening fairly often.

//code in fragment 1 class
 start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (!MainActivity.timeOn && spinner.getSelectedItem()!=null){

                MainActivity.timeOn=true;
                if(MainActivity.timeOn) {
                    MainActivity.paused = false;
                    MainActivity.stopTime=false;
                    MainActivity.StartTime = SystemClock.uptimeMillis();
                    MainActivity.handler.postDelayed(MainActivity.runnable, 0);


                }

            }}
    });

//code in main Activity class
  public static Runnable runnable = new Runnable() {

    public void run() {

        MillisecondTime = SystemClock.uptimeMillis() - StartTime;

        UpdateTime = TimeBuff + MillisecondTime;

        Seconds = (int) (UpdateTime / 1000);

        Minutes =1 +( Seconds / 60);

        Hours = Minutes / 60;

        Seconds = Seconds % 60;

        MilliSeconds = (int) (UpdateTime % 1000);

        minuteSum = (Hours * 60) + Minutes;
        minuteSumDaily = (Hours * 60) + Minutes;


        textView.setText("" + Hours + ":"
                + String.format("%02d", Minutes) + ":"
                + String.format("%02d", Seconds));


        handler.postDelayed(this, 0);


    }

};

unzip a .zip file in hadoop using java

I have a .zip file into the hadoop cluster named ‘test.zip’. I am trying to unzip it into the hadoop cluster and store it under the name test.txt but, file is not getting unzipped and my below code is not giving me any error.

public static void unZipIt(Configuration conf, String uri, String outputFolder) throws IOException {
        byte[] buffer = new byte[2048];
        //uri: path of the hadoop cluster: hdfs://localhost:8000/test/
        Path inputPath = new Path(uri);
        FileSystem fs = inputPath.getFileSystem(conf);
        FSDataInputStream inputStream = fs.open(inputPath);
        ZipInputStream zis = new ZipInputStream(inputStream);
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            System.out.println(outputFolder);
            File newFile = new File(outputFolder + "/" + fileName);
            System.out.println(newFile);
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    }

I don’t know where I am making an error. Please help.

PS: use any sample zip file for the code.

Jackson databind JSON boolean conversion

I’m using Jackson objectMapper to convert a JSON to an object and do some transformations and converting it back to JSON.

The JSON is like { "id":"abc1243", "val":1, "isDel":true}

In the above val is int and isDel is boolean.

My object is defined as below

public class MyObj{
  private String id;
  private String val;
  private String isDel;
   //getters and setters

}

When I convert the JSON to the MyObj, the String id and Int val are bound into the String but the boolean is not binded and hence I get null.

Im using the below approach

   ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    try {
        MyObj myObj = mapper.readValue(new File("/Users/sample.json"), MyObj.class);
}

May I know why the boolean is not binded to the String member.